text
stringlengths
28
935k
meta
stringlengths
137
139
red_pajama_subset
stringclasses
1 value
\section{Introduction} Starting from the 1960s people have invented many barcode types which serve for machine readable data representation and have lots of applications in various fields. The most frequently used are probably UPC and EAN barcodes for consumer products labeling, EAN128 serves for transferring information about cargo between enterprises, QR codes are widely used to provide links, PDF417 has variety of applications in transport, identification cards and inventory management. Barcodes have become ubiquitous in modern world, they are used as electronic tickets, in official documents, in advertisement, healthcare, for tracking objects and people. Examples of popular barcode types are shown in Fig.~\ref*{fig:barcode_samples}. \begin{figure} \centering \begin{subfigure}[b]{0.33\linewidth} \includegraphics[width=0.9\textwidth]{images/barcode_samples/Aztec.png} \caption{Aztec} \label{fig:gull} \end{subfigure}% \begin{subfigure}[b]{0.33\linewidth} \includegraphics[width=0.9\textwidth]{images/barcode_samples/Codabar.png} \caption{Codabar} \label{fig:gull2} \end{subfigure}% \begin{subfigure}[b]{0.33\linewidth} \includegraphics[width=0.9\textwidth]{images/barcode_samples/Code_93.png} \caption{Code 93} \label{fig:gull2} \end{subfigure}% \begin{subfigure}[b]{0.33\linewidth} \includegraphics[width=0.9\textwidth]{images/barcode_samples/DataMatrix.png} \caption{DataMatrix} \label{fig:gull2} \end{subfigure}% \begin{subfigure}[b]{0.33\linewidth} \includegraphics[width=0.9\textwidth]{images/barcode_samples/MaxiCode.png} \caption{MaxiCode} \label{fig:gull2} \end{subfigure}% \begin{subfigure}[b]{0.33\linewidth} \includegraphics[width=0.9\textwidth]{images/barcode_samples/QRCode.png} \caption{QRCode} \label{fig:gull2} \end{subfigure}% \begin{subfigure}[b]{0.33\linewidth} \includegraphics[width=0.9\textwidth]{images/barcode_samples/PDF417.png} \caption{PDF417} \label{fig:gull2} \end{subfigure}% \begin{subfigure}[b]{0.33\linewidth} \includegraphics[width=0.9\textwidth]{images/barcode_samples/upca.png} \caption{UPC-A} \label{fig:gull2} \end{subfigure}% \begin{subfigure}[b]{0.33\linewidth} \includegraphics[width=0.9\textwidth]{images/barcode_samples/patchcode.png} \caption{PatchCode} \label{fig:gull2} \end{subfigure}% \begin{subfigure}[b]{0.5\linewidth} \includegraphics[width=0.9\textwidth]{images/barcode_samples/Standard_2_of_5.png} \caption{Standard 2 of 5} \label{fig:gull2} \end{subfigure}% \begin{subfigure}[b]{0.5\linewidth} \includegraphics[width=0.9\textwidth]{images/barcode_samples/PostNet.png} \caption{Postnet} \label{fig:gull2} \end{subfigure}% \caption{Some examples of different barcodes} \label{fig:barcode_samples} \end{figure} There are two main approaches for decoding barcodes, the former uses laser and the latter just a simple camera. Through years of development, laser scanners have become very reliable and fast for the case of reading exactly one 1D barcode, but they are completely unable to deal with 2D barcodes or read several barcodes at the same time. Another drawback is that they can not read barcodes from screens efficiently as they strongly rely on reflected light. Popular camera-based reader is a simple smartphone application which is capable of scanning almost any type of barcode. However, most applications require some user guidance like pointing on barcode to decode. Most applications decode only one barcode at a time, despite it is possible to decode all barcodes in the image. It may become important when we need to scan barcodes from some official documents where might be a number of them. In this work, we introduce segmentation based barcode detector which is capable of locating all barcodes simultaneously no matter how many of them are present in the image or which types they are, so the system does not need any user guidance. The developed detector also provides information about most probable types of detected barcodes thus decreasing time for reading process. \section{Related Work} The early work in the domain of barcode detection from 2D images was motivated by the wide spread of mobile phones with cameras. \cite{Ohbuchi} proposes a method for finding 2D barcodes via corner detection and 1D barcodes through spiral scanning. \cite{Wachefeld} introduces another method for 1D barcode detection based on decoding. Both approaches however require certain guidance from the user. In more recent papers authors pay more attention on developing solutions which can be done automatically with less user guidance. \cite{Gallo2011Reading1B} finds regions with high difference between x and y derivatives, \cite{Tekin2013} calculates oriented histograms to find patches with dominant direction, \cite{Katona2013Efficient1A} relies on morphology operations to detect both 1D and 2D barcodes, reporting high accuracy on their own data. The work of S\"{o}r\"{o}s \emph{et al.} \cite{Soros2013} is notable as they compare their own algorithm with other works mentioned in this paragraph. They demonstrate that their approach is superior on the same dataset WWU Muenster Barcode Database (Muenster). Their algorithm is based on the idea that 1D barcodes have many edges, 2D barcodes have many corners, while text areas have both many edges and many corners. The work of Cresot \emph{et al.}, 2015 \cite{Cresot2015} is a solid baseline for 1D barcode detection. They evaluated their approach on Muenster and on extended ArTe-Lab 1D Medium barcode database (Artelab) provided by Zamberletti \emph{et al.} \cite{Zamberletti_2013} outperforming him on both datasets. The solution in \cite{Cresot2015} seems to outperform \cite{Soros2013} despite it is hard to compare as they were evaluated on different datasets using slightly different metrics. Cresot's algorithm detects dark bars of barcodes using Maximal Stable Extremal Regions (MSER) followed by finding imaginary perpendicular to bars center line in Hough space. In 2016 Cresot \emph{et al.} came with a new paper \cite{Cresot2016} improving previous results using a new variant of Line Segment Detector instead of MSER, which they called Parallel Segment Detector. \cite{Namane2017} proposes another bars detection method for 1D barcode detection, which is reported to be absolutely precise in real-time applications. In the recent years neural networks show very promising results in many domains including Computer Vision. However, at the moment of writing there are only a few research works which utilize deep learning for barcode detection. The first is already mentioned \cite{Zamberletti_2013} where neural network analyzes Hough space to find potential bars. More recent and promising results are obtained in \cite{YoloBarcode} where authors use YOLO (You Only Look Once) detector to find rectangles with barcodes, then apply another neural network to find the rotation angle of that barcode, thus after that they are able to rotate the barcode and pass it to any barcode recognizer simplifying the recognition task. They showed new state-of-the-art (SOTA) results on Muenster dataset. However, their solution can not be considered real-time for CPUs. Moreover, YOLO is known to have problems with narrow but very long objects, which can be an issue for some barcode types. \section{Detection via segmentation} Our approach is inspired by the idea of PixelLink \cite{Deng2018PixelLinkDS} where authors solve text detection via instance segmentation. We believe that for barcodes the situation when 2 of them are close to each other is unusual, so we do not really need to solve instance segmentation problem therefore dealing with semantic segmentation challenge should be enough. PixelLink shows good results capturing long but narrow lines with text, which can be a case for some barcode types so we believe such object shape invariance property is an additional advantage. To solve the detection task we first run semantic segmentation network and then postprocess its results. \subsection{Semantic segmentation network} \begin{table*}[t] \caption{Model architecture, C=24 is the number of channels and N is the number of predicted classes (barcode types)} \label{segmentation_network} \begin{center} \begin{small} \begin{sc} \begin{tabular}{l|ccc|cccccc|c} \toprule & \multicolumn{3}{c|}{Downscale Module} & \multicolumn{6}{c|}{Context Module} & Final \\ Layer & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 \\ \midrule Stride & 2 & 1 & 2 & 1 & 1 & 1 & 1 & 1 & 1 & 1 \\ Dilation & 1 & 1 & 1 & 1 & 2 & 4 & 8 & 16 & 1 & 1 \\ Separable & Yes & Yes & Yes & No & No & No & No & No & No & No \\ Kernel & 3x3 & 3x3 & 3x3 & 3x3 & 3x3 & 3x3 & 3x3 & 3x3 & 3x3 & 1x1 \\ Output Channels & C & C & C & C & C & C & C & C & C & 1+N \\ Receptive Field & 3x3 & 7x7 & 11x11 & 19x19 & 35x35 & 67x67 & 131x131 & 259x259 & 267x267 & 267x267 \\ \bottomrule \end{tabular} \end{sc} \end{small} \end{center} \vskip -0.15in \end{table*} Barcodes normally can not be too small so predicting results for resolution 4 times lower than original image should be enough for reasonably good results. Thus we find segmentation map for superpixels which are 4x4 pixel blocks. Detection is a primary task we are focusing on in this work, treating type classification as a less important sidetask. Most of barcodes share a common structure so it is only natural to classify pixels as being part of barcode (class 1) or background (class 0), thus segmentation network solves binary (super)pixel classification task. Barcodes are relatively simple objects and thus may be detected by relatively simple architecture. To achieve real-time CPU speed we have developed quite simple architecture based on dilated and separable convolutions (see \autoref*{segmentation_network}). It can be logically divided into 3 blocks: \begin{enumerate} \item \textbf{Downscale Module} is aimed to reduce spatial features dimension. Since these initial convolutions are applied to large feature maps they cost significant amount of overall network time, so to speed up inference these convolutions are made separable. \item \textbf{Context Module}. This block is inspired by \cite{Yu2015MultiScaleCA}. However, in our architecture it serves for slightly different purpose just improving features and exponentially increasing receptive field with each layer. \item Final classification layer is 1x1 convolution with number of filters equal to 1+n\_classes, where n\_classes is number of different barcode types we want to differentiate with. \end{enumerate} We used ReLU nonlinearity after each convolution except for the final one where we apply sigmoid to the first channel and softmax to all of the rest channels. We have chosen the number of channels $C=24$ for all convolutional layers. Our experiments show that with more filters model has comparable performance, but with less filters performance drops rapidly. As we have only a few channels in each layer the final model is very compact with only 32962 weights. As the maximal image resolution we are working with is 512x512, receptive field for prediction is at least half an image which should be more than enough contextual information for detecting barcodes. \subsection{Detecting barcodes based on segmentation} After the network pass we get segmentation map for superpixels with $1+n\_classes$ channels. For detection we use only the first channel which can be interpreted as probability being part of barcode for superpixels. We apply the threshold value for probability to get detection class binary labels (barcode/background). In all our experiments we set this threshold value to 0.5. We now find connected components on received superpixel binary mask and calculate bounding rectangle of minimal area for each component. To do the latest we apply \textit{minAreaRect} method from \textit{OpenCV} library (accessed Dec 2018). Now we treat found rectangles as detected barcodes. To get detection rectangle on original image resolution we multiply all of its vertices coordinates by the network scale 4. \subsection{Filtering results} To avoid a situation when a small group of pixels is accidentally predicted as a barcode, we filter out all superpixel connected components with area less than threshold $T_{area}$. The threshold value should be chosen to be slightly less than minimal area of objects in the dataset on the segmentation map. In all of our experiments we used value $T_{area}=20$. \subsection{Classification of detected objects} To determine barcode type of detected objects we use all of the rest $n\_classes$ channels from segmentation network output. After softmax we treat them as probabilities of being some class. Once we found the rectangle we compute the average probability vector inside this rectangle, then naturally choose the class with the highest probability. \section{Optimization scheme} \subsection{Loss function} The training loss is a weighted sum of detection and classification losses \begin{equation} L = L_{detection} + \alpha L_{classification} \end{equation} Detection loss $L_{detection}$ itself is a weighted sum of three components: mean binary crossentropy loss on positive pixels $L_{p}$, mean binary crossentropy loss on negative pixels $L_{n}$, and mean binary crossentropy loss on worst predicted $k$ negative pixels $L_{h}$, where $k$ is equal to the number of positive pixels in image. \begin{equation} L_{detection} = w_{p} L_{p} + w_{n} L_{n} + w_{h} L_{h} \end{equation} Classification loss is mean (categorical) crossentropy computed by all channels except the first one (with detection). Classification loss is calculated only on superpixels which are parts of ground truth objects. As our primary goal is high recall in detection we have chosen $w_p=15$, $w_n=1$, $w_h=5$, $\alpha=1$. We also tried several different configurations but this combination was the best among them. However, we did not spent too much time on hyperparameter search. \subsection{Data augmentation} For augmentation we do the following: \begin{enumerate} \item with (p=0.1) return original nonaugmented image \item with (p=0.5) rotate image random angle in [-45, 45] \item with (p=0.5) rotate image on one of 90, 180, 270 degrees \item with (p=0.5) do random crop. We limit crop to retain all barcodes on the image entirely and ensure that aspect ratio is changed no more than 70\% compared to the original image \item with (p=0.7) do additional image augmentation. For this purpose we used "less important" augmenters from heavy augmentation example from \textit{imgaug} library \cite{imgaug}. \end{enumerate} \section{Experimental results} \subsection{Datasets} The network performance was evaluated on 2 common benchmarks for barcode detection - namely WWU Muenster Barcode Database (Muenster) and ArTe-Lab Medium Barcode Dataset (Artelab). Datasets contain 595 and 365 images with ground truth detection masks respectively, resolution for all images is 640x480. All images in Artelab dataset contain exactly one EAN13 barcode, while in Muenster there may be several barcodes on the image. \begin{figure*} \centering \begin{subfigure}[b]{0.125\linewidth} \includegraphics[width=1.0\textwidth]{images/model_success/1.jpg} \end{subfigure}% \begin{subfigure}[b]{0.125\linewidth} \includegraphics[width=1.0\textwidth]{images/model_success/2.jpg} \end{subfigure}% \begin{subfigure}[b]{0.125\linewidth} \includegraphics[width=1.0\textwidth]{images/model_success/3.jpg} \end{subfigure}% \begin{subfigure}[b]{0.125\linewidth} \includegraphics[width=1.0\textwidth]{images/model_success/4.jpg} \end{subfigure}% \begin{subfigure}[b]{0.125\linewidth} \includegraphics[width=1.0\textwidth]{images/model_success/5.jpg} \end{subfigure}% \begin{subfigure}[b]{0.125\linewidth} \includegraphics[width=1.0\textwidth]{images/model_success/6.jpg} \end{subfigure}% \begin{subfigure}[b]{0.125\linewidth} \includegraphics[width=1.0\textwidth]{images/model_success/7.jpg} \end{subfigure}% \begin{subfigure}[b]{0.125\linewidth} \includegraphics[width=1.0\textwidth]{images/model_success/8.jpg} \end{subfigure}% \caption{Detection examples from test set} \label{fig:model_success} \end{figure*} \begin{figure*} \centering \begin{subfigure}[b]{0.2\linewidth} \includegraphics[width=0.99\textwidth]{images/model_errors/markup_failures/1_gt.png} \label{fig:gull2} \end{subfigure}% \begin{subfigure}[b]{0.2\linewidth} \includegraphics[width=0.99\textwidth]{images/model_errors/markup_failures/2_gt.png} \label{fig:gull2} \end{subfigure}% \begin{subfigure}[b]{0.2\linewidth} \includegraphics[width=0.99\textwidth]{images/model_errors/markup_failures/4_gt.png} \label{fig:gull2} \end{subfigure}% \begin{subfigure}[b]{0.2\linewidth} \includegraphics[width=0.99\textwidth]{images/model_errors/markup_failures/5_gt.png} \label{fig:gull2} \end{subfigure}% \begin{subfigure}[b]{0.2\linewidth} \includegraphics[width=0.99\textwidth]{images/border_overestimation_examples/0_gt.png} \label{fig:gull2} \end{subfigure}% \vskip -0.15in \begin{subfigure}[b]{0.2\linewidth} \includegraphics[width=0.99\textwidth]{images/model_errors/markup_failures/1_postpr.png} \label{fig:gull2} \end{subfigure}% \begin{subfigure}[b]{0.2\linewidth} \includegraphics[width=0.99\textwidth]{images/model_errors/markup_failures/2_postpr.png} \label{fig:gull2} \end{subfigure}% \begin{subfigure}[b]{0.2\linewidth} \includegraphics[width=0.99\textwidth]{images/model_errors/markup_failures/4_postpr.png} \label{fig:gull2} \end{subfigure}% \begin{subfigure}[b]{0.2\linewidth} \includegraphics[width=0.99\textwidth]{images/model_errors/markup_failures/5_postpr.png} \label{fig:gull2} \end{subfigure}% \begin{subfigure}[b]{0.2\linewidth} \includegraphics[width=0.99\textwidth]{images/border_overestimation_examples/0_postpr.png} \label{fig:gull2} \end{subfigure}% \ \caption{Detection examples: markup issues on Artelab and Muenster dataset. Markup on the top, detections results below} \label{fig:model_errors} \end{figure*} For training we used our own dataset with both 1D barcodes (Code128, Patch, EAN8, Code93, UCC128, EAN13, Industrial25, Code32, FullASCIICode, UPCE, MATRIX25, Code39, IATA25, UPCA, CODABAR, Interleaved25) and 2D barcodes (QRCode, Aztec, MaxiCode, DataMatrix, PDF417), being 16 different types for 1D and 5 types for 2D Barcodes, 21 type in total. Training dataset contains both photos and document scans. Example images from our dataset can be found in Fig.~\ref*{fig:model_success}. Dataset consist of 17k images in total, 10\% of it was used for validation. \subsection{Training procedure} We trained our model with batch size 8 for 70 epochs with learning rate 0.001 followed by additional 70 epochs with learning rate 0.0001 While training we resized all images to have maximal side at most 1024 maintaining aspect ratio and make both sides divisible by 64. We pick and augment/preprocess 3000 images from the dataset, then group them into batches by image size, and do this process repeatedly until the end of training. After that we pick next 3000 images and do the same until the end of the dataset. After we reach the end of the dataset, we shuffle image order and repeat the process. We trained three models: \textit{Ours-Detection (all types)} (without classification on entire dataset), \textit{Ours-Detection+Classification (all types)} (with classification on entire dataset), \textit{Ours-Detection (EAN13 only)} (without classification on EAN13 subset of 1000 images). \subsection{Evaluation metrics} We follow common evaluation scheme from \cite{Cresot2015}. Having binary masks $G$ for ground truth and $F$ for found detection results the Jaccard index between them is defined as $$J(G,F) = \frac{|G \cap F|}{|G \cup F|}$$ Another common name for Jaccard index is "intersection over union" or IoU which follows from definition. The overall detection rate for a given IoU threshold $T$ is defined as a fraction of images in the dataset where IoU is greater than that threshold $$D_{T} = \frac{\sum_{i \in S} I(J(G, F) \geq T))}{|S|}$$ where $S$ is set of images in the dataset and $I$ is indicator function. However, one image may contain several barcodes and if one of them is very big and another is very small $D_T$ will indicate error only on very high threshold, so we find it reasonable to evaluate detection performance with additional metrics which will average results not by images but by ground truth barcode objects on them. For this purpose we use recall $R_T$, defined as number of successfully detected objects divided by total number of objects in the dataset $$R_T = \frac{\sum_{i \in S}\sum_{G \in SG_i} I(J(G, F(G)) \geq T))}{\sum_{i \in S}|SG_i|}$$ where $SG_i$ is set of objects on ground truth on image $i$ and $F(G)$ is found box with highest Jaccard index with box $G$. The paired metric for recall is precision, defined as the number of successfully detected objects divided by total number of detections $$P_T = \frac{\sum_{i \in S}\sum_{G \in SG_i} I(J(G, F(G)) \geq T))}{\sum_{i \in S}|SF_i|}$$ where $SF_i$ is set of all detections made per image $i$. We found connected components for ground truth binary masks and treat them as ground truth objects. We emphasize that all the metrics above are computed for the detected object \textit{regardless its actual type}. To evaluate classification of the detected objects by type we use simple accuracy metric (number of correctly guessed objects / number of correctly detected objects). So if we find Barcode-PDF417 as Barcode-QRCode precision and recall will not be affected, but the classification accuracy will be. \subsection{Quantitative results} \begin{table*}[t] \caption{Result comparation on different datasets.} \label{table_artelab_muenster} \begin{center} \begin{small} \begin{sc} \begin{tabular}{l|cc|cc} \toprule & \multicolumn{2}{c|}{Muenster} & \multicolumn{2}{c}{Artelab}\\ & Acc $J_{avg}$ & Detection rate $D_{0.5}$ & Acc $J_{avg}$ & Detection rate $D_{0.5}$ \\ \midrule Cresot2015 & 0.799 & 0.963 & 0.763 & 0.893 \\ Cresot2016 & - & 0.982 & - & \textbf{0.989} \\ Yolo2017 & 0.873 & \textbf{0.991} & 0.816 & 0.926 \\ Namane2017 & \textbf{0.882} & 0.966 & \textbf{0.860} & 0.930 \\ \midrule Ours-Detection (all types) & 0.842 & 0.980 & 0.819 & \textbf{0.989} \\ Ours-Detection (EAN13 only) & 0.762 & 0.987 & 0.790 & \textbf{0.995} \\ \bottomrule \end{tabular} \end{sc} \end{small} \end{center} \end{table*} \begin{figure} \centering \includegraphics[width=0.9\linewidth]{images/graphs/artelab_detection_rate_curve_v2.png} \caption{Detection rate for different Jaccard index thresholds} \label{fig:detection_rate_artelab} \end{figure} \begin{figure} \centering \includegraphics[width=0.8\linewidth]{images/graphs/iou_custom_examples.png} \caption{Example of Jaccard index computation for various bounding boxes} \label{fig:iou_examples} \end{figure} We compare our results with Cresot2015 \cite{Cresot2015}, Cresot2016 \cite{Cresot2016}, Namane2017 \cite{Namane2017}, Yolo2017 \cite{YoloBarcode} on Artelab and Muenster datasets (\autoref*{table_artelab_muenster}). The proposed method is trained on our own dataset, however all other works which we compared with were trained on different datasets. As for the full reproducibility of other authors works on our dataset we have to follow the exactly same training protocol (including initialization and augmentations) to not underestimate the results we decided to rely on the numbers reported in works of other authors. We outperformed all previous works in terms of detection rate on Artelab dataset with the model trained only on EAN13 subset of our dataset. According to the tables, detection rate of our model trained on entire dataset with all barcode types is slightly worse than model trained on EAN13 subset. The reason for this is not poor generalization but markup errors or capturing more barcodes than in the markup (i. e. non-EAN barcodes), see Fig.~\ref*{fig:model_errors}. As it can be seen in Fig.~\ref*{fig:detection_rate_artelab} our model has a rapid decrease in detection rate for higher Jaccard thresholds. Aside from markup errors, the main reason for that is overestimation of barcode borders in detection, which is caused by prioritizing high recall in training, it makes high impact for higher Jaccard thresholds as Jaccard index is known to be very sensitive to almost exact match (Fig.~\ref*{fig:iou_examples}). On \autoref*{table_precision_recall} we show comparison of our models by precision and recall. Our models achieve close to an absolute recall, meaning that almost all barcodes are detected. On the other hand precision is also relatively high. \begin{table*}[t] \caption{Precision and recall of our approach on different datasets, Jaccard index threshold set to 0.5.} \label{table_precision_recall} \begin{center} \begin{small} \begin{sc} \begin{tabular}{l|cc|cc|cc|} \toprule & \multicolumn{2}{c|}{Muenster} & \multicolumn{2}{c|}{Artelab} & \multicolumn{2}{c|}{Test Multiclass} \\ & Precision & Recall & Precision & Recall & Precision & Recall \\ \midrule Ours-detection (all types) & 0.777 & 0.990 & 0.814 & 0.995 & 0.940 & 0.991 \\ Ours-detection+classification (all types) & \textbf{0.805} & 0.987 & \textbf{0.854} & 0.995 & \textbf{0.943} & \textbf{0.994} \\ Ours-detection (EAN13 only) & 0.759 & \textbf{1.000} & 0.839 & \textbf{0.997} & - & - \\ \bottomrule \end{tabular} \end{sc} \end{small} \end{center} \end{table*} \subsection{Execution time} \begin{table}[t] \caption{Inference time comparison} \label{table_time} \begin{center} \begin{small} \begin{sc} \begin{tabular}{lcc} \toprule & Execution time (ms) & Resolution \\ \midrule S\"{o}r\"{o}s \cite{Soros2013} & 73 & 960x723 \\ Cresot16 \cite{Cresot2016} & 40 & 640x480 \\ Yolo17 \cite{YoloBarcode} & 13.6 & 416x416 \\ Namane17 \cite{Namane2017} & 21 & 640x480 \\ Ours (GPU) & 3.8 & 512x512 \\ Ours (CPU) & 44 & 512x512 \\ \bottomrule \end{tabular} \end{sc} \end{small} \end{center} \end{table} For our network we measure time on 512x512 resolution which is enough for most of applications. We do not include postprocessing time as it is negligible compared to forward network run. The developed network performs at real-time speed and is 3.5 times faster than YOLO with darknet \cite{YoloBarcode} on higher resolution on the same GTX 1080 GPU. In the \autoref*{table_time} we compare inference times of our model with other approaches. We also provide CPU inference time (for Intel Core i5, 3.20GHz) of our model showing that it is nearly the same as reported in Cresot2016, where authors used their approach in the real-time smartphone application. It is important since not all of the devices have GPU yet. \subsection{Classification results} Among correctly detected objects we measured classification accuracy and achieved 60\% accuracy on test set. Moreover, classification subtask does not damage detection results. As shown in \autoref*{table_precision_recall} the results with classification are even slightly better, meaning that detection and classification tasks can mutually benefit from each other. \subsection{Capturing long narrow barcodes} Additional advantage of our detector is that it is capable of finding objects of any arbitrary shape and does not assume that objects should be approximately squares as done by YOLO. Some examples are provided in Fig.~\ref*{fig:model_success}. \section{Conclusion} We have introduced new barcode detector which can achieve comparable or better performance on public benchmarks and is much faster than other methods. Moreover, our model is universal barcode detector which is capable to detect both 1D and 2D barcodes of many different types. The model is very light with less than 33000 weights which can be considered very compact and suitable for mobile devices. Despite being shallow (i.e. very simple, we didn't use any SOTA techniques for semantic segmentation) our model shows that semantic segmentation may be used for object detection efficiently. It also provides natural way to detect objects of arbitrary shape (e.g. very long but narrow). Future work may include using more advanced approaches in semantic segmentation to develop better network architecture and increase performance. \bibliographystyle{IEEEtran} \section{Introduction} Starting from the 1960s people have invented many barcode types which serve for machine readable data representation and have lots of applications in various fields. The most frequently used are probably UPC and EAN barcodes for consumer products labeling, EAN128 serves for transferring information about cargo between enterprises, QR codes are widely used to provide links, PDF417 has variety of applications in transport, identification cards and inventory management. Barcodes have become ubiquitous in modern world, they are used as electronic tickets, in official documents, in advertisement, healthcare, for tracking objects and people. Examples of popular barcode types are shown in Fig.~\ref*{fig:barcode_samples}. \begin{figure} \centering \begin{subfigure}[b]{0.33\linewidth} \includegraphics[width=0.9\textwidth]{images/barcode_samples/Aztec.png} \caption{Aztec} \label{fig:gull} \end{subfigure}% \begin{subfigure}[b]{0.33\linewidth} \includegraphics[width=0.9\textwidth]{images/barcode_samples/Codabar.png} \caption{Codabar} \label{fig:gull2} \end{subfigure}% \begin{subfigure}[b]{0.33\linewidth} \includegraphics[width=0.9\textwidth]{images/barcode_samples/Code_93.png} \caption{Code 93} \label{fig:gull2} \end{subfigure}% \begin{subfigure}[b]{0.33\linewidth} \includegraphics[width=0.9\textwidth]{images/barcode_samples/DataMatrix.png} \caption{DataMatrix} \label{fig:gull2} \end{subfigure}% \begin{subfigure}[b]{0.33\linewidth} \includegraphics[width=0.9\textwidth]{images/barcode_samples/MaxiCode.png} \caption{MaxiCode} \label{fig:gull2} \end{subfigure}% \begin{subfigure}[b]{0.33\linewidth} \includegraphics[width=0.9\textwidth]{images/barcode_samples/QRCode.png} \caption{QRCode} \label{fig:gull2} \end{subfigure}% \begin{subfigure}[b]{0.33\linewidth} \includegraphics[width=0.9\textwidth]{images/barcode_samples/PDF417.png} \caption{PDF417} \label{fig:gull2} \end{subfigure}% \begin{subfigure}[b]{0.33\linewidth} \includegraphics[width=0.9\textwidth]{images/barcode_samples/upca.png} \caption{UPC-A} \label{fig:gull2} \end{subfigure}% \begin{subfigure}[b]{0.33\linewidth} \includegraphics[width=0.9\textwidth]{images/barcode_samples/patchcode.png} \caption{PatchCode} \label{fig:gull2} \end{subfigure}% \begin{subfigure}[b]{0.5\linewidth} \includegraphics[width=0.9\textwidth]{images/barcode_samples/Standard_2_of_5.png} \caption{Standard 2 of 5} \label{fig:gull2} \end{subfigure}% \begin{subfigure}[b]{0.5\linewidth} \includegraphics[width=0.9\textwidth]{images/barcode_samples/PostNet.png} \caption{Postnet} \label{fig:gull2} \end{subfigure}% \caption{Some examples of different barcodes} \label{fig:barcode_samples} \end{figure} There are two main approaches for decoding barcodes, the former uses laser and the latter just a simple camera. Through years of development, laser scanners have become very reliable and fast for the case of reading exactly one 1D barcode, but they are completely unable to deal with 2D barcodes or read several barcodes at the same time. Another drawback is that they can not read barcodes from screens efficiently as they strongly rely on reflected light. Popular camera-based reader is a simple smartphone application which is capable of scanning almost any type of barcode. However, most applications require some user guidance like pointing on barcode to decode. Most applications decode only one barcode at a time, despite it is possible to decode all barcodes in the image. It may become important when we need to scan barcodes from some official documents where might be a number of them. In this work, we introduce segmentation based barcode detector which is capable of locating all barcodes simultaneously no matter how many of them are present in the image or which types they are, so the system does not need any user guidance. The developed detector also provides information about most probable types of detected barcodes thus decreasing time for reading process. \section{Related Work} The early work in the domain of barcode detection from 2D images was motivated by the wide spread of mobile phones with cameras. \cite{Ohbuchi} proposes a method for finding 2D barcodes via corner detection and 1D barcodes through spiral scanning. \cite{Wachefeld} introduces another method for 1D barcode detection based on decoding. Both approaches however require certain guidance from the user. In more recent papers authors pay more attention on developing solutions which can be done automatically with less user guidance. \cite{Gallo2011Reading1B} finds regions with high difference between x and y derivatives, \cite{Tekin2013} calculates oriented histograms to find patches with dominant direction, \cite{Katona2013Efficient1A} relies on morphology operations to detect both 1D and 2D barcodes, reporting high accuracy on their own data. The work of S\"{o}r\"{o}s \emph{et al.} \cite{Soros2013} is notable as they compare their own algorithm with other works mentioned in this paragraph. They demonstrate that their approach is superior on the same dataset WWU Muenster Barcode Database (Muenster). Their algorithm is based on the idea that 1D barcodes have many edges, 2D barcodes have many corners, while text areas have both many edges and many corners. The work of Cresot \emph{et al.}, 2015 \cite{Cresot2015} is a solid baseline for 1D barcode detection. They evaluated their approach on Muenster and on extended ArTe-Lab 1D Medium barcode database (Artelab) provided by Zamberletti \emph{et al.} \cite{Zamberletti_2013} outperforming him on both datasets. The solution in \cite{Cresot2015} seems to outperform \cite{Soros2013} despite it is hard to compare as they were evaluated on different datasets using slightly different metrics. Cresot's algorithm detects dark bars of barcodes using Maximal Stable Extremal Regions (MSER) followed by finding imaginary perpendicular to bars center line in Hough space. In 2016 Cresot \emph{et al.} came with a new paper \cite{Cresot2016} improving previous results using a new variant of Line Segment Detector instead of MSER, which they called Parallel Segment Detector. \cite{Namane2017} proposes another bars detection method for 1D barcode detection, which is reported to be absolutely precise in real-time applications. In the recent years neural networks show very promising results in many domains including Computer Vision. However, at the moment of writing there are only a few research works which utilize deep learning for barcode detection. The first is already mentioned \cite{Zamberletti_2013} where neural network analyzes Hough space to find potential bars. More recent and promising results are obtained in \cite{YoloBarcode} where authors use YOLO (You Only Look Once) detector to find rectangles with barcodes, then apply another neural network to find the rotation angle of that barcode, thus after that they are able to rotate the barcode and pass it to any barcode recognizer simplifying the recognition task. They showed new state-of-the-art (SOTA) results on Muenster dataset. However, their solution can not be considered real-time for CPUs. Moreover, YOLO is known to have problems with narrow but very long objects, which can be an issue for some barcode types. \section{Detection via segmentation} Our approach is inspired by the idea of PixelLink \cite{Deng2018PixelLinkDS} where authors solve text detection via instance segmentation. We believe that for barcodes the situation when 2 of them are close to each other is unusual, so we do not really need to solve instance segmentation problem therefore dealing with semantic segmentation challenge should be enough. PixelLink shows good results capturing long but narrow lines with text, which can be a case for some barcode types so we believe such object shape invariance property is an additional advantage. To solve the detection task we first run semantic segmentation network and then postprocess its results. \subsection{Semantic segmentation network} \begin{table*}[t] \caption{Model architecture, C=24 is the number of channels and N is the number of predicted classes (barcode types)} \label{segmentation_network} \begin{center} \begin{small} \begin{sc} \begin{tabular}{l|ccc|cccccc|c} \toprule & \multicolumn{3}{c|}{Downscale Module} & \multicolumn{6}{c|}{Context Module} & Final \\ Layer & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 \\ \midrule Stride & 2 & 1 & 2 & 1 & 1 & 1 & 1 & 1 & 1 & 1 \\ Dilation & 1 & 1 & 1 & 1 & 2 & 4 & 8 & 16 & 1 & 1 \\ Separable & Yes & Yes & Yes & No & No & No & No & No & No & No \\ Kernel & 3x3 & 3x3 & 3x3 & 3x3 & 3x3 & 3x3 & 3x3 & 3x3 & 3x3 & 1x1 \\ Output Channels & C & C & C & C & C & C & C & C & C & 1+N \\ Receptive Field & 3x3 & 7x7 & 11x11 & 19x19 & 35x35 & 67x67 & 131x131 & 259x259 & 267x267 & 267x267 \\ \bottomrule \end{tabular} \end{sc} \end{small} \end{center} \vskip -0.15in \end{table*} Barcodes normally can not be too small so predicting results for resolution 4 times lower than original image should be enough for reasonably good results. Thus we find segmentation map for superpixels which are 4x4 pixel blocks. Detection is a primary task we are focusing on in this work, treating type classification as a less important sidetask. Most of barcodes share a common structure so it is only natural to classify pixels as being part of barcode (class 1) or background (class 0), thus segmentation network solves binary (super)pixel classification task. Barcodes are relatively simple objects and thus may be detected by relatively simple architecture. To achieve real-time CPU speed we have developed quite simple architecture based on dilated and separable convolutions (see \autoref*{segmentation_network}). It can be logically divided into 3 blocks: \begin{enumerate} \item \textbf{Downscale Module} is aimed to reduce spatial features dimension. Since these initial convolutions are applied to large feature maps they cost significant amount of overall network time, so to speed up inference these convolutions are made separable. \item \textbf{Context Module}. This block is inspired by \cite{Yu2015MultiScaleCA}. However, in our architecture it serves for slightly different purpose just improving features and exponentially increasing receptive field with each layer. \item Final classification layer is 1x1 convolution with number of filters equal to 1+n\_classes, where n\_classes is number of different barcode types we want to differentiate with. \end{enumerate} We used ReLU nonlinearity after each convolution except for the final one where we apply sigmoid to the first channel and softmax to all of the rest channels. We have chosen the number of channels $C=24$ for all convolutional layers. Our experiments show that with more filters model has comparable performance, but with less filters performance drops rapidly. As we have only a few channels in each layer the final model is very compact with only 32962 weights. As the maximal image resolution we are working with is 512x512, receptive field for prediction is at least half an image which should be more than enough contextual information for detecting barcodes. \subsection{Detecting barcodes based on segmentation} After the network pass we get segmentation map for superpixels with $1+n\_classes$ channels. For detection we use only the first channel which can be interpreted as probability being part of barcode for superpixels. We apply the threshold value for probability to get detection class binary labels (barcode/background). In all our experiments we set this threshold value to 0.5. We now find connected components on received superpixel binary mask and calculate bounding rectangle of minimal area for each component. To do the latest we apply \textit{minAreaRect} method from \textit{OpenCV} library (accessed Dec 2018). Now we treat found rectangles as detected barcodes. To get detection rectangle on original image resolution we multiply all of its vertices coordinates by the network scale 4. \subsection{Filtering results} To avoid a situation when a small group of pixels is accidentally predicted as a barcode, we filter out all superpixel connected components with area less than threshold $T_{area}$. The threshold value should be chosen to be slightly less than minimal area of objects in the dataset on the segmentation map. In all of our experiments we used value $T_{area}=20$. \subsection{Classification of detected objects} To determine barcode type of detected objects we use all of the rest $n\_classes$ channels from segmentation network output. After softmax we treat them as probabilities of being some class. Once we found the rectangle we compute the average probability vector inside this rectangle, then naturally choose the class with the highest probability. \section{Optimization scheme} \subsection{Loss function} The training loss is a weighted sum of detection and classification losses \begin{equation} L = L_{detection} + \alpha L_{classification} \end{equation} Detection loss $L_{detection}$ itself is a weighted sum of three components: mean binary crossentropy loss on positive pixels $L_{p}$, mean binary crossentropy loss on negative pixels $L_{n}$, and mean binary crossentropy loss on worst predicted $k$ negative pixels $L_{h}$, where $k$ is equal to the number of positive pixels in image. \begin{equation} L_{detection} = w_{p} L_{p} + w_{n} L_{n} + w_{h} L_{h} \end{equation} Classification loss is mean (categorical) crossentropy computed by all channels except the first one (with detection). Classification loss is calculated only on superpixels which are parts of ground truth objects. As our primary goal is high recall in detection we have chosen $w_p=15$, $w_n=1$, $w_h=5$, $\alpha=1$. We also tried several different configurations but this combination was the best among them. However, we did not spent too much time on hyperparameter search. \subsection{Data augmentation} For augmentation we do the following: \begin{enumerate} \item with (p=0.1) return original nonaugmented image \item with (p=0.5) rotate image random angle in [-45, 45] \item with (p=0.5) rotate image on one of 90, 180, 270 degrees \item with (p=0.5) do random crop. We limit crop to retain all barcodes on the image entirely and ensure that aspect ratio is changed no more than 70\% compared to the original image \item with (p=0.7) do additional image augmentation. For this purpose we used "less important" augmenters from heavy augmentation example from \textit{imgaug} library \cite{imgaug}. \end{enumerate} \section{Experimental results} \subsection{Datasets} The network performance was evaluated on 2 common benchmarks for barcode detection - namely WWU Muenster Barcode Database (Muenster) and ArTe-Lab Medium Barcode Dataset (Artelab). Datasets contain 595 and 365 images with ground truth detection masks respectively, resolution for all images is 640x480. All images in Artelab dataset contain exactly one EAN13 barcode, while in Muenster there may be several barcodes on the image. \begin{figure*} \centering \begin{subfigure}[b]{0.125\linewidth} \includegraphics[width=1.0\textwidth]{images/model_success/1.jpg} \end{subfigure}% \begin{subfigure}[b]{0.125\linewidth} \includegraphics[width=1.0\textwidth]{images/model_success/2.jpg} \end{subfigure}% \begin{subfigure}[b]{0.125\linewidth} \includegraphics[width=1.0\textwidth]{images/model_success/3.jpg} \end{subfigure}% \begin{subfigure}[b]{0.125\linewidth} \includegraphics[width=1.0\textwidth]{images/model_success/4.jpg} \end{subfigure}% \begin{subfigure}[b]{0.125\linewidth} \includegraphics[width=1.0\textwidth]{images/model_success/5.jpg} \end{subfigure}% \begin{subfigure}[b]{0.125\linewidth} \includegraphics[width=1.0\textwidth]{images/model_success/6.jpg} \end{subfigure}% \begin{subfigure}[b]{0.125\linewidth} \includegraphics[width=1.0\textwidth]{images/model_success/7.jpg} \end{subfigure}% \begin{subfigure}[b]{0.125\linewidth} \includegraphics[width=1.0\textwidth]{images/model_success/8.jpg} \end{subfigure}% \caption{Detection examples from test set} \label{fig:model_success} \end{figure*} \begin{figure*} \centering \begin{subfigure}[b]{0.2\linewidth} \includegraphics[width=0.99\textwidth]{images/model_errors/markup_failures/1_gt.png} \label{fig:gull2} \end{subfigure}% \begin{subfigure}[b]{0.2\linewidth} \includegraphics[width=0.99\textwidth]{images/model_errors/markup_failures/2_gt.png} \label{fig:gull2} \end{subfigure}% \begin{subfigure}[b]{0.2\linewidth} \includegraphics[width=0.99\textwidth]{images/model_errors/markup_failures/4_gt.png} \label{fig:gull2} \end{subfigure}% \begin{subfigure}[b]{0.2\linewidth} \includegraphics[width=0.99\textwidth]{images/model_errors/markup_failures/5_gt.png} \label{fig:gull2} \end{subfigure}% \begin{subfigure}[b]{0.2\linewidth} \includegraphics[width=0.99\textwidth]{images/border_overestimation_examples/0_gt.png} \label{fig:gull2} \end{subfigure}% \vskip -0.15in \begin{subfigure}[b]{0.2\linewidth} \includegraphics[width=0.99\textwidth]{images/model_errors/markup_failures/1_postpr.png} \label{fig:gull2} \end{subfigure}% \begin{subfigure}[b]{0.2\linewidth} \includegraphics[width=0.99\textwidth]{images/model_errors/markup_failures/2_postpr.png} \label{fig:gull2} \end{subfigure}% \begin{subfigure}[b]{0.2\linewidth} \includegraphics[width=0.99\textwidth]{images/model_errors/markup_failures/4_postpr.png} \label{fig:gull2} \end{subfigure}% \begin{subfigure}[b]{0.2\linewidth} \includegraphics[width=0.99\textwidth]{images/model_errors/markup_failures/5_postpr.png} \label{fig:gull2} \end{subfigure}% \begin{subfigure}[b]{0.2\linewidth} \includegraphics[width=0.99\textwidth]{images/border_overestimation_examples/0_postpr.png} \label{fig:gull2} \end{subfigure}% \ \caption{Detection examples: markup issues on Artelab and Muenster dataset. Markup on the top, detections results below} \label{fig:model_errors} \end{figure*} For training we used our own dataset with both 1D barcodes (Code128, Patch, EAN8, Code93, UCC128, EAN13, Industrial25, Code32, FullASCIICode, UPCE, MATRIX25, Code39, IATA25, UPCA, CODABAR, Interleaved25) and 2D barcodes (QRCode, Aztec, MaxiCode, DataMatrix, PDF417), being 16 different types for 1D and 5 types for 2D Barcodes, 21 type in total. Training dataset contains both photos and document scans. Example images from our dataset can be found in Fig.~\ref*{fig:model_success}. Dataset consist of 17k images in total, 10\% of it was used for validation. \subsection{Training procedure} We trained our model with batch size 8 for 70 epochs with learning rate 0.001 followed by additional 70 epochs with learning rate 0.0001 While training we resized all images to have maximal side at most 1024 maintaining aspect ratio and make both sides divisible by 64. We pick and augment/preprocess 3000 images from the dataset, then group them into batches by image size, and do this process repeatedly until the end of training. After that we pick next 3000 images and do the same until the end of the dataset. After we reach the end of the dataset, we shuffle image order and repeat the process. We trained three models: \textit{Ours-Detection (all types)} (without classification on entire dataset), \textit{Ours-Detection+Classification (all types)} (with classification on entire dataset), \textit{Ours-Detection (EAN13 only)} (without classification on EAN13 subset of 1000 images). \subsection{Evaluation metrics} We follow common evaluation scheme from \cite{Cresot2015}. Having binary masks $G$ for ground truth and $F$ for found detection results the Jaccard index between them is defined as $$J(G,F) = \frac{|G \cap F|}{|G \cup F|}$$ Another common name for Jaccard index is "intersection over union" or IoU which follows from definition. The overall detection rate for a given IoU threshold $T$ is defined as a fraction of images in the dataset where IoU is greater than that threshold $$D_{T} = \frac{\sum_{i \in S} I(J(G, F) \geq T))}{|S|}$$ where $S$ is set of images in the dataset and $I$ is indicator function. However, one image may contain several barcodes and if one of them is very big and another is very small $D_T$ will indicate error only on very high threshold, so we find it reasonable to evaluate detection performance with additional metrics which will average results not by images but by ground truth barcode objects on them. For this purpose we use recall $R_T$, defined as number of successfully detected objects divided by total number of objects in the dataset $$R_T = \frac{\sum_{i \in S}\sum_{G \in SG_i} I(J(G, F(G)) \geq T))}{\sum_{i \in S}|SG_i|}$$ where $SG_i$ is set of objects on ground truth on image $i$ and $F(G)$ is found box with highest Jaccard index with box $G$. The paired metric for recall is precision, defined as the number of successfully detected objects divided by total number of detections $$P_T = \frac{\sum_{i \in S}\sum_{G \in SG_i} I(J(G, F(G)) \geq T))}{\sum_{i \in S}|SF_i|}$$ where $SF_i$ is set of all detections made per image $i$. We found connected components for ground truth binary masks and treat them as ground truth objects. We emphasize that all the metrics above are computed for the detected object \textit{regardless its actual type}. To evaluate classification of the detected objects by type we use simple accuracy metric (number of correctly guessed objects / number of correctly detected objects). So if we find Barcode-PDF417 as Barcode-QRCode precision and recall will not be affected, but the classification accuracy will be. \subsection{Quantitative results} \begin{table*}[t] \caption{Result comparation on different datasets.} \label{table_artelab_muenster} \begin{center} \begin{small} \begin{sc} \begin{tabular}{l|cc|cc} \toprule & \multicolumn{2}{c|}{Muenster} & \multicolumn{2}{c}{Artelab}\\ & Acc $J_{avg}$ & Detection rate $D_{0.5}$ & Acc $J_{avg}$ & Detection rate $D_{0.5}$ \\ \midrule Cresot2015 & 0.799 & 0.963 & 0.763 & 0.893 \\ Cresot2016 & - & 0.982 & - & \textbf{0.989} \\ Yolo2017 & 0.873 & \textbf{0.991} & 0.816 & 0.926 \\ Namane2017 & \textbf{0.882} & 0.966 & \textbf{0.860} & 0.930 \\ \midrule Ours-Detection (all types) & 0.842 & 0.980 & 0.819 & \textbf{0.989} \\ Ours-Detection (EAN13 only) & 0.762 & 0.987 & 0.790 & \textbf{0.995} \\ \bottomrule \end{tabular} \end{sc} \end{small} \end{center} \end{table*} \begin{figure} \centering \includegraphics[width=0.9\linewidth]{images/graphs/artelab_detection_rate_curve_v2.png} \caption{Detection rate for different Jaccard index thresholds} \label{fig:detection_rate_artelab} \end{figure} \begin{figure} \centering \includegraphics[width=0.8\linewidth]{images/graphs/iou_custom_examples.png} \caption{Example of Jaccard index computation for various bounding boxes} \label{fig:iou_examples} \end{figure} We compare our results with Cresot2015 \cite{Cresot2015}, Cresot2016 \cite{Cresot2016}, Namane2017 \cite{Namane2017}, Yolo2017 \cite{YoloBarcode} on Artelab and Muenster datasets (\autoref*{table_artelab_muenster}). The proposed method is trained on our own dataset, however all other works which we compared with were trained on different datasets. As for the full reproducibility of other authors works on our dataset we have to follow the exactly same training protocol (including initialization and augmentations) to not underestimate the results we decided to rely on the numbers reported in works of other authors. We outperformed all previous works in terms of detection rate on Artelab dataset with the model trained only on EAN13 subset of our dataset. According to the tables, detection rate of our model trained on entire dataset with all barcode types is slightly worse than model trained on EAN13 subset. The reason for this is not poor generalization but markup errors or capturing more barcodes than in the markup (i. e. non-EAN barcodes), see Fig.~\ref*{fig:model_errors}. As it can be seen in Fig.~\ref*{fig:detection_rate_artelab} our model has a rapid decrease in detection rate for higher Jaccard thresholds. Aside from markup errors, the main reason for that is overestimation of barcode borders in detection, which is caused by prioritizing high recall in training, it makes high impact for higher Jaccard thresholds as Jaccard index is known to be very sensitive to almost exact match (Fig.~\ref*{fig:iou_examples}). On \autoref*{table_precision_recall} we show comparison of our models by precision and recall. Our models achieve close to an absolute recall, meaning that almost all barcodes are detected. On the other hand precision is also relatively high. \begin{table*}[t] \caption{Precision and recall of our approach on different datasets, Jaccard index threshold set to 0.5.} \label{table_precision_recall} \begin{center} \begin{small} \begin{sc} \begin{tabular}{l|cc|cc|cc|} \toprule & \multicolumn{2}{c|}{Muenster} & \multicolumn{2}{c|}{Artelab} & \multicolumn{2}{c|}{Test Multiclass} \\ & Precision & Recall & Precision & Recall & Precision & Recall \\ \midrule Ours-detection (all types) & 0.777 & 0.990 & 0.814 & 0.995 & 0.940 & 0.991 \\ Ours-detection+classification (all types) & \textbf{0.805} & 0.987 & \textbf{0.854} & 0.995 & \textbf{0.943} & \textbf{0.994} \\ Ours-detection (EAN13 only) & 0.759 & \textbf{1.000} & 0.839 & \textbf{0.997} & - & - \\ \bottomrule \end{tabular} \end{sc} \end{small} \end{center} \end{table*} \subsection{Execution time} \begin{table}[t] \caption{Inference time comparison} \label{table_time} \begin{center} \begin{small} \begin{sc} \begin{tabular}{lcc} \toprule & Execution time (ms) & Resolution \\ \midrule S\"{o}r\"{o}s \cite{Soros2013} & 73 & 960x723 \\ Cresot16 \cite{Cresot2016} & 40 & 640x480 \\ Yolo17 \cite{YoloBarcode} & 13.6 & 416x416 \\ Namane17 \cite{Namane2017} & 21 & 640x480 \\ Ours (GPU) & 3.8 & 512x512 \\ Ours (CPU) & 44 & 512x512 \\ \bottomrule \end{tabular} \end{sc} \end{small} \end{center} \end{table} For our network we measure time on 512x512 resolution which is enough for most of applications. We do not include postprocessing time as it is negligible compared to forward network run. The developed network performs at real-time speed and is 3.5 times faster than YOLO with darknet \cite{YoloBarcode} on higher resolution on the same GTX 1080 GPU. In the \autoref*{table_time} we compare inference times of our model with other approaches. We also provide CPU inference time (for Intel Core i5, 3.20GHz) of our model showing that it is nearly the same as reported in Cresot2016, where authors used their approach in the real-time smartphone application. It is important since not all of the devices have GPU yet. \subsection{Classification results} Among correctly detected objects we measured classification accuracy and achieved 60\% accuracy on test set. Moreover, classification subtask does not damage detection results. As shown in \autoref*{table_precision_recall} the results with classification are even slightly better, meaning that detection and classification tasks can mutually benefit from each other. \subsection{Capturing long narrow barcodes} Additional advantage of our detector is that it is capable of finding objects of any arbitrary shape and does not assume that objects should be approximately squares as done by YOLO. Some examples are provided in Fig.~\ref*{fig:model_success}. \section{Conclusion} We have introduced new barcode detector which can achieve comparable or better performance on public benchmarks and is much faster than other methods. Moreover, our model is universal barcode detector which is capable to detect both 1D and 2D barcodes of many different types. The model is very light with less than 33000 weights which can be considered very compact and suitable for mobile devices. Despite being shallow (i.e. very simple, we didn't use any SOTA techniques for semantic segmentation) our model shows that semantic segmentation may be used for object detection efficiently. It also provides natural way to detect objects of arbitrary shape (e.g. very long but narrow). Future work may include using more advanced approaches in semantic segmentation to develop better network architecture and increase performance. \bibliographystyle{IEEEtran}
{'timestamp': '2019-06-18T02:23:47', 'yymm': '1906', 'arxiv_id': '1906.06281', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06281'}
arxiv
\section{Introduction} A plane embedding of a planar graph $G$ is said to be a plane near-triangulation if all its faces, except possibly the exterior face, are triangles. It was known even before the strong perfect graph theorem (\citet{chudnovsky2006strong}) that a planar graph is not perfect if and only if it contains an induced odd hole (\citet{tucker1973strong}). Algorithmic recognition of planar perfect graphs was subsequently studied by \citet{hsu1987recognizing} who discovered a method to determine whether a given planar graph of $n$ vertices is perfect in $O(n^{3})$ time. Later, ~\citet{cornuejols2003polynomial} discovered an algorithm to recognize perfect graphs in $O(n^{9})$ time, using the strong perfect graph theorem. Though structural characterizations for perfect plane triangulations were attempted in the literature (see for example, \citet{benchetrit2015h}), a local characterization for perfect plane triangulations (or plane near-triangulations) does not seem to be known. An attempt in this direction was initiated by \citet{SalamCWKS19}. In this work, we extend their results to obtain a local characterization for a plane (near-) triangulated graph to be perfect. The characterization leads to an $O(n^{2})$ algorithm for checking perfectness of a plane near-triangulation. No quadratic time algorithm seems to be known in the literature for testing perfectness of plane triangulations. If a plane near-triangulation $G$ contains a cut vertex or an edge separator, we can split $G$ into two induced subgraphs such that $G$ is perfect if and only if each of the induced subgraphs is perfect. Consequently, it suffices to consider plane triangulations that are both $2$-connected and have no edge separators. A triangle $\Delta$ in $G$ consisting of vertices $x,y,z$, is a separating triangle in $G$ if the interior of $\Delta$ as well as the exterior of $\Delta$ contain at least one vertex. Let $Int(\Delta)$ and $Ext(\Delta)$ denote the set of vertices in the interior and exterior of $\Delta$. It is not hard to see that $G$ is perfect if and only if the subgraphs induced by $Int(\Delta)\cup \{x,y,z\}$ and $Ext(\Delta)\cup \{x,y,z\}$ are perfect. Thus, a separating triangle in $G$ splits $G$ into two induced subgraphs such that $G$ is perfect if and only if both the induced subgraphs are perfect. Consequently, we assume hereafter that $G$ does not contain any separating triangles as well. A \textit{W-triangulation} is a $2$-connected plane near-triangulation that does not contain any edge separator or a separating triangle \cite{SalamCWKS19}. It is easy to see that the closed neighbourhood $N[x]$ of any internal vertex $x$ in a W-triangulation $G$ will induce a wheel; for otherwise $G$ will contain a separating triangle. It was shown by \citet{SalamCWKS19} that a plane W-triangulation that does not contain any induced wheel on five vertices is not perfect if and only if it contains either a vertex or a face, the boundary of the exterior face of the closed neighbourhood of which, induces an odd hole. However, their proof strategy was crucially dependent on the graph being free of induced wheels on five vertices. Let $X$ be a set of vertices in a graph $G$. The \textit{local neighbourhood} of $X$ is defined as the subgraph $G[N[X]]$ induced by $X$ and its neighbours in $G$. Given a W-triangulation $G$, our objective is to show that if $G$ is not perfect, then there exists a small connected induced subgraph $X$ in $G$ whose local neighbourhood has an odd hole as the boundary of its exterior face. We will show that $X$ will either be a vertex, an edge or a facial triangle of $G$. First, observe that if an internal vertex $x$ of $G$ has odd degree, then the local neighbourhood of $X=\{x\}$ is a wheel, whose exterior boundary is an odd hole. Thus, the non-trivial graphs to consider are W-triangulations in which all internal vertices are of even degree. An \textit{even W-triangulation} is a W-triangulation in which every internal vertex has even degree \cite{SalamCWKS19}. Figure~\ref{fig00} shows an even W-triangulation $G$ that is not perfect \cite{SalamCWKS19}. Here, the local neighbourhood of the facial triangle consisting of vertices $x,y$ and $z$ has an odd hole as its exterior boundary, and hence we can choose $X=\{x,y,z\}$. Note that, for this particular graph, no smaller substructure (a vertex or an edge) exists, whose local neighbourhood has an odd hole as its exterior boundary. \begin{figure}[!htb] \centering \includegraphics[scale=0.75]{counter.pdf} \caption{The local neighbourhood of the facial triangle $\Delta=\{x,y,z\}$ has an odd hole in its boundary.} \label{fig00} \end{figure} In Section~\ref{sec:perfect}, we prove that every non-perfect even W-triangulation $G$ contains a subset of vertices $X$, which consists of either the endpoints of an edge or a facial triangle, such that the induced subgraph $G[N[X]]$ has an odd hole as the boundary of its exterior face. This yields: \begin{Theorem} \label{thm:main-thm} Let $G=(V,E)$ be a plane near-triangulated graph. $G$ is not perfect if and only if there exists a vertex, an edge or a triangle, the exterior boundary of the local neighbourhood of which, is an odd hole. \end{Theorem} In Section~\ref{perfect plane}, we describe an $O(n^2)$ algorithm that uses Theorem~\ref{thm:main-thm} to check whether a plane near-triangulation $G$ of $n$ vertices is perfect. \section{Perfect plane near-triangulations}\label{sec:perfect} Let $G=(V,E)$ be an even non-perfect W-near-triangulated graph. A \textit{minimal odd hole} $C$ in $G$ is defined as an odd hole such that there is no other odd hole in $C \cup Int(C)$. Let $C$ be a minimal odd hole in $G$ and let $S=\{a_0,a_1,\ldots,a_s\}$ be the set of vertices in $C$, listed in clockwise order. To avoid cumbersome notation, hereafter a reference to a vertex $a_i\in S$ for $i>s$ may be inferred as reference to the vertex $a_{i\bmod (s+1)}$. With this notation, we have $a_ia_{i+1}\in E(G)$, for $0\leq i \leq s$. Since $C$ is an odd hole, $s$ must be even and $s\geq 4$. Throughout the paper, the length of a path (respectively, cycle) will be the number of edges in the path (respectively, cycle). Let $H$ be the subgraph of $G$ induced by the vertices in $Int(C)$. We study the structure of $H$ in detail, in order to derive our perfectness characterization. Since $G$ is a plane near-triangulation, $H$ is non-empty. We show next that $H$ is a $2$-connected plane near-triangulation. \begin{Claim}\label{claim:connect} $H$ has at least $3$ vertices. Moreover, for any vertex $b \in V(H)$, the neighbours of $b$ on $C$ (if any) are consecutive vertices of $C$. \end{Claim} \begin{proof} Since $G$ is an even W-triangulation, $H$ cannot be a single vertex as otherwise the degree of that vertex would be $|S|$, which is odd. The number of vertices in $H$ cannot be two, as in that case the two vertices must be adjacent, with even degree and having exactly two common neighbours on $C$. However, this will contradict the parity of the number of vertices in $C$. Thus, $H$ has at least $3$ vertices. (Note that it is possible for $H$ to have exactly three vertices as in Figure~\ref{fig00}). Let $b$ be a vertex of $H$ with at least one neighbour on $C$. Without loss of generality, we may assume that $a_0$ is adjacent to $b$. For contradiction, assume that the neighbours of $b$ on $C$ are not consecutive. That is, for some $0<i<j<k<l\le s+1$, we have $\{a_0, a_1, \ldots a_{i-1}\}\subseteq N(b)$, $\{a_j, a_{j+1},\ldots, a_{k-1}\} \subseteq N(b)$ and $a_{l \bmod (s+1)} \in N(b)$; but $\{a_i, a_{i+1}, \ldots, a_{j-1}\}6 \cap N(b) =\emptyset$ and $\{a_k, a_{k+1}, \ldots, a_{l-1}\} \cap N(b) =\emptyset$ (see Figure~\ref{fig01}). Note that, it is possible to have $a_{l \bmod (s+1)} =a_0$. Let $P_1, P_2, P_3, P_4$ and $P_5$ be subpaths of $C$ defined as follows: $P_1 = a_0 a_1 \ldots a_{i-1}$, $P_2 = a_{i-1}a_i a_{i+1} \ldots a_{j}$, $P_3 = a_j a_{j+1} \ldots a_{k-1}$, $P_4 = a_{k-1} a_k a_{k+1} \ldots a_{l}$ and $P_5 = a_l a_{l+1} \ldots a_{s}a_0$. Note that, the union of these five paths is $C$. We know that the closed neighbourhood of $b$ induces a wheel. Let $R$ denote the cycle forming the exterior boundary of this wheel. Since $G$ is an even W-triangulation, $R$ is of even length. Let $Q_1=x_1 x_2 \ldots x_p$, $Q_2=y_1 y_2 \ldots y_q$ be subpaths of $R$ that are vertex disjoint from $C$, such that the concatenation of the paths $P_1, a_{i-1} x_1, Q_1, x_p a_j, P_3, a_{k-1} y_1, Q_2, y_q a_l$ (in that order) forms a subpath of $R$. The path $P_2$ has at least two edges, because $i<j$. It is easy to see that $b a_{i-1} P_2 a_j b$ is an induced cycle in $G$ and since $C$ is assumed to be a minimal odd hole, $P_2$ must be of even length. Similarly, the path $P_4$ also has at least two edges and is of even length. Note that, the edge set $(E(C) \setminus E(P_2)) \cup E(Q_1) \cup \{a_{i-1} x_1, x_p a_j\}$ is another induced cycle in $G$. Hence, the path $Q_1$ must be of odd length. Similarly, the path $Q_2$ is also of odd length. But, this implies that the induced cycle formed by the edge set $(E(C) \setminus (E(P_2) \cup E(P_4))) \cup E(Q_1) \cup E(Q_2) \cup \{a_{i-1} x_1, x_p a_j, a_{k-1} y_1, y_q a_l\}$ is an odd hole. This contradicts the minimality of $C$ and hence we can conclude that the neighbours of $b$ on $C$ must be consecutive. \end{proof} \begin{figure}[!htb] \centering \includegraphics[scale=0.70]{2connected.pdf} \caption{b is a vertex with non consecutive neighbours in $C$} \label{fig01} \end{figure} \begin{lemma}\label{lem:H-connected} $H$ is a $2$-connected near-triangulation with at least three vertices. \end{lemma} \begin{proof} Since $G$ is a plane near-triangulation, it is easy to see that $H$ is a plane near-triangulation. Hence, by Claim~\ref{claim:connect}, it only remains to prove that $H$ has no cut vertices. For contradiction, suppose $b$ is a cut vertex in $H$. It is easy to see that $b$ must have at least one neighbour on $C$. By Claim~\ref{claim:connect}, neighbours of $b$ on $C$ are consecutive. Without loss of generality, let $N(b) \cap V(C)=\{a_0, a_1, \ldots, a_i\}$, for some $0 \le i < s$. Since $G$ is a W-triangulation, the neighbourhood of $b$ induces a wheel with $b$ as the center. Let $R$ be the induced cycle formed by the neighbours of $b$ in $G$. Since $G$ has no separating triangles, $a_0, a_1, \ldots, a_i$ should be consecutive vertices in $R$ as well. Let $H_1$ and $H_2$ be two connected components of $H \setminus b$. Let $v_1$ be a neighbour of $b$ in $H_1$ and $v_2$ be a neighbour of $b$ in $H_2$. Both $v_1$ and $v_2$ are vertices that belong to the cycle $R$ and they cannot be consecutive on $R$. Let $P_1$ and $P_2$ denote the two edge disjoint paths between $v_1$ and $v_2$ in $R$ such that their union is $R$. As $v_1$ and $v_2$ are not connected in $H\setminus b$, both $P_1$ and $P_2$ must intersect $C$. These intersections happen on vertices in $V(C) \cap V(R) \subseteq N(b)$. Hence there exist $0 \le j, k\le i$ such that $a_j \in V(P_1) \cap V(C)$ and $a_k \in V(P_2) \cap V(C)$. Note that, if we delete $v_1$ and $v_2$ from $R$, $a_j$ and $a_k$ get disconnected from each other. However, this is impossible, since vertices $N(b) \cap V(C)=\{a_0, a_1, \ldots, a_i\}$ are known to be consecutive on $R$. Hence, $H$ is $2$-connected. \end{proof} Consequently from Lemma~\ref{lem:H-connected} we have: \begin{Corollary}\label{cor:H} The boundary of the exterior face of $H$ has at least three vertices. \end{Corollary} Let $C'$ be the cycle forming the boundary of the exterior face of $H$. If $C'$ is a triangle, then it must be a facial triangle in $G$, as $G$ is assumed to contain no separating triangles. In this case, the exterior face of the closed neighbourhood of $C'$ is the odd hole $C$, and Theorem~\ref{thm:main-thm} is immediate. Hence, we assume hereafter that $C'$ is not a triangle. Let $T=\{b_0,b_1,\ldots,b_t\}$, $t\geq 3$ be the vertices of $C'$, listed in clockwise order. To simplify the notation, reference to a vertex $b_j\in T$ for $j>t$ may be inferred as reference to the vertex $b_{j\bmod (t+1)}$. It is easy to see that every vertex in $T$ is a neighbour of at least one vertex in $S$ and vice versa. Let $G'=(V',E')$ be the subgraph of $G$ with $V'=S\cup T$ and $E'=\{uv: u\in S , v\in T\} \cup E(C) \cup E(C')$. Note that, $b_ib_{i+1}\in E'$, for all $0\leq i \leq t$; but $E'$ excludes chords in $C'$. Since $G$ is a plane near-triangulation, the following observation is immediate. \begin{Observation}\label{obs:neighbour} For every $0\leq i\leq s$ and $0 \leq j \leq t$: \begin{enumerate} \item The neighbours of $a_i$ in $C'$ must be $b_l,b_{l+1}\ldots b_m$ for some consecutive integers $l,l+1\ldots m$. \item The neighbours of $b_j$ in $C$ must be $a_k,a_{k+1}\ldots a_r$ for some consecutive integers $k,k+1\ldots r$. \item $a_{i}$ and $a_{i+1}$ must have a common neighbour in $C'$. \item $b_{j}$ and $b_{j+1}$ must have a common neighbour in $C$. \item The minimum degree of any vertex of $G'$ is at least $3$. \end{enumerate} \end{Observation} Consider a vertex $a_i\in S$. Suppose $b_l,b_{l+1},\ldots b_{m}$ are the neighbours of $a_i$ in $C'$. If there is an edge between some non-consecutive vertices $b_p$ and $b_q$ for some $l \le p, q \le m$, then $a_i,b_p$ and $b_q$ will form a separating triangle in $G$, a contradiction. Hence we have: \begin{Observation}\label{Obs:triangle} For any $a_i \in S$, there exists an edge between two neighbours of $a_i$ in $C'$ if and only if they are consecutive in $C'$. \end{Observation} \begin{lemma}\label{evenC'} For any vertex $b_j\in T$, $deg_{G'}(b_j)$ is either $3$ or an even number greater than $3$. \end{lemma} \begin{proof} Let $deg_{G'}(b_j)\neq 3$ and be odd. Since $deg_{C'}(b_j)=2$, the neighbours of $b_j$ in $C$ form a path (say $Z$) of even length ($\geq 2$). Let the neighbours of $b_j$ in $C$ be $a_i,a_{i+1},\ldots,a_k$ in the clockwise order (see Figure~\ref{fig0}(a)). Note that $a_k a_i \notin E(G)$. Further, since $C$ is an odd hole, the length of the subpath $Y$ of $C$ from $a_k$ to $a_i$ in clockwise direction, must be an odd number $\geq 3$. Hence the cycle formed by replacing the path $Z$ in $C$ with the edges $a_ib_j,b_ja_k$ will be an odd hole, distinct from $C$, with vertices chosen only from $S$ and $Int(C)$. This contradicts the minimality of $C$. \end{proof} \begin{figure}[!htb] \centering \includegraphics[scale=0.50]{alphadeg.pdf} \caption{ (a) The degree of vertex $b_i$ is odd. (b) The degree of vertex $a_i$ is odd} \label{fig0} \end{figure} \begin{lemma}\label{evenC} For any vertex $a_i\in T$, $deg_{G'}(a_i)$ is either $3$ or an even number greater than $3$. \end{lemma} \begin{proof} Suppose $deg_{G'}(a_i) > 3$. With no loss of generality, let the neighbours of $a_i$ in $C'$ be $b_0,b_1,\ldots,b_l$, $l\geq 1$ in the clockwise order (see Figure~\ref{fig0}(b)). For contradiction, suppose $l$ is even. Then, the length of the path $b_0,b_1\ldots, b_l$ is even. Let the neighbours of $b_0$ in the clockwise direction in $C$ be $a_{j},a_{j+1},\ldots,a_i$ and the neighbours of $b_l$ in the clockwise direction in $C$ be $a_i,a_{i+1},\ldots,a_{k}$. We may assume without loss of generality that $j<i$. Let $P$ be the path in $C$ from $a_{j}$ to $a_{k}$ through $a_i$. As $deg_{G'}(b_0)$ and $deg_{G'}(b_l)$ are even (by Lemma~\ref{evenC'}), the length of path $P$ is even, $\geq 2$. Let $X$ be the path $a_jb_0b_1\ldots b_la_k$. Since $l$ is assumed to be even, $deg_{G'}(a_i)$ is odd, and hence $X$ must be of even length. Note that, $a_k \neq a_j$, as in that case the path $P$ will be the whole (odd) cycle $C$ which is impossible as $P$ has even length. Thus, the edges $a_jb_l$ and $a_kb_0$ cannot be present in $G'$ as otherwise we would have $a_k=a_j$. Hence, unless $a_ka_j$ is an edge in $G'$, then $X$ is an induced path in $G$. However, $a_ka_j$ cannot be an edge in $G'$ as otherwise $X$ along with the edge $a_ka_j$ induces an odd hole, distinct from $C$, with vertices chosen only from $S$ and $Int(C)$, which is impossible. Thus, we conclude that $X$ is an induced path in $G'$. Consequently, the cycle formed by replacing even length path $P$ in $C$ with the even length induced path $X$ will be an odd hole, distinct from $C$, with vertices chosen only from $S$ and $Int(C)$. This contradicts the choice of $C$. \end{proof} We introduce some notation. A vertex $a_i\in S$ with $deg_{G'}(a_i)=4$ (respectively $deg_{G'}(a_i)>4$) will be called an $\alpha$ vertex (respectively $\alpha'$ vertex). Similarly a vertex $b_j\in T$ with $deg_{G'}(b_j)=4$ (respectively $deg_{G'}(b_j)>4$) will be called an $\beta$ vertex (respectively $\beta'$ vertex). Every degree three vertex in $S$ (respectively $T$) will be called a $\gamma$ vertex (respectively $\delta$ vertex). Let $V_\alpha,V_{\alpha'},V_\beta, V_{\beta'},V_{\gamma}$ and $V_{\delta}$ denote the set of $\alpha, \alpha',\beta,\beta',\gamma$ and $\delta$ vertices respectively and $N_\alpha,N_{\alpha'},N_\beta, N_{\beta'},N_{\gamma}$ and $N_{\delta}$ denote the number of $\alpha, \alpha',\beta,\beta',\gamma$ and $\delta$ vertices respectively (See Figure~\ref{fig1}). \begin{figure}[h] \centering \includegraphics[scale=0.65]{oddhole.pdf} \caption{An illustration of the notation.} \label{fig1} \end{figure} With the above notation, the following observation is immediate. \begin{Observation}\label{obs:gamma} ~ \begin{enumerate} \item Every $\alpha$ and $\alpha'$ vertex (respectively $\beta$ and $\beta'$ vertex) has exactly two neighbours in $T$ (respectively $S$) that are not $\delta$ vertices (respectively $\gamma$ vertices). \item Every $\gamma$ vertex (respectively $\delta$ vertex) must have exactly one neighbour in $T$ (respectively $S$). Moreover the neighbour must be a $\beta'$ vertex (respectively $\alpha'$ vertex). \end{enumerate} \end{Observation} \begin{lemma}\label{lem:numgamma} $N_\gamma$ and $N_\delta$ are even. \end{lemma} \begin{proof} Let $G''$ be the bipartite subgraph of $G'$ with vertex set $V''=V_\delta \cup V_{\alpha'}$ and edge set $E''=\{a_i b_j \colon a_i \in V_{\alpha'}, b_j \in V_\delta\}$. Consider any vertex $a_i \in V_{\alpha'}$. We know that in $G'$, $a_i$ has exactly two neighbours in $S$. Since by Lemma~\ref{evenC}, $deg_{G'}(a_i)$ is even, it follows that in $G'$, $a_i$ has an even number of neighbours from $T$. From Observation~\ref{obs:gamma}, $a_i$ has exactly two neighbours in $T$ that are not in $V_\delta$. Hence, the number of edges from $a_i$ to $V_\delta$ in $G'$ must be even. Therefore, in the bipartite graph $G''$, every vertex in $V_{\alpha'}$ has an even degree. By Observation~\ref{obs:gamma}, $deg_{G''}(b_j)=1$, for each $b_j \in V_\delta$. Consequently, $N_\delta = |V_\delta|= \sum_{a_i \in V_{\alpha'}}{deg_{G''}(a_i)}$ is an even number. The proof for the claim that $N_\gamma$ is even is similar. \end{proof} Note that $|S|=N_{\gamma}+N_\alpha+ N_{\alpha'}$. By Lemma~\ref{lem:numgamma}, $N_{\gamma}$ is even. As $C$ is an odd hole, we have: \begin{Corollary}\label{cor:numalpha} $N_\alpha+ N_{\alpha'}$ is odd. \end{Corollary} \begin{lemma}\label{obs:Nalphabeta} ~ \begin{enumerate} \item Every vertex in $S$ is a neighbour of a $\beta$ or a $\beta'$ vertex. \item Every vertex in $T$ is a neighbour of a $\alpha$ or a $\alpha'$ vertex. \item $N_{\alpha}+N_{\alpha'}=N_{\beta}+N_{\beta'}$. \end{enumerate} \end{lemma} \begin{proof} The first two parts are easy to see. To prove the third part, consider the bipartite subgraph $G''=(V'', E'')$ of $G'$ with vertex set $V''=V_{\alpha} \cup V_{\alpha'}\cup V_{\beta}\cup V_{\beta'}$ and edge set $E''=\{a_i b_j \colon a_i \in V_{\alpha} \cup V_{\alpha'}, b_j \in V_{\beta}\cup V_{\beta'} \}$. By Observation~\ref{obs:gamma}, every $\alpha$ and $\alpha'$ vertex has exactly two neighbours in $T$ that are either $\beta$ vertices or $\beta'$ vertices. Similarly, each $\beta$ and $\beta'$ vertex have exactly two neighbours in $S$ which are either $\alpha$ or $\alpha'$ vertices. Thus, $G''$ is a $2$-regular bipartite graph. Hence, $N_{\alpha}+N_{\alpha'}=N_{\beta}+N_{\beta'}$. \end{proof} Combining Lemma~\ref{lem:numgamma}, Corollary~\ref{cor:numalpha} and Lemma~\ref{obs:Nalphabeta}, we see that $|T|=N_\delta+N_{\beta}+N_{\beta'}$ is odd. This means that $C'$ is an odd cycle. As $C'$ cannot be an odd hole and we have assumed that it is not a triangle, we have: \begin{Observation}\label{obs:chord} $C'$ is an odd cycle with at least one chord in $G$ connecting vertices in $C'$. \end{Observation} \begin{figure}[!htb] \centering \includegraphics[scale=0.50]{multi2multi.pdf} \caption{$b_i \in V_{\beta'}$ and $b_j \in V_\beta$. } \label{fig2} \end{figure} The following lemma shows that any chord in $C'$ must have a $\delta$ vertex as one of its end points. \begin{lemma}\label{lem:multiC} If $b_ib_j$ is a chord in $C'$ then $\{b_i,b_j\} \cap V_\delta \ne \emptyset$. \end{lemma} \begin{proof} Suppose $\{b_i,b_j\} \cap V_\delta =\emptyset$ and $i < j$. Let $a_k,a_{k+1},\ldots,a_l$ be the neighbours of $b_i$ in $C$ and let $a_x,a_{x+1},\ldots,a_y$ be the neighbours of $b_j$ in $C$, both taken in clockwise order (see Figure~\ref{fig2}). As $b_ib_j$ is a chord, there exists at least one vertex between $b_i$ and $b_j$ in $C'$ (in both directions). Hence $a_l \neq a_x$ (otherwise the vertices $a_x,b_i,b_j$ will form a separating triangle). Similarly, $a_k \neq a_y$. As $b_i$ and $b_j$ have even number of neighbours in $C$, it is easy to see that either the clockwise path $P$ from $a_l$ to $a_x$ or the clockwise path $Q$ from $a_y$ to $a_k$ in $C$ must be even, for otherwise $C$ cannot be an odd hole. With no loss of generality, assume that the length of $P$ is even. Then the vertices in the path $P$ along with the edges $\{a_xb_j,b_jb_i,b_ia_l\}$ forms an odd hole consisting of vertices chosen only from $S$ and $Int(C)$, a contradiction. \end{proof} By Lemma~\ref{lem:multiC}, $C'$ contains at least one chord connecting a vertex $b_j\in V_\delta$ to some other vertex in $C'$. By Observation~\ref{obs:gamma}, the neighbour of $b_j$ in $C$ must be an $\alpha'$ vertex. Hence, \begin{Corollary}\label{cor:nalpha1} There exists at least one $\alpha'$ vertex in $C$. \end{Corollary} The next lemma shows that if a chord in $C'$ connects two $\delta$ vertices, then their neighbours in $C$ will be adjacent. \begin{lemma}\label{lem:gammachord} Let $\{b_i,b_j\}\subseteq V_\delta$. Let $a_x$ and $a_y$ be the neighbours of $b_i$ and $b_j$ respectively in $C$. If $b_ib_j$ is a chord in $C'$ (in $G$), then $a_xa_y$ is an edge in $C$. \end{lemma} \begin{proof} Let $\{b_i,b_j\} \subseteq V_\delta$ and suppose $b_ib_j$ is a chord in $G$ connecting vertices of $C'$. Let $a_x$ and $a_y$ be the unique neighbours of $b_i$ and $b_j$ respectively in $C$ (Observation~\ref{obs:gamma}). It follows that $a_x\neq a_y$, as otherwise the vertices $b_i,a_x,b_j$ will form a separating triangle in $G$ (See Figure~\ref{fig3}(a)). Since $C$ is an odd hole, exactly one of the two paths from $a_x$ to $a_y$ through vertices in $C$ must be of even length. With no loss of generality, assume that the path $P$ from $a_y$ to $a_x$ in the clockwise direction is even (see Figure~\ref{fig3}(b)). Then if $a_xa_y$ is not an edge in $C$, the edges in the path $P$ together with the edges $a_xb_i,b_ib_j$ and $b_ja_y$ forms an odd hole consisting of vertices chosen only from $S$ and $Int(C)$ (see Figure~\ref{fig3}(b), (c)), a contradiction. \end{proof} \begin{figure}[!htb] \centering \includegraphics[scale=0.60]{single2single1.pdf} \caption{(a) $a_x=a_y$ (b) $a_xa_y$ is not an edge in $G$ (c) $a_xa_y$ is an edge} \label{fig3} \end{figure} Next we bound the number of $\alpha$ and $\alpha'$ vertices in $C$. A bound on the number of $\beta$ and $\beta'$ vertices follows from this. \begin{lemma}\label{nalphabeta3} $N_\alpha+ N_{\alpha'}\leq 3$ \end{lemma} \begin{proof} Suppose $N_\alpha+ N_{\alpha'}> 3$. As $N_\alpha+ N_{\alpha'}$ is odd (by Corollary~\ref{cor:numalpha}), $N_\alpha+ N_{\alpha'}\geq 5$. By Corollary~\ref{cor:nalpha1}, an $\alpha'$ vertex $a_i$ must exist in $C$. By the definition of an $\alpha'$ vertex and by Lemma~\ref{evenC}, we know that $a_i$ has an an even number ($\ge 6$) of neighbours in $G'$, of which exactly two are on $C$. Without loss of generality, let $b_q,b_{q+1},\ldots,b_r$ ($r\geq q+3$) be the neighbours of $a_i$ in $T$ (see Figure~\ref{fig4}(a)). Let the neighbours of $b_q$ and $b_r$ in $C$ in clockwise order be $a_x,a_{x+1}\ldots, a_i$ and $a_i,a_{i+1},\ldots,a_y$ respectively. Clearly, $a_x$ and $a_y$ are in $V_\alpha \cup V_{\alpha'}$. If $x=y$, then $V_\alpha \cup V_{\alpha'}=\{a_x, a_i\}$, contradicting our assumption that $N_\alpha+ N_{\alpha'} \ge 5$. Further, since $a_x, a_i$ and $a_y$ are the only vertices in $V_\alpha \cup V_{\alpha'}$ in the clockwise subpath of $C$ from $a_x$ to $a_y$, at least two internal vertices of the clockwise subpath of $C$ from $a_y$ to $a_x$ must belong to $V_\alpha \cup V_{\alpha'}$, since $N_\alpha+ N_{\alpha'} \ge 5$. Let $b_p,b_{p+1},\ldots, b_{q}$ and $b_r,b_{r+1},\ldots,b_{s}$ be the neighbours of $a_x$ and $a_y$ in $C'$ respectively in clockwise order. Note that $b_p$ and $b_s$ are distinct, non-adjacent vertices in $C'$. This is because $N_{\beta}+N_{\beta'}=N_{\alpha}+N_{\alpha'}\geq 5$ (part (3) of Lemma~\ref{obs:Nalphabeta}). Let the neighbours of $b_p$ and $b_s$ in $C$ be $a_g,a_{g+1},\ldots,a_x$ and $a_y,a_{y+1},\ldots,a_h$ respectively. As $N_\alpha+ N_{\alpha'}\geq 5$, $a_g \neq a_h$. Since $b_p,b_q,b_r$ and $b_s$ are elements of $V_\beta \cup V_{\beta'}$, their degrees must be even (by Lemma~\ref{evenC'}). Hence the path from $a_g$ to $a_h$ through $a_x,a_i$ and $a_y$ along vertices in $C$ is of even length. Consequently, as $C$ is an odd hole, the (chordless) path $L$ from $a_h$ to $a_g$ in clockwise order in $C$ (as shown in Figure~\ref{fig4}(a)) must be of odd length ($\geq 1$). We will show that there exists another odd hole in $G$, consisting of vertices chosen only from $S$ and $Int(C)$, contradicting the choice of $C$. Consider the path $P=a_gb_pb_{p+1}\ldots b_{q}a_ib_rb_{r+1}\ldots b_{s}a_h$. Since $a_x$ and $a_y$ are of even degree (by Lemma~\ref{evenC}), $P$ is of even length (see Figure~\ref{fig4}(a)). This path, together with the with the path $L$, form an odd cycle of length at least seven. If we prove that this cycle is chordless, it will be an odd hole, consisting of vertices chosen only from $S$ and $Int(C)$, a contradiction to the choice of $C$ as desired. Hence we analyze the possible chords in $G$ for the cycle formed by edges of $P$ and the edges of $L$. By Observation~\ref{Obs:triangle}, there cannot be any chord in $P$ connecting any two vertices in the set $\{b_p,b_{p+1},\ldots b_q\}$ or any two vertices in the set $\{b_r,b_{r+1},\ldots,b_s\}$. For the same reason, a $b_qb_r$ chord also cannot exist. Moreover, since as $b_q,b_p, b_r$ and $b_s$ are elements in $V(\beta)\cup V(\beta')$, by Lemma~\ref{lem:multiC}, there will not be a chord between them. Further, as there is no edge connecting $a_x$ and $a_y$, no chord exists between a vertex in the set $\{b_{p+1},\ldots b_{q-1}\}$ and a vertex in the set $\{b_{r+1}\ldots b_{s-1}\}$ (by Lemma~\ref{lem:gammachord}). Hence, chords in $P$ can exist only between a vertex in the set $\{b_p,b_q\}$ and a vertex in the set $\{b_{r+1},\ldots,b_{s-1}\}$ or between a vertex in the set $\{b_r,b_s\}$ and a vertex in the set $\{b_{p+1},\ldots ,b_{q-1}\}$. We systematically rule out these possibilities below. \begin{itemize} \item \textbf{Case 1} There exists a $b_pb_k$ chord in $C'$ for some $b_k \in \{b_{r+1}\ldots,b_{s-1}\}$ (Figure~\ref{fig4}(b)): Let $L'$ be the (chordless) path from $a_y$ to $a_g$ in the clockwise direction in $C$. Since $ b_s$ is of even degree (by Lemma~\ref{evenC'}), and $L'$ is obtained by combining the path from $a_y$ to $a_h$ along $C$ with the odd length path $L$, path $L'$ should be of even length. Consequently, the path $L'$ along with the edges $a_gb_p,b_pb_k$ and $b_ka_y$ will induce an odd hole consisting of vertices chosen only from $S$ and $Int(C)$, a contradiction. \item \textbf{Case 2} There exists a $b_sb_k$ chord in $C'$ for some $b_k \in \{b_{p+1}\ldots,b_{q-1}\}$: This case is symmetric to Case 1. \item \textbf{Case 3} There exists a $b_qb_k$ chord in $C'$ for some $b_k \in \{b_{r+1}\ldots,b_{s-1}\}$ (Figure~\ref{fig4}(c)): Let the neighbours of $a_h$ in $C'$ be $b_s,b_{s+1},\ldots,b_m$ and the neighbours of $b_m$ on $C$ be $a_h,a_{h+1},\ldots,a_j$ . Note that since $N_\alpha + N_{\alpha'} \geq 5$, by part (3) of Lemma~\ref{obs:Nalphabeta}, $C'$ should contain at least five vertices. Hence we see that $b_m \neq b_p$. Consider the path $Q=a_xb_qb_{q+1}\ldots b_ra_yb_s\ldots b_ma_j$. As $a_i$ and $a_h$ are of even degree (by Lemma~\ref{evenC}), the path $Q$ is of even length. As $b_q,b_r,b_s$ and $b_m$ are elements in $V(\beta)\cup V(\beta')$, they have even number of neighbours in $C$ (by Lemma~\ref{evenC'}). Hence the path from $a_x$ to $a_j$ in clockwise direction in $C$ is of even length. Consequently, as $C$ is an odd hole, the path $M$ from $a_j$ to $a_x$ in $C$ in clockwise order is of odd length. Suppose that the path $Q$ is chordless. Then combining the path $Q$ with $M$ yields an odd hole (see Figure~\ref{fig4}(c)) consisting of vertices chosen only from $S$ and $Int(C)$, a contradiction. Note that this is true even if $a_j=a_g$ (i.e., $N_\alpha+ N_{\alpha'}=5$). Thus it suffices to prove that the path $Q$ is chordless. We rule out each of the following possible cases of chords appearing in $Q$. \begin{itemize} \item[(a)] There exists a chord connecting a vertex in the set $\{b_{q+1},\ldots,b_r\}$ and a vertex in the set $\{b_s,\ldots,b_m\}$ in $C'$: As $b_qb_{k}$ is a chord in $C'$, this is impossible, as otherwise $G$ cannot be planar. \item[(b)] There exists a $b_qb_m$ chord or a $b_qb_s$ chord: This possibility is ruled out by Lemma~\ref{lem:multiC}. \item[(c)] There exists a chord $b_q b_l$ such that $b_l \in \{b_{s+1},\ldots,b_{m-1}\}$ (Figure~\ref{fig4}(d)): Let $b_qb_l$ be a chord in $C'$ . Let $M'$ be the path from $a_h$ to $a_x$ in clockwise direction in $C$. Since $b_q,b_r$ and $b_s$ are elements in $V(\beta)\cup V(\beta')$, they have even number of neighbours in $C$ (by Lemma~\ref{evenC'}). Hence the path from $a_x$ to $a_h$ in clockwise direction in $C$ is of odd length. Consequently, as $C$ is an odd hole, the path $M'$ must have even length ($\geq 2$). Hence the path $M'$ along with the edges $a_xb_q,b_qb_l$ and $b_la_h$ will induce an odd hole consisting of vertices chosen only from $S$ and $Int(C)$, a contradiction. \end{itemize} Thus we conclude that the path $Q$ is chordless, as required. \item \textbf{Case 4} There exists a $b_rb_k$ chord in $C'$ for some $b_k \in \{b_{p+1}\ldots,b_{q-1}\}$: This case is symmetric to the Case 3. \end{itemize} Hence we conclude that $N_\alpha+ N_{\alpha'}\leq 3$. \end{proof} \begin{figure}[!htb] \centering \includegraphics[scale=0.750]{nalpha.pdf} \caption{$N_\alpha+ N_{\alpha'}\ge 5$.} \label{fig4} \end{figure} By part (3) of Lemma~\ref{obs:Nalphabeta}, We have: \begin{Corollary}\label{nbeta3} $N_\beta+ N_{\beta'}\le 3$. \end{Corollary} Since $N_\alpha+ N_{\alpha'}\leq 3$ and $C$ is an odd hole, $C$ contains at least one $\gamma$ vertex which must be adjacent to a $\beta'$ vertex in $C'$ (by part 2 of Observation~\ref{obs:gamma}). Consequently we have: \begin{Corollary}\label{nbeta1} There exists at least one $\beta'$ vertex in $C'$. That is, $N_{\beta'} \ge 1$. \end{Corollary} \begin{lemma}\label{lem:alphabeta1} Let $a_j$ be an $\alpha'$ vertex in $C$. Let $b_x,b_{x+1},\ldots,b_y$ be the neighbours of $a_j$ in $C'$ in clockwise order. Then at least one among $b_x$ and $b_y$ must be a $\beta$ vertex. \end{lemma} \begin{proof} Suppose that $b_x$ and $b_y$ are $\beta'$ vertices. Let $a_i,a_{i+1}\ldots,a_j$ and $a_j,a_{j+1}\ldots, a_k$ ($j\geq i+3$, $k\geq j+3$) be the neighbours of $b_x$ and $b_y$ respectively in $C$, considered in clockwise order (see Figure~\ref{fig5}(a)). As $b_x$ and $b_y$ have even number ($\geq 4$) of neighbours in $C$ (by Lemma~\ref{evenC'}), the path $P$ from $a_i$ to $a_k$ through $a_j$ in $C$ is chordless and has even length ($\geq 6$). Since $C$ is an odd hole, we see that $a_i \neq a_k$. By Lemma~\ref{lem:multiC}, there is no chord connecting $b_x$ and $b_y$ in $G$. Replacing the path $P$ in $C$ by the edges $a_ib_x,b_xa_j,a_jb_y$ and $b_ya_k$ induces an odd hole in $G$ consisting of vertices chosen only from $S$ and $Int(C)$, a contradiction. Hence at least one among $b_x$ and $b_y$ must be a $\beta$ vertex. \end{proof} \begin{figure}[!htb] \centering \includegraphics[scale=0.75]{beta31.pdf} \caption{(a) $N_{\beta'}=3$ and $N_\delta\neq 0$ (b) $b_x$ is a $\beta'$ vertex and both $a_i$ and $a_j$ are $\alpha'$ vertices. } \label{fig5} \end{figure} Since there exists at least one $\alpha'$ vertex in $C$ (by Corollary~\ref{cor:nalpha1}), we have: \begin{Corollary} \label{cor:nbeta1} $N_\beta \ge 1$. \end{Corollary} As $N_{\beta}\geq 1$ and $N_{\beta'} \geq 1$ (by Corollary~\ref{cor:nbeta1} and Corollary~\ref{nbeta3}), we have $N_{\beta}+N_{\beta'}\geq 2$. Moreover, by part (3) of Lemma~\ref{obs:Nalphabeta} and Corollary~\ref{cor:numalpha}, $N_{\beta}+N_{\beta'} (= N_{\alpha}+N_{\alpha'})$ is odd and by Corollary~\ref{nbeta3}, $N_{\beta}+N_{\beta'}\leq 3$. Thus we have: \begin{Observation}\label{Obs:nbeta2} $N_{\alpha}+N_{\alpha'}=N_{\beta}+N_{\beta'}=3$. \end{Observation} \begin{lemma}\label{lem:betaalpha1} Let $b_x$ be a $\beta'$ vertex in $C'$ and $a_i,a_{i+1},\ldots,a_j$ be the neighbours of $b_x$ in $C$ in clockwise order. If $N_{\alpha}\neq 0$ then at least one among $a_i$ and $a_j$ must be an $\alpha$ vertex. \end{lemma} \begin{proof} For the sake of contradiction assume that $a_i$ and $a_j$ are $\alpha'$ vertices (see Figure~\ref{fig5}(b)). Let $b_z,b_{z+1}\ldots b_x$ and $b_x,b_{x+1},\ldots,b_y$ be the neighbours of $a_i$ and $a_j$ in $C$ respectively in clockwise order. Let $a_k$ be an $\alpha$ vertex in $C$. By Observation~\ref{Obs:nbeta2}, $a_i$, $a_j$ and $a_k$ must be the only vertices in $C$ that are not $\gamma$ vertices. Hence $b_y$ and $b_z$ must be neighbours of $a_k$ and $b_yb_z$ must be an edge in $C'$. As $a_i$ has two neighbours in $C'$ which are not $\delta$ vertices ($b_x$ and $b_z$), we conclude using part (1) of Observation~\ref{obs:gamma} that $b_y$ cannot be a neighbour of $a_i$. Similarly, $b_z$ cannot be a neighbour of $a_j$. Moreover, there cannot be a chord between $b_x$ and $b_y$ or between $b_z$ and $b_x$ (by Lemma~\ref{lem:multiC}). Consequently, the vertices $a_i,b_x,a_j,b_y, b_z$ should induce an odd hole which contains vertices only in $C$ and $Int(C)$, a contradiction. Hence at least one among $a_i$ and $a_j$ must be an $\alpha$ vertex. \end{proof} \begin{lemma} If $N_\alpha=0$, then there exist a $\beta'$ vertex $b_i$ and a $\delta$ vertex $b_x$ satisfying the following: \begin{itemize}\label{lem:nalpha0} \item[(a)] $b_i$ is the unique $\beta'$ vertex in $C'$. \item[(b)]$b_ib_x$ is a chord in $C'$. \item[(c)]Every vertex in $C$ is adjacent to either $b_i$ or $b_x$. \end{itemize} \end{lemma} \begin{proof} \begin{itemize} \item[(a)] By Corollary~\ref{nbeta1}, there exists at least one $\beta'$ vertex in $C'$. Also by Corollary~\ref{cor:nbeta1}, there exists at least one $\beta$ vertex in $C'$. As $N_\beta + N_{\beta'}=3$ (by Observation~\ref{Obs:nbeta2}), it is enough to prove that $N_{\beta'} \neq 2$. Assume that $N_{\beta'} = 2$. Let $b_i$ and $b_j$ be two consecutive $\beta'$ vertices in clockwise order in $C$. Then $b_i$ and $b_j$ must have a common neighbour (say $a_k$) in $C$. As $N_\alpha=0$ and $N_\alpha+N_{\alpha'}>0$, $a_k$ must be an $\alpha'$ vertex. But this is not possible by Lemma~\ref{lem:alphabeta1}. Therefore, $N_{\beta'} = 1$. \item[(b)] By Observation~\ref{Obs:nbeta2} and part (a), $N_\beta=2$. Let $b_j$ and $b_k$ be the $\beta$ vertices and $b_i$ be the $\beta'$ vertex in $C'$. Let $a_p,a_{p+1},\ldots,a_q$ ($q \geq p+3$) be the neighbours of $b_i$ in $C$ arranged in clockwise order (see figure~\ref{fig6}(a)). Let $a_q$ and $a_r$ be the neighbours of $b_j$ and let $a_r$ and $a_p$ be the neighbours of $b_k$ in $C$ in clockwise order. Note that $a_p,a_q$ and $a_r$ are $\alpha'$ vertices by assumption. Hence no two vertices from the set $\{b_i, b_j, b_k\}$ are consecutive on $C'$. Note that $b_j,b_{j+1},\ldots,b_k$ are the neighbours of $a_r$ in $C'$ Then the vertices $a_p,b_i,a_q,b_j,b_{j+1},\ldots,b_k,a_p$ forms an odd cycle (say $C''$). Since $C''$ contains vertices only in $C$ and $Int(C)$, it cannot be an odd hole. Hence, there must be at least one chord inside $C''$. However, there is no chord between any two vertices in $\{b_i,b_j,b_k\}$ and between any two vertices in $\{b_j,b_{j+1},\ldots,b_k\}$ (by Observation~\ref{Obs:triangle}). Hence the only possibility for the chord is $b_ib_x$ such that $x\in\{j+1,\ldots,k-1\}$ (see Figure~\ref{fig6}(b)). \item[(c)] By Part (a), since $b_i$ is the unique $\beta'$ vertex in $C'$, every $\gamma$ vertex in $C$ must be adjacent to $b_i$ (part 2 of Observation~\ref{obs:gamma}). Moreover as $N_\alpha=0$, $b_i$ must have two $\alpha'$ vertices (say $a_p$ and $a_q$) in $C$ as neighbours. Consequently, as $N_{\alpha'}=3$ (Observation~\ref{Obs:nbeta2}), the only one vertex that is not a neighbour of $b_i$ in $C$ is an $\alpha'$ vertex, say $a_r$ (see Figure~\ref{fig6}(b)). By part (b) there exists a chord $b_ib_x$ between the $\beta'$ vertex $b_i$ and a $\delta$ vertex $b_x$ in $C'$. As $b_x$ is a $\delta$ vertex, it has exactly one neighbour on $C$. This neighbour cannot be $a_p$ (or $a_q$) as otherwise the vertices $b_i,b_x$ and $a_p$ (respectively $b_i,b_x$ and $a_q$) will form a separating triangle in $G$. Hence $a_r$ is the neighbour of $b_x$ in $C$. \end{itemize} \end{proof} \begin{Corollary}\label{cor:alpha0} If $N_\alpha=0$, then there exist a chord $b_ib_x$ in $C'$ such that the boundary of the exterior face of the local neighbourhood of $b_ib_x$ is the odd hole $C$. \end{Corollary} Note that Corollary~\ref{cor:alpha0} gives a local characterization for the odd hole $C$ when $N_{\alpha}=0$. That is, there exists an edge in $G$, the exterior boundary of its local neighbourhood is the hole $C$. Our goal is to obtain a similar local characterization when $N_{\alpha}>0$. \begin{figure}[!htb] \centering \includegraphics[scale=0.70]{nalpha01.pdf} \caption{$N_{\alpha'}=3$ } \label{fig6} \end{figure} For the rest of the paper, we use the following notation. Let $A$ be the set of all vertices in $C$ of type $\alpha$ or $\alpha'$ and let $B$ be the set of all vertices in $C'$ of type $\beta$ or $\beta'$. By Observation~\ref{Obs:nbeta2}, $|A|=|B|=3$. Let $a_i,a_j$ and $a_k$ (respectively $b_x,b_y$ and $b_z$) be the vertices of $A$ (respectively $B$) listed in clockwise order in $G'$. There exists at least one $\beta$ vertex in $B$ (by Corollary~\ref{cor:nbeta1}) and at least one $\alpha'$ vertex in $A$ (by Corollary~\ref{cor:nalpha1}). We fix $b_y$ to be a $\beta$ vertex in $B$ and $a_i$ to be an $\alpha'$ vertex in $A$. The next lemma shows that every vertex in $C$ must be a neighbour of either $b_x$ or $b_z$ (or both). \begin{lemma}\label{lem:betaminus} Let $b_y\in B$ be a $\beta$ vertex. Then the boundary of the exterior face of the subgraph induced by the closed neighbourhood of $B\setminus \{b_y\}$ in $G$ is the odd hole $C$. \end{lemma} \begin{proof} Since $b_y$ is a $\beta$ vertex, $b_y$ must have exactly two neighbours in $C$ - say $a_i$ and $a_j$ in clockwise order. Further, we have $j=i+1$ and $a_ia_j$ will be an edge in $C$. (See Figure~\ref{fig7}(a)). Moreover, $a_i$ and $a_j$ cannot have another common neighbour $b_t$ for any $t\in \{x,z\}$ as otherwise $b_t,a_i$ and $a_j$ will form a separating triangle with $b_y$ in the interior. As each of $a_i$ and $a_j$ must have a neighbour in $B$ distinct from $b_y$ (by Observation~\ref{obs:gamma}), we may assume without loss of generality that $b_x$ is a neighbour of $a_i$ and $b_z$ is a neighbour of $a_j$. Thus, each neighbour of $b_y$ in $C$ is either a neighbour of $b_x$ or a neighbour of $b_z$. Since every vertex in $C$ must be a neighbour $b_x$ or $b_y$ or $b_z$ (Lemma~\ref{obs:Nalphabeta}), it follows that every vertex in $C$ is a neighbour of $b_x$ or $b_z$. The lemma follows since $C$ is assumed to be the boundary of the exterior face of the subgraph induced by the closed neighbourhood of $B$. \end{proof} Since Corollary~\ref{nbeta1} guarantees that $C'$ contains a $\beta$ vertex, we now have a local characterization for the odd hole $C$ in the sense that $C$ will be the exterior boundary of the local neighbourhood of the two element set $\{b_x,b_z\}$. We now strengthen Lemma~\ref{lem:betaminus} by showing that there exists an edge in $G$ (connecting two vertices in $C'$) whose local neighbourhood has $C$ as its exterior boundary. \begin{lemma}\label{lem:onebeta} There exists two vertices $b_p$ and $b_q$ in $C'$ such that: \begin{itemize} \item $b_pb_q$ is an edge in $G$. \item The boundary of the exterior face of the closed neighbourhood of $b_pb_q$ is the odd hole $C$. \end{itemize} \end{lemma} \begin{proof} If $N_\alpha=0$, then the result follows by Corollary~\ref{cor:alpha0}. Hence, assume that $N_\alpha>0$. Recall that we have assumed $b_y$ to be a $\beta$ vertex. Therefore, if $b_x$ and $b_z$ are adjacent in $C'$, setting $b_pb_q=b_x b_z$ suffices (by Lemma~\ref{lem:betaminus}). If $b_x b_z$ are not adjacent in $C'$, the common neighbour of $b_x$ and $b_z$ on $C$ must be an $\alpha'$ vertex. By Lemma~\ref{lem:alphabeta1}, either $b_x$ or $b_z$ is a $\beta$ vertex and by Corollary~\ref{nbeta1}, at least one of them must be a $\beta'$ vertex. Hence, without loss of generality, we may assume that $b_x$ is a $\beta$ vertex and $b_z$ is a $\beta'$ vertex. By Lemma~\ref{lem:betaalpha1}, at least one of the neighbours of $b_z$ must be an $\alpha$ vertex. Therefore, the common neighbour of $b_z$ and $b_y$ in $C$ must be an $\alpha$ vertex. This implies that $b_z b_y$ is an edge of $C'$ (see Figure~\ref{fig7}(b)). Since $b_x$ is a $\beta$ vertex, every neighbour of $b_x$ in $C$ must be a neighbour of $b_y$ or $b_z$. Hence, by Lemma~\ref{lem:betaminus}, setting $b_pb_q=b_z b_y$ suffices to complete the proof. \end{proof} \begin{figure} \centering \includegraphics[scale=0.75]{onebeta.pdf} \caption{ (a)$N_{\beta}=1$, $N_{\alpha'}=1$ (b)$N_{\beta}=2$, $N_{\alpha'}=2$ and $b_xb_z$ is not an edge in $C'$} \label{fig7} \end{figure} Let us now consolidate our observations so far. Recall that our objective was to prove Theorem~\ref{thm:main-thm}, to obtain a local characterization for a plane near-triangulation to be perfect. Since the graph can be decomposed into induced $2$-connected subgraphs containing no separating triangles or edge separators without affecting the perfectness of the graph, it was sufficient to limit the attention to W-triangulations. We noted that if any internal vertex $x$ in a W-triangulation has on odd degree, the result was immediate because the exterior face of the closed neighbourhood of $x$ would have been an odd hole. Consequently, the core of the problem was to characterize odd holes in even W-near-triangulated (induced) subgraphs of the original plane near-triangulation. If an even W-near-triangulation $G$ is non-perfect, we considered a \textit{minimal odd hole} $C$ in $G$ such that there is no other odd hole in $C \cup Int(C)$. Then we considered the cycle $C'$ forming the boundary of the subgraph $H$ induced by the vertices in $Int(C)$. We showed that either (i) $C'$ is a (non-separating) triangle, the exterior face of the closed neighbourhood of which is the odd hole $C$ or (ii) there exists an edge $b_pb_q$ connecting vertices in $C'$ such that the boundary of the exterior face of the closed neighbourhood of the edge $b_pb_q$ is the odd hole $C$ (Lemma~\ref{lem:onebeta}). Thus we have: \begin{Corollary}\label{evenwtriangulation} A W-triangulation $G$ is not-perfect if and only if $G$ contains at least one among the following: \begin{itemize} \item a vertex $x$ (of odd degree), the exterior boundary of the local neighbourhood of which, is an odd hole. \item an edge $xy$, the exterior boundary of the local neighbourhood of which, is an odd hole. \item a facial triangle $xyz$, the exterior boundary of the local neighbourhood of which, is an odd hole. \end{itemize} \end{Corollary} From this, Theorem~\ref{thm:main-thm} is immediate. We make note of a few details about Theorem~\ref{thm:main-thm} which are of significance while translating Theorem~\ref{thm:main-thm} into an algorithm for checking whether a plane near-triangulation is perfect. Let $G$ be a plane near-triangulation that is not perfect. Let $X=xyz$ be a facial triangle in an induced even W-near-triangulated subgraph $G'$ of $G$, such that exterior boundary of the local neighbourhood of $X$ induces an odd hole in $G$. It must be noted that $X$ need not necessarily be a facial triangle in the original graph $G$, but could be a separating triangle in $G$. Hence, identification of the separating triangles in $G$ becomes a significant algorithmic consideration. It turns out this task is easy due to the algorithm by \citet{kant1997more} that identifies the separating triangles and the W-triangulated subgraphs of $G$ in linear time. The second point to note is the following. We \textit{cannot} conclude from Theorem~\ref{thm:main-thm} that in a non-perfect near-triangulation $G$, we can find an induced subgraph $X$ which is either a vertex, an edge or a triangle, such that the neighbours of $X$ induces an odd hole in $G$. That is, it is necessary to inspect the \textit{exterior boundary} of the local neighbourhood of each vertex, edge and face to detect an odd hole. Figure~\ref{fig9} gives an example of a graph illustrating this fact. In this example, the exterior boundary of the local neighbourhood of the edge $ip$ induces the odd hole $abcde$. However, the subgraph induced by the neighbours of the edge $ip$ (or any other edge or face) does not induce an odd hole. The requirement to check the exterior boundary of the local neighbourhood of each edge and each face results in quadratic time complexity for the algorithm described in the next section. If a W-near-triangulation $G$ does not contain any induced wheel on five vertices, then it is known that $G$ is not perfect if and only if it contains a vertex or a face whose neighbours induce an odd hole~\cite{SalamCWKS19}. Consequently, for this restricted class of graphs, checking perfectness requires only sub-quadratic time. \begin{figure} \centering \includegraphics[scale=0.7]{eg1.pdf} \caption{The neighbours of the edge $ip$ does not induce an odd hole though the boundary of its local neighbourhood induces an odd hole.} \label{fig9} \end{figure} \section{Recognition of perfect plane near-triangulations}\label{perfect plane} In this section, we describe an $O(n^2)$ algorithm to determine whether a given plane near-triangulation $G$ of $n$ vertices is perfect. The algorithm essentially checks the conditions of Theorem~\ref{thm:main-thm}, using well known techniques for handling planar graphs. For the sake of clarity, the steps of the algorithm and its analysis are presented in detail. Initially, we assume that $G$ is a plane triangulation. Later, we will describe how to handle near-triangulations as well. Given a plane triangulation $G$, using the linear time algorithm of \citet{kant1997more} for identifying separating triangles in a plane triangulation, $G$ can be split into its $4$-connected blocks. It is well known that a plane triangulation is $4$-connected if and only if it is free of separating triangles. Consequently, the $4$-connected blocks identified by Kant's algorithm are precisely the maximal induced W-triangulations in $G$. We will call each such $4$-connected block a {\em W-component} of $G$ \cite{SalamCWKS19}. We have already seen that $G$ is perfect if and only if all its W-components are perfect. Hence, our task reduces to the problem of finding a quadratic time algorithm for checking whether a given plane triangulation without separating triangles is perfect. We split our task into four stages, as described below. \subsection{Preprocessing}\label{preprocess} Let $H$ be a plane triangulation on $n$ vertices, without separating triangles. Suppose we are given the adjacency list of $H$ as input. We will first compute a planar straight line embedding of $H$ on a $n \times n$ grid, using the linear time algorithm of \citet{schnyder1990embedding}. This essentially gives us the $(x, y)$ coordinates of each vertex of $H$. Using these coordinates, the slopes of all the edges of $H$ can be computed in $O(m)$ time, where $m$ is the number of edges of $H$. Note that, for a planar graph, $m=O(n)$. It would be useful to preprocess the adjacency list of $H$ at this point, so that for each vertex $v$, its neighbours are arranged in the descending order of the slopes of edges incident at $v$. This preprocessing can be done in $O(m \log{n})$ time. The next three stages involve verifying the conditions of perfectness mentioned in Theorem~\ref{thm:main-thm} one by one. \subsection{Checking vertex degrees}\label{vertexdegree} If any vertex $u$ of $H$ is of odd degree, the open neighbourhood $N_{H}(u)$ induces an odd hole and $H$ is not perfect. Checking the degrees of all vertices can be easily done in time linear in $n$. If every vertex of $H$ is of even degree, we need to check the remaining conditions to verify the perfectness of $H$. \subsection{Checking the boundary of the local neighbourhood of each edge} \label{sec:neighbourhoodedge} The next step is to check if the boundary of the local neighbourhood of any edge of $H$ is an odd hole. For each edge $uv$ of $H$, define $S_{uv}=N(u) \cup N(v) \cup \{u, v\}$ and construct an indicator array $A_{uv}$ of length $n$, where $A_{uv}[i]=1$ if vertex $v_i \in S_{uv}$ and zero otherwise. The construction of these arrays can be done in $O(mn)=O(n^2)$ time in total. Now, we construct $m$ plane subgraphs of $H$, one corresponding to each edge of $H$. The graph $H_{uv}$ will be the induced subgraph of $H$ on the vertex set $S_{uv}$. We store the coordinate position information of each vertex of $H_{uv}$, by copying the same from $H$. To get the sorted adjacency list of $H_{uv}$, we start with a copy of the sorted adjacency list of $H$. Then, mark the lists of vertices not in $S_{uv}$ as deleted. For each vertex $x$ in $S_{uv}$, go through the adjacency list $x$ in order, and when an edge $xv_i$ such that $A_{uv}[i]=0$ is encountered, then mark the edge as deleted. It takes only $O(m+n)$ time for obtaining the sorted adjacency list of $H_{uv}$, in this manner. The construction of subgraphs $H_{uv}$ corresponding to each edge $uv$ of $H$ along with the information mentioned above, takes only $O(m (m+n))=O(n^2)$ time in total. Now, we describe a procedure to check if the exterior boundary of an induced subgraph $H_{uv}$ constructed above is an odd hole. It is easy to see that the exterior boundary of $H_{uv}$ is an induced cycle. So, it suffices to identify the vertices on the exterior boundary and check the parity of their count. Since we have coordinates of vertices from a straight line drawing, this is easy. First, identify the left most vertex of $H_{uv}$ in the straight line embedding. This only involves identifying a vertex of $H_{uv}$ with the smallest $x$ coordinate. Clearly, this vertex is on the exterior face of $H_{uv}$. Let this vertex be $l$. Recall that the adjacency list of each vertex is sorted in the decreasing order of slopes. The edge with the largest slope incident at vertex $l$ must be on the exterior boundary of $H_{uv}$. The other endpoint of this edge can be identified as the next vertex on the boundary of $H_{uv}$. After identifying a new vertex $x$ on the boundary, it is easy to identify the next one. Suppose W is the vertex identified before $x$. If $y$ is the vertex that succeeds W (in the cyclic order) in the adjacency list of $x$, then $y$ is the next vertex on the boundary of $H_{uv}$. When this procedure encounters the initial vertex $l$ again, we would have identified all the vertices on the boundary of $H$. Thus, identifying the exterior boundary of $H_{uv}$ and checking whether it is an odd hole, can be done in $O(m+n)$ time. For checking the boundaries of all subgraphs $H_{uv}$ we constructed, total time required is only $O(m (m+n))=O(n^2)$. If this check fails to find an odd hole, we have to check the boundary of the local neighbourhood of each triangle, as described below. \subsection{Checking the boundary of the local neighbourhood of each triangle}\label{sec:neighbourhoodtriangle} Since $H$ is free of separating triangles, triangles of $H$ are precisely its faces. A listing of all the faces of $H$ can be done in linear time, by traversing the adjacency list of every vertex once. Checking whether the exterior boundary of the closed neighbourhood of a triangle $uvw$ forms an odd hole can be done in a way very similar to the method we discussed in the previous subsection. For each triangle $uvw$, we will define a set $S_{uvw}=N(u) \cup N(v) \cup N(w) \cup \{u, v, w\}$ and an indicator array $A_{uvw}$ for $S_{uvw}$. Then, we can construct plane subgraphs $H_{uvw}$, the induced subgraph of $H$ on the vertex set $S_{uvw}$. The method of checking whether the boundary of $H_{uvw}$ is an odd hole or not, is the same as the method described earlier for $H_{uv}$. The number of subgraphs to be processed is the number of faces of $H$, which is linear in $n$. Hence, the time required for checking the boundaries of each such subgraph is again $O(n^2)$ only. \subsection{Handling plane near-triangulations} The method described above for recognizing planar perfect graphs can be extended to recognize perfect plane near-triangulations by the simple modifications described below, without affecting the complexity of the algorithm. The strategy is to triangulate the plane near-triangulation; use the algorithm of \citet{kant1997more} to identify the W-components of the triangulated graph; and retrieve the W-components of the original plane near-triangulation. Let $G(V,E)$ be a plane near-triangulation. If $G$ is not $2$-connected, in linear time we can find the $2$-connected components of $G$ using depth first search, and work on each component. Hence, we assume without loss of generality that $G$ is $2$-connected. We can embed $G$ into an $n\times n$ grid using the algorithm of \citet{schnyder1990embedding} in $O(n)$ time, preprocess the adjacency list of $G$ as described in Subsection~\ref{preprocess} in $O(m\log n)$ time and identify the vertices on the boundary of exterior face of $G$ by using the method discussed in Subsection~\ref{sec:neighbourhoodedge} in $O(n)$ time. Let $v_1,v_2,\ldots,v_k,v_1$ be the cycle forming the the boundary of exterior face of $G$. Construct a plane triangulation $G'$ from $G$ by adding a new vertex $v_0$ on the exterior face of $G$ and adding edges from $v_0$ to $v_i$ for every $i \in \{1,2,\ldots,k\}$. The adjacency list of $G$ can be modified to get the adjacency list of $G'$ in linear time. Note that, as $G'$ is a triangulation, it contains no edge separators. We can use the linear time algorithm of \citet{kant1997more} for identifying separating triangles in the plane triangulation $G'$ and decompose $G'$ into W-components. Note that $v_iv_j$ is an edge separator of $G$ if and only if it is a chord connecting two vertices on the external face of $G$, forming a separating triangle $v_iv_jv_0$ in $G'$. Conversely, a separating triangle in $G'$ containing $v_0$ must be of the form $v_0v_iv_j$ for some $i,j\in \{1,2,\ldots, k\}$, with $v_iv_j$ forming a chord connecting two vertices on the exterior face of $G$. Moreover, every separating triangle in $G$ will be a separating triangle in $G'$ and every separating triangle in $G'$ that does not contain $v_0$ is a separating triangle in $G$. Hence, we have the following observation. \begin{Observation}\label{obs:reduction} Let $G_1',G_2',\ldots , G_r'$ be the W-components of $G'$. Let $G_i=G_i'$ if $v_0\notin V(G_i')$ and $G_i=G_i'\setminus\{v_0\}$ otherwise. Then, $G_1,G_2,\ldots ,G_r$ are precisely the W-components of $G$. \end{Observation} As a consequence of Observation~\ref{obs:reduction}, it suffices to decompose $G'$ into its W-components and remove the vertex $v_0$ from each W-component to recover the W-components of $G$. Removing $v_0$ from all the W-components of $G'$ requires only traversing the adjacency lists of all the graphs once and hence possible in $O(n)$ time. It is easy to verify that the $O(n^{2})$ method described earlier for checking perfectness of the W-components of a plane triangulation suffices for handling the W-components of the plane near-triangulation $G$ as well. Thus, it follows that checking the perfectness of plane near-triangulations requires only $O(n^{2})$ time. \section{Acknowledgment} We thank Sunil Chandran, IISc. Bangalore and Ajit A. Diwan, IIT Bombay for discussions and suggestions. We thank the latter also for the example in Figure~\ref{fig9}. \bibliographystyle{plainnat}
{'timestamp': '2019-07-30T02:01:27', 'yymm': '1906', 'arxiv_id': '1906.06200', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06200'}
arxiv
\section{Introduction} The application of deep neural networks to speech recognition has achieved tremendous success due to its superior performance over the traditional hidden Markov model with Gaussian mixture emissions. It has become the dominant acoustic modeling approach for speech recognition, especially for large vocabulary tasks. While it has strong modeling power through multiple layers of nonlinear processing, it is still not immune to many known problems such as the mismatch of training and test data. When tested in mistach conditions, performance degradation can still be expected. To address this problem, many adaptation techniques have been proposed. Robust speech recognition methods can be classified into two categories: feature-space approaches and model-space approaches. Compared with model-space approaches, feature-space approaches do not need to modify or retrain the acoustic model. Instead, various operations can be performed on the acoustic features to improve the noise robustness of the features. As for the model-space approaches, rather than focusing on the modification of features, the acoustic model parameters are adjusted to match the testing data. In the category of feature-space approaches popular strategies include using speaker adaptive features~\cite{povey2013}, or augmenting input features with speaker information~\cite{Miao2014c} as well as incorporating auxiliary information such as i-vector and speaker code into the network~\cite{Tan2015,Kundu2016}. Traditionally this also includes feature normalization as the most straightforward strategy to eliminate the training-testing mismatch. This includes strategies like cepstral mean subtraction (CMS)~\cite{Westphal97theuse}, cepstral mean and variance normalization (CMVN)~\cite{molau2003}, and histogram equalization (HEQ)~\cite{hilger2006}. A further method to increase the robustness against noise is adding a variety of noise samples to clean training data, known as multi-style or multi-condition training~\cite{hirsch2000aurora}. However, due to the unpredictable nature of real-world noise, it is impossible to account for all noise conditions that may be encountered. Rather than augmenting the features, the acoustic model parameters can be compensated to match the testing conditions. A simple example of modifying the models is to re-train the whole speaker independent (SI) deep neural network (DNN) model, or only certain layer(s) of the model on adaptation data~\cite{Liao2013,dong2013}. To avoid over-fitting, regularization such as in \cite{dong2013} is applied. Another approach is to insert and adapt speaker dependent linear layers into the network to transform either input feature~\cite{Neto1995}, top-hidden-layer output~\cite{Li2010}, or hidden layer activations~\cite{Gemello2006}. Finally, the acoustic model can be trained for different conditions separately such as in~\cite{Wu2015a,Delcroix2015,Tan2016}. This work combines feature-space approaches and model-space approaches and evaluates if they provide complementary improvements in word error rate (WER). i-vectors~\cite{Dehak2011} are employed and optimized as a feature-space approach and based on our prior work~\cite{kitza18:interspeech}, affine transformations (AT) are used for speaker and environment adaptation. In this paper, we combine speaker dependent model transforms with i-vectors as an input to the neural network to perform instantaneous speaker and environment adaptation. To our knowledge i-vectors have not yet been combined with speaker dependent affine transformations within a bidirectional LSTM Network. Therefore, we would like to evaluate how the adaptation performance behaves if they are combined. The effectiveness of adaptation by speaker dependent transformations in regards to the depth of the network is reevaluated in the context of i-vectors. Further, detailed investigations into the structure of the transformations have been done. Also the best methods to train them have been evaluated. We also compare the performance of speaker and environment adaptation. The remainder of this paper presents our system in detail. Section 2 describes prior work, in section 3 we discuss our implementation of the i-vector adaptation and affine transformation adaptation. Experimental results are analysed in Section 4 followed by a conclusion. \section{Related work} The proposed work is builds on our prior work~\cite{kitza18:interspeech}, where we investigated the significance of the position of speaker dependent affine transformations within a bidirectional LSTM Network using a separate transformation for the forward- and backward-direction. It used a similar methodology as presented in \cite{Liu2016} and \cite{Miao2015a}, where affine transformation to adapt an LSTM acoustic model were used. However, here only speaker independent input features were used. Other works in this field include \cite{Zhao2016,Xue2014,Trmal2010,Li2010,Huang2018} and \cite{Gemello2006}, where feedforward neural networks were employed. I-vectors have been used sucessfully as a sole adaptation method using time-delay neural network (TDNN)~\cite{Peddinti2015} as well as BLSTM acoustic models for automatic speech recognition~\cite{Xiong2018,Kanda2018}. \section{Adaptation} In this section, we describe the i-vector estimation process adopted during training and decoding as well as the training procedure for the affine transformations. \subsection{i-vectors} In this paper we use a i-vector adapted neural network acoustic model. On each frame we append a i-vector to the 40-dimensional Gammatone Filterbank (GT)~\cite{schluter2007} input of the neural network. Most prior work report that they use Mel-frequency cepstral coefficients (MFCCs)~\cite{Davis1980} to estimate the i-vectors even if other features are used in the acoustic model~\cite{Peddinti2015,Xiong2018,Xiong2016}. But we noticed that the i-vector adaptation was not sufficiently effective in adapting to test signals when using MFCCs to estimate the i-vectors. Therefore, we compared MFCC to GT features without further processing as well as with concatenated first and second order derivatives and with temporal context and linear discriminant analysis (LDA) for dimension reduction. The results can be seen in Table~\ref{tab:feature}. Using Gammatone features with a context of 9 frames reduced to 60 dimensions with LDA gives us significantly better performance. We did not check if MFCCs would be better if the acoustic model would also be trained on them. \begin{table}[th] \caption{Comparison of features used for universal background model training. The i-vectors were extraced only from speech frames and have a dimension of 100. Word error rate is given on the full Hub5'00 dataset. The acoustic model is a BLSTM trained on gammatone filterbank features.} \label{tab:feature} \centering \begin{tabular}{l|l|l} \textbf{i-vectors} & \textbf{UBM Features} & \textbf{WER {[}\%{]}} \\ \hline no & --- & 14.4 \\ \hline yes & MFCC & 14.3 \\\cline{2-3} & \quad+derivatives & 14.0 \\\cline{2-3} & \quad+context+LDA & 14.2 \\\cline{2-3} & GT & 14.2 \\\cline{2-3} & \quad+derivatives & 13.9 \\\cline{2-3} & \quad+context+LDA & \textbf{13.5} \\ \end{tabular} \end{table} \subsubsection{i-vector Extraction} The i-vectors are estimated in the same manner for training and testing datasets. In order to ensure sufficient variety of the i-vectors in the training data, rather than estimating a separate i-vector per speaker, we estimate a single i-vector for each utterance. The i-vectors are estimated only on speech frames. Feature frames which contain silence or noise are discarded prior to the extraction. For the training dataset, the silence frames are classified based on a framewise state alignment obtained from a Hidden markov model with Gaussian mixture emissions system. For the testing datasets, there are two options. On the one hand, a first pass decode of the audio data using the GMM-HMM system can be used. On the other hand, a two-class Gaussian Mixture Model (GMM) is trained to distinguish between speech and non-speech events to filter out long portions of non-speech data~\cite{magrin2001overview, kingsbury13:cantonese}. The final part of i-vector extraction is normalization. Rather than using i-vectors that are derived from a total variability model directly, it is typically more feasible to apply some form of normalization first. The basic form is to normalize a given i-vector $v \in \mathbb{R}^D$ with $D \in \mathbb{N}$ to have unit euclidean norm. Another option is to scale $v$ in proportion to the square root of its dimension. The length normalized i-vector $\hat{v}$ is then given by \begin{equation*} \hat{v} = \frac{v}{||v||_2} \cdot \sqrt{D}. \end{equation*} Finally, Radial Gaussianization (RG)~\cite{Lyu2009}, which is used successfully in speaker diarization tasks~\cite{Gracia2011}, can be used for i-vector normalization. Table~\ref{tab:dim} shows the word error rate given a combination of i-vector dimension and length normalization. It can also be seen, that the adaptation performance dependents significantly on the dimension and normalization. \begin{table}[th] \caption{WERs (in \%) on Hub5'00 for i-vectors of different dimension and normalization based on GT+context+LDA features.} \label{tab:dim} \centering \begin{tabular}{@{}l|l|l|l@{}} \textbf{i-vector} & \multicolumn{3}{c}{\textbf{WER [\%] for Dimension}} \\ \textbf{normalization} & 50 & 100 & 200 \\ \hline --- & 14.9 & 14.3 & 14.8 \\ \hline Unity & 13.9 & 13.7 & 13.5 \\ \hline Square root & 14.2 & 13.7 & \textbf{13.3} \\ \hline RG & 14.0 & 13.4 & 13.4 \\ \end{tabular} \end{table} \subsection{Affine Transformations} A practical constraint for a large scale speech recognition system is that the system needs to serve many users. Therefore, the user-specific parameters should be kept small. The main goal of this investigation is to develop methods to effectively adapt the speaker independent model using a minimal number of speaker-specific parameters. Two approaches are studied in this work: Adapting existing neural network components and adapting inserted affine transformation between layers. The affine transformations are realized as additional layers in the neural network. They usually have the same dimension as the preceding layer and the identify function $f(z) = z$ is employed as the activation function for these additional layers. The speaker-specific parameters are given as the weights $W_s$, which are initialized to the unity matrix, and biases $b_s$, which are initialized to $0.0$. These are trained for each speaker separately. According to the different positions of the linear layers, they are denoted as Linear Input Network (LIN)~\cite{Neto1995}, Linear Hidden Network (LHN)~\cite{Gemello2006} and Linear Output Network (LON)~\cite{Li2010}, where LHN can be inserted to any position between two successive hidden layers. The LIN linearly transforms the observed acoustic features before forwarding them to the speaker independent model, similar to a constrained maximum likelihood linear regression (CMLLR). When adding a affine transformation to the output layer of the neural network, the transformation is inserted before the softmax function. A first pass decoding is performed using a speaker-independent model. This is used to generate the targets for the unsupervised adaptation process. The adaptation datasets were split randomly into separate training and cross-validation sets, where 90\% were used for training and 10\% for cross-validation. The cross-validation frame accuracy was also used to control the learning rate decay. \section{Experimental Results} The baseline acoustic model was trained on $283$ hours from the Switchboard-1 Release 2 (LDC97S62)~\cite{Godfrey1992} corpus using $40$-dimensional gammatone features without any adaptive feature space transformations, as we did not observe any word error rate reductions with speaker adapted features. The targets were $9001$ tied states. The acoustic model consists of seven BLSTM layers for forward and backward direction, each with a size of $500$. For the training, a dropout~\cite{srivastava2014dropout} probability of $10\%$ is used together with a $L_2$ regularization constant of $0.01$ with an initial learning rate of $0.0005$ that is controlled using the cross-validation frame accuracy (CVFA) based learning rate decay. This approach divides the learning rate by $\sqrt{2}$ if the CVFA did not improve. For further regularization, gradient noise~\cite{neelakantan2015adding} is added with a variance of $0.3$ and focal loss~\cite{lin2017focal} is used with a factor of $2.0$. The models have also been pretrained using a layer-wise pretraining algorithm, which gradually builds up the network. For the first epoch, only a single layer is used and with each consecutive epoch one additional layers are added until the maximum of seven is reached. During decoding, we use a $4$-gram language model which was trained on the transcripts of the acoustic training data ($3$M running words) and the transcripts of the Fisher English corpora (LDC2004T19 \& LDC2005T19) with $22$M running words. More details can be found in~\cite{Tuske2015}. The results are reported on the Hub5'00 evaluation data (LDC2002S09) which contains two types of data, Switchboard (SWBD) -- which is better matched to the training data -- and CallHome English (CHE). The i-vector estimator was trained on the full 283 hour set of training data: this includes the training of the Gaussian mixture model used for the universal background model (UBM), and the estimation of the total-variability (T) matrix. The affine transformation layers are trained using stochastic gradient descent with momentum. In our experience, stochastic gradient descent provides better convergence under a wider set of hyperparameters than more complex algorithms as RMSprop and Nadam. However, the latter show better convergence when the complete acoustic model is trained. The learning rate was set to $10^{-6}$ with a momentum of $0.9$ for all positions. $L_2$-regularization centered on the unity matrix was used with a scale of $0.01$. Beside the \emph{identify} activation function we tried \emph{sigmoid} and \emph{relu} but they consistently underperformed compared to the identify activation function. \begin{table}[th] \caption{WERs (in \%) on Hub5'00 to compare the effectiveness of environment and speaker adaptation at different positions within the acoustic model. The baseline model is a BLSTM without i-vectors.} \label{tab:cluster} \centering \begin{tabular}{l|r|r|r|r|r|r} \textbf{Affine}& \multicolumn{6}{c}{\textbf{Adaptation Target}} \\ \textbf{Trans.} & \multicolumn{3}{c|}{\textbf{Environment}} & \multicolumn{3}{c}{\textbf{Speaker}} \\ \textbf{Layer} & \textbf{SWB} & \textbf{CH} & \multicolumn{1}{l|}{\textbf{Avg.}} & \textbf{SWB} & \textbf{CH} & \textbf{Avg.} \\ \hline --- & 9.7 & 19.1 & 14.4 & 9.7 & 19.1 & 14.4 \\ \hline 1 & 9.7 & 18.7 & \textbf{14.2} & 9.7 & 18.2 & 13.9 \\ 2 & 9.8 & 18.8 & 14.3 & 9.6 & 18.2 & \textbf{13.8} \\ 3 & 9.8 & 18.7 & 14.3 & 9.6 & 18.3 & 13.9 \\ 4 & 9.9 & 18.7 & 14.3 & 9.5 & 18.3 & 13.9 \\ 5 & 9.9 & 19.1 & 14.5 & 9.6 & 18.5 & 14.1 \\ 6 & 9.8 & 19.1 & 14.5 & 9.6 & 18.8 & 14.2 \\\hline all & 9.7 & 19.0 & 14.4 & 9.6 & 18.6 & 14.1 \\ \end{tabular} \end{table} \subsection{Cumulative Adaptation} Table~\ref{tab:cluster} compares systems without i-vectors but with affine transformations adapted to speakers and environments, using different positions for the transformations. For the environment adaptation, the CallHome and Switchboard subsets were used as environments and for speaker adaptation, each recording was treated as a different speaker. From the table, it is clear, that without i-vectors speaker adaptation outperforms environment adaptation. The results are consistent with~\cite{kitza18:interspeech} in the conclusion, that performing adaptation on single layers at the beginning of a neural network is beneficial compared to adapting later layers or the whole network. Table~\ref{tab:cluster_ivec} compares systems with i-vectors and affine transformations adapted to speakers and environments. Comparing these to Table~\ref{tab:cluster}, the relative improvements increase. Although the system uses i-vectors internally for adaptation, the additional information provided by the i-vectors is also beneficial for the second pass adaptation. Further, it can be seen that environment adaptation performs better under these circumstances. Using i-vectors, the performance of environment adaptation, where only a single transformation is trained for CallHome and Switchboard respectively, is the same for CallHome with $16.6\%$ and only slightly worse on Switchboard with $8.7\%$ compared to $8.6\%$. Therefore, it is no longer important to train one affine transformations for each speaker, because the transformation can use the information in the i-vector to do the speaker adaptation. Moreover, the best position for environment adaptation is the first layer compared to the second layer for speaker adaptation. Given these circumstances we tried adapting the first and second layer simultaneously, but there were no further improvements to be gained. We also tried adapting the first layer on the environment adaptation set followed by speaker specific adaptation of the second layer. This also gave no additional improvements. \begin{table}[th] \caption{WERs (in \%) on Hub5'00 to compare the effectiveness of environment and speaker adaptation at different positions within the acoustic model. The baseline model is a BLSTM with i-vectors.} \label{tab:cluster_ivec} \centering \begin{tabular}{l|r|r|r|r|r|r} \textbf{Affine}& \multicolumn{6}{c}{\textbf{Adaptation Target}} \\ \textbf{Trans.} & \multicolumn{3}{c|}{\textbf{Environment}} & \multicolumn{3}{c}{\textbf{Speaker}} \\ \textbf{Layer} & \textbf{SWB} & \textbf{CH} & \multicolumn{1}{l|}{\textbf{Avg.}} & \textbf{SWB} & \textbf{CH} & \textbf{Avg.} \\ \hline --- & 8.9 & 17.7 & 13.3 & 8.9 & 17.7 & 13.3 \\ \hline 1 & 8.7 & 16.6 & \textbf{12.7} & 8.7 & 16.8 & 12.8 \\ 2 & 8.8 & 16.9 & 12.9 & 8.6 & 16.6 & \textbf{12.6} \\ 3 & 8.9 & 17.0 & 12.9 & 8.7 & 16.6 & 12.7 \\ 4 & 8.9 & 17.2 & 13.1 & 8.7 & 16.7 & 12.7 \\ 5 & 8.9 & 17.2 & 13.1 & 8.8 & 16.9 & 12.8 \\ 6 & 8.9 & 17.2 & 13.1 & 8.8 & 17.1 & 13.0 \\ \hline (1,2) & 8.7 & 16.7 & 12.7 & 8.6 & 16.7 & 12.7 \\ \end{tabular} \end{table} \subsection{Sequence Training and RNNLMs} Table~\ref{tab:switchboard} gives detailed word error rates for systems where the cumulative adaptation is used in conjuction with a lattice-based version of state-level minimum Bayes risk (SMBR) training as well as recurrent neural network language models (RNNLM)~\cite{beck19:interspeech}. Similar to the second pass adaptation also SMBR training provides larger relative improvements if i-vectors are used in the baseline. \begin{table}[h] \caption{Detailed WERs (in \%) on Hub5'00 comparing the influence of i-vectors, SMBR, and environment adaptation with affine transformation (AT). WERs are given for count based language models and RNNLM.} \label{tab:switchboard} \centering \begin{tabular}{llllrrr} \textbf{} & \textbf{} & \textbf{} & \multicolumn{1}{l|}{\textbf{}} & \multicolumn{3}{c}{\textbf{Hub5'00}} \\ \multicolumn{1}{l|}{\textbf{AT}} & \multicolumn{1}{l|}{\textbf{i-vec.}} & \multicolumn{1}{l|}{\textbf{SMBR}} & \multicolumn{1}{l|}{\textbf{LM}} & \multicolumn{1}{l|}{\textbf{SWBD}} & \multicolumn{1}{l|}{\textbf{CH}} & \multicolumn{1}{l}{\textbf{Avg.}} \\ \hline \multicolumn{1}{l|}{no} & \multicolumn{1}{l|}{no} & \multicolumn{1}{l|}{no} & \multicolumn{1}{l|}{4-gram} & \multicolumn{1}{r|}{9.7} & \multicolumn{1}{r|}{19.1} & 14.4 \\ \cline{3-7} \multicolumn{1}{l|}{} & \multicolumn{1}{l|}{} & \multicolumn{1}{l|}{yes} & \multicolumn{1}{l|}{4-gram} & \multicolumn{1}{r|}{9.6} & \multicolumn{1}{r|}{18.3} & 13.9 \\ \cline{4-7} \multicolumn{1}{l|}{} & \multicolumn{1}{l|}{} & \multicolumn{1}{l|}{} & \multicolumn{1}{l|}{LSTM} & \multicolumn{1}{r|}{7.7} & \multicolumn{1}{r|}{15.3} & 11.7 \\ \cline{2-7} \multicolumn{1}{l|}{} & \multicolumn{1}{l|}{yes} & \multicolumn{1}{l|}{no} & \multicolumn{1}{l|}{4-gram} & \multicolumn{1}{r|}{8.9} & \multicolumn{1}{r|}{17.7} & 13.3 \\ \cline{3-7} \multicolumn{1}{l|}{} & \multicolumn{1}{l|}{} & \multicolumn{1}{l|}{yes} & \multicolumn{1}{l|}{4-gram} & \multicolumn{1}{r|}{8.3} & \multicolumn{1}{r|}{16.7} & 12.5 \\ \cline{4-7} \multicolumn{1}{l|}{} & \multicolumn{1}{l|}{} & \multicolumn{1}{l|}{} & \multicolumn{1}{l|}{LSTM} & \multicolumn{1}{r|}{6.7} & \multicolumn{1}{r|}{14.7} & 10.7 \\ \cline{1-4} \cline{4-7} \multicolumn{1}{l|}{yes} & \multicolumn{1}{l|}{yes} & \multicolumn{1}{l|}{yes} & \multicolumn{1}{l|}{4-gram} & \multicolumn{1}{r|}{8.1} & \multicolumn{1}{r|}{15.4} & 11.8 \\ \cline{4-7} \multicolumn{1}{l|}{} & \multicolumn{1}{l|}{} & \multicolumn{1}{l|}{} & \multicolumn{1}{l|}{LSTM} & \multicolumn{1}{r|}{6.7} & \multicolumn{1}{r|}{13.5} & 10.2 \\ \hline & & & & \multicolumn{1}{l}{} & \multicolumn{1}{l}{} & \multicolumn{1}{l}{} \end{tabular} \end{table} \section{Conclusion} Using a combination of i-vectors and environment dependent unsupverised second pass training of affine transformatons, we were able to show that the cumulative application of these adaptation methods gives significantly larger improvements than any method on its own. The choice of features and normalization for i-vector estimation was shown to have a large influence on their adaptation performance. Also, we have shown, that environment adaptation and speaker adaptation perform best at different locations within the network. Our best single system achieves a word error rate of $10.2\%$ on the Hub5'00 evaluation corpus when trained only on 283 hours of training data. To our knowledge this is state of the art for a recognition system not based on system combination. \section{Acknowledgements} This work has received funding from the European Research Council (ERC) under the European Union's Horizon 2020 research and innovation programme (grant agreement No 694537, project "SEQCLAS" and Marie Sk\l{}odowska-Curie grant agreement No 644283, project "LISTEN") and from a Google Focused Award. The work reflects only the authors' views and none of the funding parties is responsible for any use that may be made of the information it contains. \bibliographystyle{IEEEtran}
{'timestamp': '2019-06-17T02:14:24', 'yymm': '1906', 'arxiv_id': '1906.06207', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06207'}
arxiv
\section{Introduction} Conditional neural language models, which train a neural net to map from one sequence to another, have had enormous success in natural language processing tasks such as machine translation \cite{sutskever2014sequence,Luong2015EffectiveAT}, text summarization \cite{Nallapati2016AbstractiveTS}, and dialog systems \cite{Vinyals2015ANC}. These models output a probability distribution over the next token in the output sequence given the input and the previously predicted tokens. Since computing the overall most likely output sequence is intractable, early work in neural machine translation found that beam search is an effective strategy to heuristically sample sufficiently likely sequences from these probabilistic models \cite{sutskever2014sequence}. However, for more open-ended tasks, beam search is ill-suited to generating a set of diverse candidate sequences; this is because candidates outputted from a large-scale beam search often only differ by punctuation and minor morphological variations \cite{li2016mutual}. The term ``diversity" has been defined in a variety of ways in the literature, with some using it as a synonym for sentence interestingness or unlikeliness \citep{tatsunori2019unifying}, and others considering it a measure of how different two or more sentences are from each other \citep{vijayakumar2016diverse,gimpel2013systematic}. We take the latter approach, and define diversity as the ability of a generative method to create a set of possible outputs that are each valid given the input, but vary as widely as possible in terms of word choice, topic, and meaning. \begin{figure} \scriptsize \begin{subfigure}[l]{3.3cm} \includegraphics[width=3.3cm]{COCO_val2014_000000155401.jpg} \end{subfigure} \begin{subfigure}[l]{3cm} \begin{tabular}{l} \textbf{Beam Search} \\ A bus is stopped at a bus stop. \\ A bus is parked at a bus stop. \\ A bus stopped at a bus stop in a city. \\ A bus stopped at a bus stop at a bus stop. \\ A bus that is parked in front of a building. \\ \hline \textbf{Random Sampling} \\ A bus parked at a bus stop at a bus stop. \\ There is a bus that is at the station. \\ A man standing by a bus in a city. \\ A bus pulling away from the train station. \\ A bus stopped at a stop on the sunny day. \\ \end{tabular} \end{subfigure} \caption{An image with the top five captions from standard beam search and from random sampling. Note the latter set is more diverse but lower quality.} \label{first_example} \end{figure} There are a number of reasons why it is desirable to produce a set of diverse candidate outputs for a given input. For example, in collaborative story generation, the system makes suggestions to a user for what they should write next \cite{clark2018creative}. In these settings, it would be beneficial to show the user multiple different ways to continue their story. In image captioning, any one sentence-long caption is probably missing some information about the image. \citet{krause2017hierarchical} show how a set of diverse sentence-length image captions can be transformed into an entire paragraph about the image. Lastly, in applications that involve reranking candidate sequences, the reranking algorithms are more effective when the input sequences are diverse. Reranking diverse candidates has been shown to improve results in both open dialog and machine translation \cite{li2016diversity,li2016mutual,gimpel2013systematic}. Furthermore, in open-ended dialog, the use of reranking to personalize a model's responses for each user is a promising research direction \cite{Choudhary2017DomainAN}. With these sorts of applications in mind, a variety of alternatives and extensions to beam search have been proposed which seek to produce a set of diverse candidate responses instead of a single high likelihood one \cite{li2016diversity,vijayakumar2016diverse,kulikov2018importance,tam2019clustered}. Many of these approaches show marked improvement in diversity over standard beam search across a variety of generative tasks. However, there has been little attempt to compare and evaluate these strategies against each other on any single task. In this paper, we survey existing methods for promoting diversity in order to systematically investigate the relationship between diversity and perceived quality of output sequences of conditional language models. In addition to standard beam search and greedy random sampling, we compare several recently proposed modifications to both methods. In addition, we propose the use of over-sampling followed by post-decoding clustering to remove similar sequences. The main contributions of this paper can be summarized as follows: \begin{itemize} \item A detailed comparison of existing diverse decoding strategies on two tasks: open-ended dialog and image captioning, and recommendations for a diverse decoding strategy. \item A novel clustering-based algorithm that can be used on the results of any decoding strategy to increase quality and diversity.\footnote{Code can be found at \url{https://github.com/rekriz11/DeDiv}.} \end{itemize} \section{Standard Decoding Methods} Conditional language models, which have wide applications across machine translation, text simplification, conversational agents, and more, generally consist of an encoder, which transforms some input $\textbf{x}$ into a fixed-size latent representation, and a decoder which transforms these representations in order to output a conditional probability of each word in the target sequence given the previous words and the input. Let $z_t = f(y_{1},\ldots,y_{t-1}, \mathbf{x})$ represent the output of an encoder-decoder model given input $\mathbf{x}$ and the sequence of tokens predicted so far, $y_1,\ldots,y_{t-1}$, which for notational simplicity we write as $y_{<t}$. The output $z_t \in \mathds{R}^V$ (where $V$ is the cardinality of the enumerated vocabulary $\mathcal{V}$) The probability distribution over the next possible token being word $w_i \in \mathcal{V}$ is the softmax: \begin{align*} P(y_t = w_i | y_{<t}, \mathbf{x}) &= \frac{\exp(z_{t,i})}{\sum_{j=1}^{V}{\exp{(z_{t,j})}}}\quad \\ &\forall i \in \{1,\ldots,V\} \end{align*} Most decoding strategies strive to find the most likely overall sequence, i.e. pick a $\mathbf{\hat{y}}$ such that: \[\Scale[0.85]{ \mathbf{\hat{y}} = \arg\max_{\mathbf{y}}{ P(\mathbf{y} | \mathbf{x})} = \arg\max_{\mathbf{y}}{\prod_{t=1}^{N} {P(y_t \mid y_{<t}, \mathbf{x})}} }\] Unlike Markovian processes, no sub-exponential algorithm exists to find the optimal decoded sequence, and thus we instead use approximations. \noindent\textbf{Arg-max}\quad The simplest approach to decoding a likely sequence is to greedily select a word at each timestep: \begin{equation*} \hat{y}_t = \arg\max_{y_t}{ P(y_t | y_{<t}, \mathbf{x})} \end{equation*} However, because this deterministic approach typically yields repetitive and short output sequences, and does not permit generating multiple samples, it is rarely used in language modelling. \noindent\textbf{Random Sampling}\quad Another option is to randomly sample from the model's distribution at every timestep. Often, a temperature parameter $T$ is added to control the entropy of the distribution before sampling. \begin{align*} P(y_t = w_i | y_{<t}, \mathbf{x}) &= \frac{\exp(z_{t,i}/T)}{\sum_{j=1}^{V}{\exp{(z_{t,j}/T)}}} \quad \\ \forall i \in \{1,\ldots,V\}\\ \hat{y}_t &\sim y_t \end{align*} Choosing a temperature greater than one causes outputs to look increasingly more random, while bringing the temperature less than zero causes sequences to increasingly resemble greedy sampling. Recently, top-$s$ random sampling has been proposed as an alternative to using temperature. Sampling is restricted to the $s$ most likely tokens at each step \cite{fan2018hierarchical,radford2019language}. We find that top-$s$ random sampling's hard-restriction on generating low probability words is more effective at controlling the stochasticity of sampled sequences than sampling with temperature. \begin{table*} \centering \small \begin{tabular}{|L{2.6cm} | L{4.5cm} || L{2.7cm} | L{4.3cm} |} \hline Method & Description & Method & Description \\ \hline Random Sampling & Standard decoding mechanism, greedily samples a token from the distribution at each time step. & Random Sampling with Temperature & Before sampling, modify entropy of predicted distribution. \\ \hline \makecell[l]{Top-$s$ Random\\Sampling\\\citep{fan2018hierarchical}}& Restrict sampling to the $s$-most likely words in the distribution. (story generation) & Beam Search & \makecell[l]{Standard decoding mechanism,\\keeps the top $b$ partial hypotheses\\at every time step.\\(machine translation)}\\ \hline NPAD Beam Search \citep{cho2016noisy}& Add random noise to the hidden state of the decoder at each time step. (machine translation) & \makecell[l]{Top-$g$ Capping\\Beam Search\\ \citep{li2016mutual}}& Only consider the top $c$ hypotheses from each parent hypothesis at each time step. (machine translation, dialog)\\ \hline Hamming Diversity Beam Search \citep{vijayakumar2016diverse}& \makecell[l]{Penalize new hypotheses that have\\many of the same tokens as\\existing partial hypotheses.\\(image captioning)} & \makecell[l]{Iterative Beam Search\\ \citep{kulikov2018importance}}& Run beam search several times, preventing later iterations from generating intermediate states already explored. (dialog)\\ \hline \makecell[l]{Clustered Beam\\Search\\\citep{tam2019clustered}}& Initially consider more hypotheses at each time step, and then cluster similar hypotheses together. (dialog) & Post-Decoding Clustering (Ours) & Sample a large number of candidates, and then cluster similar outputs together. \\ \hline \end{tabular} \caption{ Brief high-level descriptions of each decoding method we consider in this paper. In parentheses we give the applications on which the technique was originally applied. } \label{tab:methods} \end{table*} \noindent\textbf{Beam Search}\quad Beam search approximates finding the most likely sequence by performing breadth-first search over a restricted search space. At every step of decoding, the method keeps track of $b$ partial hypotheses. The next set of partial hypotheses are chosen by expanding every path from the existing set of $b$ hypotheses, and then choosing the $b$ with the highest scores. Most commonly, the log-likelihood of the partial sequence is used as the scoring function. We use this as our baseline.\footnote{We present the beam search algorithm in the appendix.} Since beam search only explores a limited portion of the overall search space, it tends to yield multiple variants of the same high-likelihood sequence, sequences that often only differ in punctuation and minor morphological changes \cite{li2016mutual}. Therefore, standard beam search is not ideal for producing diverse outputs. \section{Extensions to Beam Search} In this section, we will discuss a variety of methods that have been developed recently to eliminate redundancy during decoding and generate a wider range of candidate outputs. \noindent\textbf{Noisy Parallel Approximate Decoding}\quad Introduced by \citet{cho2016noisy}, NPAD is a technique than can be applied to any decoding setting. The main idea is that diversity can be achieved more naturally by taking advantage of the continuous manifold on which neural nets embed language. Instead of encouraging diversity by manipulating the probabilities outputted from the model, diverse outputs are instead produced by adding small amounts of noise to the hidden state of the decoder at each step. The noise is randomly sampled from a normal distribution. The variance is gradually annealed from a starting $\sigma_0$ to 0 as decoding progresses (that is $\sigma_t = \frac{\sigma_0}{t}$) under the reasoning that uncertainty is greatest at the beginning of decoding. NPAD can be used in conjunction with any decoding strategy; following the best results from the original paper, we show results using NPAD with beam search. Extensions to NPAD have sought to learn the direction in which to manipulate the hidden states using an arbitrary decoding objective \cite{gu2017trainable}. Since such objectives can be highly domain-specific, we do not evaluate this method. \noindent\textbf{Top-$g$ Capping}\quad In beam search, it is often the case that one hypothesis $h$ is assigned a much higher probability than all other hypotheses, causing all hypotheses in the next step to have $h$ as their parent. Following \newcite{li2016mutual} and \newcite{li2016simple}, we add an additional constraint to standard beam search to encourage the model to choose options from diverse candidates. At each step $t$, current hypotheses are grouped according to the parental hypothesis they come from. After grouping candidates, only the top $g$ from each grouping are considered. The resulting $b \times g$ candidates are ranked, and the top $b$ are selected as hypotheses for the next beam step. \noindent\textbf{Hamming Diversity Reward}\quad \newcite{vijayakumar2016diverse} proposes adding an additional diversity-promoting term, $\theta$, to the log-likelihood before reranking. This term measures how different a candidate hypothesis $c^{(i)}_{\leq t}$ is from the partial hypotheses selected in the previous step. Let $\mathcal{H}_{t-1} = \{c^{(1)}_{\leq t-1}$, \ldots $c^{(b)}_{\leq t-1}\}$ be these partial hypotheses. Then the beam search scoring function for the $i$th candidate at timestep $t$ becomes: \begin{align*} \text{score}(c^{(i)}_{\leq t}) = \sum_{j=1}^t \big(\log P(c^{(i)}_j | c^{(i)}_{<j}, \textbf{x})\big) \\+ \lambda\theta(c^{(i)}_{\leq t}, \mathcal{H}_{t-1}) \end{align*} where $\lambda$ is a tunable hyperparameter. \citet{vijayakumar2016diverse} try a variety of definitions for $\theta$, including embedding diversity and $n$-gram diversity, but they find that Hamming distance, the number of tokens in the candidate sequence which exist in the previously selected partial hypotheses, is most effective. We take the negative of the Hamming distance as $\theta$. \noindent\textbf{Iterative Beam Search}\quad In an attempt to improve the size of the search space explored without sacrificing runtime, \newcite{kulikov2018importance} propose an iterative beam search method. Beam search is run many times, where the states explored by subsequent beam searches are restricted based on the intermediate states explored by previous iterations. Formally, we can define the set of all partial hypotheses for beam search instance $i$ at time step $t$ as $\mathcal{H}_t^{(i)}$. From here, the search space explored by beam search instance $i$ can be expressed as $S_i = \cup_{t=1}^T \mathcal{H}_t^{(i)}$. The $i$th beam search is prevented from generating any partial hypothesis that has previously been generated, that is, any hypothesis found in $S_{<i} = \cup_{i^{\prime}=0}^{i-1}S_{i^{\prime}}$. The authors also attempt a soft inclusion criterion, where any states within $\epsilon$ Hamming distance from a previously explored state are also excluded. During the experimentation of \newcite{kulikov2018importance}, however, the soft-inclusion was found to not be beneficial; thus, we only restrict exact matches of previous states in our implementation. In practice, this means after the first beam search instance runs as normal, the first step of the second beam search instance will contain the $b$+1 to 2$b$-most likely starting tokens; this pattern holds for the third beam search instance, and so on. \noindent\textbf{Clustered Beam Search}\quad Most recently, \newcite{tam2019clustered} proposed a clustering-based beam search method to help condense and remove meaningless responses from chatbots. Specifically, at each decoding step $t$, this method initially considers the top $2*b$ candidates. From there, each candidate sequence is embedded\footnote{We follow \newcite{tam2019clustered} and used averaged GloVe word embeddings \cite{pennington2014glove}.}, and the embeddings are clustered into $c$ clusters using $K$-means. Finally, we take the top $\frac{b}{c}$ candidates from each cluster. Note that in the case any clusters have size less than $\frac{b}{c}$, we then include the highest-ranked candidates not found after clustering. \section{Clustering Post-Decoding (PDC)} \label{section:postcluster} In the previous section, we discuss several diversity-promoting methods that can be applied during the decoding process. However, it is also possible to encourage additional diversity post-hoc. On the task of sentence simplification, after decoding using a large-scale diversity-promoting beam search (beam size 100), \newcite{kriz2019complexity} then clustered similar sentences together to further increase the variety of simplifications from which to choose. Document embeddings generated via Paragraph Vector \cite{Le2014distributed} were used as the sentence embeddings with which to perform $K$-means. In this work, we extend this post-decoding clustering idea in three key ways. First, we make use of sentence-level embeddings which leverage the pre-trained language representations from the Bidirectional Encoder Representations from Transformers (BERT) \cite{devlin2018bert}.\footnote{BERT sentence-level embeddings were obtained using https://github.com/hanxiao/bert-as-service.} Second, after clustering, \newcite{kriz2019complexity} took the sentence closest to the centroid of each cluster as the representative candidate; we instead choose the highest-ranked candidate (according to log-likelihood) from each cluster to ensure the best candidates are still selected. Finally, after performing standard $K$-means clustering, we found that it was often the case that some clusters contained large numbers of good candidates, while others contained very few candidates that are also either ungrammatical or otherwise inferior. Thus, in our implementation, we remove clusters containing two or fewer sentences, and then sample a second candidate from each of the remaining clusters, prioritizing selecting candidates from larger clusters first. \section{Experimental Setup} We evaluate the decoding strategies described in the previous sections under the following settings. For each of the published beam search algorithms, we choose the hyperparameters that were found to be best in the original publications.\\ \small \begin{tabular}{l|l} \multirow{2}{*}{RS} & Random sampling with temp = 0.5,\\ & 0.7, 1.0, or 1.0 with top-10 capping.\\ Standard BS & Standard beam search\\ Top5Cap BS & Top-$g$ capping with $g=3$\\ Iter5 BS & Iterative beam search with 5 iterations\\ HamDiv0.8 BS & Hamming Diversity with $\lambda=0.8$\\ Cluster5 BS & Clustered beam search with 5 clusters\\ NPAD0.3 BS & Noisy Decoding with $\sigma_0=0.3$ \\ \end{tabular} \normalsize \\ For random sampling, we sample 10 outputs, and with beam-search based methods, we use a beam size of 10 to generate 10 outputs. In addition, we show results from oversampling then filtering. We use a beam size of 100 or generate 100 samples through random sampling, and then we select 10 from the 100, either through post-decoding clustering (PDC) or by taking the 10 candidates with highest likelihood. We examine these decoding strategies on two tasks: open ended dialog and image captioning. For each task, we evaluate both the quality and diversity of the 10 outputs from each strategy. \subsection{Open-ended Dialog Task} In the dialog domain, we use an LSTM-based sequence-to-sequence (Seq2Seq) model implemented in the OpenNMT framework \cite{opennmt}. We match the model architecture and training data of \citet{baheti2018generating}. The Seq2Seq model has four layers each in the encoder and decoder, with hidden size 1000, and was trained on a cleaned version of OpenSubtitles \cite{tiedemann2009news} to predict the next utterance given the previous one. Evaluation is performed on 100 prompts from the Cornell Movie Dialog Corpus~\cite{danescu2011chameleons}. These prompts are a subset of the 1000 prompts used in \citet{baheti2018generating}, which were filtered using item response theory for discriminative power. We report perplexity (PpL), averaged over \textit{all} the top 10 outputs for each example.\footnote{This differs from existing work which computes perplexity over only the top output for each example. For our task we are interested in the quality of all of the generated responses.} Since the quality of open-ended dialog is notoriously difficult to evaluate automatically, we ran a human evaluation task on Amazon Mechanical Turk where annotators were shown a prompt and 5 potential responses generated by any of our decoding methods. Evaluators were asked to provide binary ratings on fluency, adequacy, and interestingness for each response. Overall, we collected 3 human judgments for each of the top ten responses for each of our decoding methods; in other words, we collected 3,000 judgments per method.\footnote{The full instructions shown on AMT are in the appendix.} \begin{table*}[t] \centering \small \setlength\tabcolsep{4pt} \begin{tabular}{|lr||ccc||ccccc|} \hline \multicolumn{2}{|c||}{\textbf{Method}} & \textbf{Fluency} & \textbf{Adequacy} & \textbf{Interestingness} & \textbf{Ppl} & \textbf{Dist-1} & \textbf{Dist-2} & \textbf{Ent-2} & \textbf{Ent-4} \\ \hline\hline Reference & & 0.795 & 0.732 & 0.636 & -- & -- & -- & -- & -- \\ \hline\hline RS 0.7 &(sample 10) & \textbf{0.758} & 0.399 & \textbf{0.388} & 35.98 & 0.63 & 0.80 & 4.08 & 3.84 \\ RS 1.0 &(sample10) & 0.550 & 0.303 & \td{0.386} & 67.99 & \textbf{0.74} & \textbf{0.87} & \textbf{4.35} & \textbf{4.08} \\ RS 1.0,top10 &(sample 10) & \td{0.745} & \textbf{0.418} & \td{0.387} & \textbf{10.33} & 0.60 & 0.80 & 4.12 & 3.91 \\ \hline\hline Standard BS &(10 beams) & \textbf{0.950} & \textbf{0.621} & 0.336 & \textbf{4.01} & 0.37 & 0.45 & 3.16 & 3.01 \\ Top3Cap BS &(10 beams)& \td{0.942} & 0.603 & 0.346 & 4.03 & 0.37 & 0.46 & 3.17 & 3.03 \\ Iter5 BS &(10 beams)& 0.903 & 0.520 & 0.335 & 5.42 & \textbf{0.62} & \textbf{0.74} & \textbf{3.68} & \textbf{3.25} \\ HamDiv0.8 BS &(10 beams)& 0.923 & 0.599 & \td{0.366} & 4.56 & 0.33 & 0.37 & 3.08 & 3.00 \\ Cluster5 BS &(10 beams)& 0.936 & 0.582 & \textbf{0.381} & 4.23 & 0.39 & 0.46 & 3.24 & 3.06 \\ NPAD0.3 BS &(10 beams) & \td{0.942} & \td{0.604} & 0.335 & 4.05 & 0.36 & 0.44 & 3.13 & 2.99 \\ \hline\hline RS 1.0,top10 &(sample 100, rank) & \textbf{0.922} & \textbf{0.548} & 0.347 & \textbf{5.10} & 0.52 & 0.68 & 3.54 & 3.18 \\ RS 1.0,top10 &(sample 100, PDC) & 0.852 & 0.494 & \textbf{0.372} & 6.96 & \textbf{0.63} & \textbf{0.76} & \textbf{3.74} & \textbf{3.27} \\ \hline\hline Standard BS &(100 beams, rank) & \textbf{0.964} & \textbf{0.611} & \td{0.332} & \textbf{4.01} & 0.44 & 0.61 & 3.33 & 3.05 \\ Standard BS &(100 beams, PDC) & 0.944 & 0.599 & \textbf{0.346} & 4.42 & \textbf{0.57} & \textbf{0.70} & \textbf{3.59} & \textbf{3.21} \\ \hline \end{tabular} \caption{ Results on 100 dialog prompts. The first row shows the mean human ratings of the single reference response available for each prompt. The next three rows show results for random sampling, with 10 samples drawn per prompt. The next six rows are variants of beam search using beam size 10. The last four rows use random sampling or standard beam search to generate 100 outputs, then filter down to 10 outputs either through ranking by log-likelihood or by performing post-decoding clustering (PDC). In each section, the highest value is bolded, and statistical ties are marked \textdagger.} \label{tab:results_no_cluster} \end{table*} \begin{table*} \small \centering \begin{tabular}{|lr||ccc||cccc|} \hline & & \multicolumn{3}{c||}{\textbf{SPICE}} & & & & \\ \multicolumn{2}{|c||}{\textbf{Method}} & \textbf{Mean} & \textbf{@1} & \textbf{@10} & \textbf{Dist-1} & \textbf{Dist-2} & \textbf{Ent-2} & \textbf{Ent-4} \\ \hline\hline RS 0.7 &(sample10) & \textbf{0.170} & \textbf{0.192} & \textbf{0.278} & 0.31 & 0.52 & 3.67 & 4.00 \\ RS 1.0 &(sample10) & 0.133 & 0.167 & 0.247 & \textbf{0.44} & \textbf{0.71} & \textbf{4.17} & \textbf{4.26} \\ RS 1.0,top10 &(sample10) & 0.159 & 0.183 & 0.272 & 0.33 & 0.59 & 3.90 & 4.17 \\ \hline \hline Standard BS &(10 beams) & 0.194 & 0.193 & 0.283 & 0.18 & 0.26 & 2.94 & 3.18 \\ Top3Cap BS &(10 beams) & \textbf{0.195} & \textbf{0.196} & 0.282 & 0.17 & 0.26 & 2.93 & 3.17 \\ HamDiv0.8 BS &(10 beams) & 0.194 & 0.194 & 0.282 & 0.18 & 0.27 & 2.98 & 3.19 \\ Cluster5 BS &(10 beams) & 0.191 & 0.194 & \textbf{0.285} & \textbf{0.19} & \textbf{0.28} & \textbf{3.04} & \textbf{3.25} \\ NPAD0.3 BS &(10 beams) & 0.191 & 0.192 & 0.280 & 0.18 & 0.26 & 2.94 & 3.17 \\ \hline \hline RS 1.0,top10 &(sample100, rank) & \textbf{0.182} & \textbf{0.188} & \textbf{0.284} & 0.25 & 0.41 & 3.31 & 3.64 \\ RS 1.0,top10 &(sample100, PDC) & 0.169 & \textbf{0.188} & 0.282 & \textbf{0.31} & \textbf{0.52} & \textbf{3.62} & \textbf{3.91} \\ \hline \hline Standard BS &(100 beams, rank) & \textbf{0.188} & 0.190 & 0.279 & 0.20 & 0.31 & 3.04 & 3.32 \\ Standard BS &(100 beams, PDC) & 0.186 & \textbf{0.192} & \textbf{0.288} & \textbf{0.24} & \textbf{0.38} & \textbf{3.25} & \textbf{3.57} \\ \hline \end{tabular} \caption{Image captioning results for selected random sampling and beam search methods. SPICE@1 measures the SPICE score of the most likely caption. SPICE@10 is the maximum score across the 10 candidates generated by each method. Mean SPICE is the mean score over all 10 candidates. In each section, the best value is bolded.} \label{tab:image_captioning} \end{table*} \subsection{Image Captioning Task} For image captioning, we use a state-of-the-art model introduced in \citet{anderson2018bottom}. We take advantage of \citet{Luo2017}'s open-source implementation and released model parameters trained on MSCOCO \cite{lin2014microsoft}. We evaluate on a test set containing 5000 images. We report Semantic Propositional Image Caption Evaluation (SPICE) scores, an automatic evaluation metric that has been shown to correlate well with human judgments of quality\citep{Anderson2016SPICE}. SPICE measures how well the semantic scene graph induced by the proposed caption matches one induced by the ground truth. In addition to computing SPICE on the top-scoring caption (SPICE@1), we follow \citet{vijayakumar2016diverse} in reporting Oracle SPICE@10 scores. This is done to show the upper bound on the potential impact diversity can have. We also compute the mean SPICE score across all of the candidate captions for an image. Unlike SPICE@1 and SPICE@10, this metric shows the overall quality of \textit{all} of the candidate captions, which is useful to know for applications that combine diverse candidate output sequences \cite{krause2017hierarchical}. \subsection{Evaluating Diversity} To measure the diversity across the generated candidate sequences for a given input, we report \textbf{Dist-k}, the total number of distinct k-grams divided by the total number of produced tokens in all of the candidate responses for a prompt \citep{li2016diversity}. We report Dist-2 and Dist-4 averaged over the prompts in the test set. A limitation of Dist-$k$ is that all $k$-grams that appear at least once are weighted the same, ignoring the fact that infrequent $k$-grams contribute more to diversity than frequent ones. \citet{zhang2018generating} instead propose an entropy metric, \textbf{Ent-k}, defined as: \begin{align*} \textit{Ent-k} = \frac{-1} {\sum_{w \in S}F(w)} \sum_{w \in S} F(w) \log \frac{F(w)} {\sum_{w' \in S} F(w')} \end{align*} where $S$ is the set of all $k$-grams that appear in candidate responses for an example, and $F(w)$ denotes the frequency of $w$ in the candidate responses. \section{Results} We report results on dialog systems and image captioning in Tables \ref{tab:results_no_cluster} and \ref{tab:image_captioning}, respectively. As expected, random sampling-based approaches yield outputs with greater diversity but worse quality than beam search-based approaches. Over-sampling then filtering increases the quality of outputs while still ensuring high diversity. In the following sections, we discuss the diversity-quality tradeoff, and then delve further into the results for each method group. \begin{figure*}[ht] \centering \begin{subfigure}[l]{5cm} \includegraphics[width=5cm]{dist2_vs_human.pdf} \end{subfigure} \begin{subfigure}[l]{5cm} \includegraphics[width=5cm]{ent4_vs_human.pdf} \end{subfigure} \begin{subfigure}[l]{5cm} \includegraphics[width=5cm]{perplexity_vs_human.pdf} \end{subfigure} \caption{Each decoding strategy is plotted, showing that human-perceived quality is negatively correlated with diversity. The Pearson Correlation coefficients between each statistic and the average of fluency, coherence, and interestingness are shown in parentheses.} \label{fig:correlations} \end{figure*} \begin{table*}[t] \centering \small \begin{tabular}{|l|l|l|} \hline \multicolumn{3}{|l|}{\rule{0pt}{0.35cm} \textbf{Prompt:} Look, nobody knows we did it.} \\ \hline \hline \textbf{RS 0.5} & \textbf{Standard BS} & \textbf{NPAD0.3 BS} \\ \hline \makecell[l]{ I don't know what you're talking about. \\ What's the matter with you? \\ I don't know what it is. \\ I don't think so. \\ He's got to get out of here. \\ }& \makecell[l]{ We've got to get out of here. \\ What do you mean? \\ I don't think it's a good idea. \\ I don't know what to say. \\ I don't know what's going on. \\ }& \makecell[l]{ I don't think it's a good idea. \\ I don't know what to say. \\ I don't know what's going on. \\ I don't know what to do. \\ I don't know what's going on here. \\ } \\ \hline \hline \textbf{RS 1.0} & \textbf{Standard BS with PDC} & \textbf{Cluster5 BS} \\ \hline \makecell[l]{ I can't find it. \\ They're our ships. \\ It's all right anyone is the right to interfere. \\ We didn't have a plan I engineered a policy. \\ Same time you pick us up at six and get we. \\ }& \makecell[l]{ I don't know! \\ I don't think so. \\ What do you mean? \\ Why didn't you tell me? \\ That's why we're here. \\ }& \makecell[l]{ I don't know why. \\ What do you mean? \\ I don't think so. \\ How do you know that? \\ I'll tell you what. \\ } \\ \hline \hline \textbf{RS 1.0,top10} & \textbf{RS 1.0,top10 with PDC} & \textbf{Top3Cap BS} \\ \hline \makecell[l]{ I don't know what else to do. \\ It doesn't have to be that way! \\ We're in the air! \\ I've seen a guy in his place in a it. \\ And I'm not we any more. \\ }& \makecell[l]{ What do you mean? \\ I don't think so. \\ That's why I'm here. \\ It's all right we. \\ We've been through this before. \\ }& \makecell[l]{ We've got to get out of here. \\ What do you mean? \\ I don't think it's a good idea. \\ I don't know what to say. \\ I don't know what's going on. \\ } \\ \hline \end{tabular} \caption{Responses to an example prompt for selected methods. More examples can be seen in the appendix.} \label{examples} \end{table*} \subsection{The Quality Diversity Tradeoff} The goal of diverse decoding strategies is to generate high-quality candidate sequences which span as much of the space of valid outputs as possible. However, we find there to be a marked trade-off between diversity and quality. This can be seen in Figure \ref{fig:correlations}, where we plot the human-judged quality score for each dialog experiment against our primary diversity descriptive statistics. Fluency and adequacy are both strongly negatively correlated with diversity. While we had expected interestingness to be positively correlated with diversity, the fact that it is not suggests that existing diversity statistics are insufficient for capturing what it means to humans for outcomes to be interesting. Likewise, in image captioning, the mean SPICE score of the 10 candidate captions (averaged over all examples for each experimental setting) is strongly anti-correlated with diversity, with a Pearson correlation coefficient of -0.83 with the Ent-4 measure and -0.84 with Dist-2. Clearly it remains an open challenge to generate a diverse set of image captions that are all high-quality. When researchers choose to use a diverse decoding strategy, they must decide where on the quality-diversity tradeoff they would like to lie; selecting an optimal method depends strongly on one's tolerance for errors. In machine translation, where mistakes could severely impact coherence, beam search-based methods, which tend to result in better fluency and coherence, but worse diversity might be preferred. In more open-ended applications, where novel text is of greater importance, increased diversity could be worth the fluency and coherency hit. As state-of-the-art models continue to improve, one would hope that the quality cost of encouraging diversity will continue to decrease. In the interest of reporting a single overall best method for each task, we computed a sum-of-ranks score for each method. For dialog, we ranked the methods each by fluency, coherence, interestingness, and Ent-4, and then took a weighted sum of the four ranks, with 50\% of the weight assigned to Ent-4, and 50\% distributed evenly among the human evaluation ranks. Overall, clustered beam search and standard BS (beam size 100, PDC) have the best scores, followed by clustered beam search (beam size 10). Similarly, for image captioning, we rank the methods by their mean SPICE score and by Ent-4. Summing these ranks, random sampling (temp 1.0, top-10 capping, PDC) came in first. Standard beam search, Hamming Diversity beam search, and Top-$g$ capping beam search (beam size 10) tied for second. \subsection{Random Sampling-based Methods} Higher sampling temperatures result in both an increase in diversity in generated responses and a reduction in overall quality. In the dialog domain, evaluators consistently rate the responses sampled with temperature 1.0 to have worse fluency, coherence, and interestingness when those sampled with temperature 0.5. In the image captioning domain, lower temperature improves automatic evaluation metrics for quality while reducing diversity. For dialog, restricting sampling to the top-10 vocabulary words is a more effective strategy than adjusting temperature for ensuring balance between the quality and diversity of outputs. Top-10 random sampling has the highest fluency, coherence, and interestingness, as well as significantly lower perplexity than other random sampling methods. However, this trend did not extend to image captioning, where top-10 random sampling results in both worse SPICE scores and lower diversity measures than setting the temperature to 0.7. This may be because image captioning is a less ambiguous task than open-ended dialog, leading to a better-trained model that puts more probability mass on high-quality vocabulary words, ameliorating the challenge top-$c$ filtering is designed to eliminate: that of a long tail of low probability vocabulary words taking up a large amount of probability mass. \subsection{Beam Search-based Methods} For dialog, clustered beam search (Cluster5 BS) performs the best of all beam search methods in terms of human-judged interestingness. It ties for best with NPAD0.3BS on fluency and ties with Standard BS on coherence. Iterative beam search (Iter5 BS) achieves the greatest diversity, but at the expensive of quality. It has the lowest human-judged coherence among beam search methods; thus, we do not evaluate this method on image captioning. For image captioning, Cluster5 BS has the highest diversity among beam search methods, but this difference is quite small. Cluster5 BS also has the highest SPICE@10 score, indicating it is the best method for generating at least one high quality candidate. However, Top3Cap BS results in the highest mean SPICE score, suggesting it is best at ensuring all outputs are reasonable quality. \subsection{Effect of Over-sampling} In our experiments, we explore over-sampling 100 outputs, and then either using post-decoding clustering (PDC) or re-ranking by log-likelihood to filter these 100 down to 10 diverse outputs. In the dialog domain, this over-sampling approach is a definite win. When over-sampling with random sampling both methods of filtering substantially improve human judgements of fluency and adequacy compared to random sampling only 10 outputs. However, interestingness scores go down, and while the outputs are still more diverse than beam search-based methods, they are less diverse than random sampling without filtering. In the beam search methods that use a beam size of 100 then filter down to 10, human-judged quality is on par with beam size 10 results, but diversity is considerably higher. When comparing the two types of filtering, PDC results in higher interestingness and diversity statistics, while log-likelihood re-ranking improves fluency and adequacy. This again demonstrates the trade-off between quality and diversity.\footnote{In the appendix, we show results with every method where we generate 10 samples; generate 100 samples followed by selecting the 10 most likely outputs; and generate 100 samples followed by post-decoding clustering to select 10 outputs.} For image captioning, over-sampling with reranking does not consistently improve quality as it does in the dialog domain. Mean SPICE score is improved for random sampling but not for beam search. SPICE@1 becomes worse for both random sampling and decoding, while SPICE@10 improves for random sampling, and for beam search when PDC is applied. From these results, we can conclude that over-sampling then ranking does not have a sizeable effect, either negative or positive, on quality. Moreover, the diversity of the captions generated by random sampling actually decreases when oversampling. The diversity of beam search-generated captions does improve with over-sampling. While oversampling does generally improve outcomes on the diversity/quality tradeoff, it is more computationally expensive, particularly with beam search. Running PDC also requires generating sentence embeddings for every output, which adds additional computation time. \section{Additional Related Work} In this paper, we have compared a variety of post-training diversity-promoting algorithms. Here, we discuss other related works that instead promote diversity at train-time, as well as alternative quality evaluation methods. We also note that concurrent work has proposed nucleus sampling as an improvement to the sampling strategies discussed in this paper \cite{holtzman2019curious}. \textbf{Diversity Promotion During Training}\quad Several works have attempted to encourage diversity during training by replacing the standard log-likelihood loss with a diversity-promoting objective. \citet{li2016diversity} introduces an objective that maximizes mutual information between the source and target. \citet{zhang2018generating} uses an adversarial information maximization approach to encourage generated text to be simultaneously informative and diverse. \citet{xu2018diversity} also uses an adversarial loss; their loss function rewards fluent text and penalizes repetitive text. We do not evaluate on these methods as they tend to be task-specific and difficult to implement. All of the diversity strategies we evaluate share the trait that they are agnostic to model architecture and to the data type of the input, as long as the output of the model is a probability distribution over tokens in a sequence. \textbf{Automatic Quality Evaluation}\quad An important part of this work is how to accurately measure not only the effect these methods have on candidate diversity, but also on the overall quality of the candidates. In choosing to report human scores and perplexity for the dialog domain, and SPICE for image captioning, we omitted some quality measures used in other papers. For image captioning, BLEU \citep{Papineni2001Bleu}, ROUGE \citep{lin2004rouge}, METEOR \citep{elliott2013image}, and CIDer \citep{Vedantam2015Cider} scores are often reported, but SPICE has been shown to have higher correlation with human judgments \cite{Anderson2016SPICE}. In the dialog domain, single-reference BLEU score \citep{Papineni2001Bleu} is sometimes used to measure response quality, but it has been shown to have little correlation with human-judged quality \citep{liu2016not}. Therefore, most works in dialog systems use human evaluation as the ultimate measure of quality \citep{li2016diversity,sedoc2018chateval} \section{Conclusion} In this work, we perform an analysis of post-training decoding strategies that attempt to promote diversity in conditional language models. We show how over-sampling outputs then filtering down to the desired number is an easy way to increase diversity. Due to the computational expense of running large beam searches, we recommend using random-sampling to over-sample. The relative effectiveness of the various decoding strategies differs for the two tasks we considered, which suggests that choice of optimal diverse decoding strategy is both task-specific and dependent on one's tolerance for lower quality outputs. While we have focused on evaluating each decoding strategy under the specifics reported to be the best in the original, further work is necessary to conclude whether observed differences in quality and diversity may simply be due to each work's chosen hyperparameters. The ability to effectively generate a diverse set of responses while not degrading quality is extremely important in a variety of generation tasks, and is a crucial component to harnessing the power of state-of-the-art generative models. \section{Acknowledgements} We thank our anonymous reviewers for helpful feedback. We also thank Yun William Yu for assistance with statistical testing and proofreading. This material is based in part on research sponsored by DARPA under grant number HR0011-15-C-0115 (LORELEI). The U.S. Government is authorized to reproduce and distribute reprints for Governmental purposes. The views and conclusions in this publication are those of the authors and should not be seen as representing official endorsements of DARPA and the U.S. Government.
{'timestamp': '2019-06-18T02:01:30', 'yymm': '1906', 'arxiv_id': '1906.06362', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06362'}
arxiv
\section{#1}} \newcommand{\Subsection}[1]{\subsection{#1}} \newcommand{\Subsubsection}[1]{\subsubsection{#1}~~~~~~} \newcommand{\SUBsubsection}[1]{\vspace*{\medskipamount} \noindent $\bullet$ {\em #1}~~~~~~ \newcommand{\Subsubsubsection}[1]{\vspace*{\medskipamount} \noindent $\bullet$ \textbf{#1}~~~~~~} \newcommand{\cg}[1]{#1 \newcommand{\cgr}[1]{#1 \newcommand{\cgred}[1]{#1 \usepackage[utf8]{inputenc} \begin{document} \setcounter{footnote}{2} \title{Self-Stabilizing Snapshot Objects\\ for Asynchronous Fail-Prone Network Systems~\footnote{This document was the Appendix of our accepted submissions to PODC 2019 and NETYS 2019.}\\~{(preliminary report)}} \author{Chryssis Georgiou~\footnote{Department of Computer Science, University of Cyprus, Nicosia, Cyprus. E-mail: \texttt{[email protected]}} \and Oskar Lundstr\"om~\footnote{Department of Engineering and Computer Science, Chalmers University of Technology, Gothenburg, SE-412 96, Sweden, E-mail: \texttt{[email protected]}.} \and Elad M.\ Schiller~\footnote{Department of Engineering and Computer Science, Chalmers University of Technology, Gothenburg, SE-412 96, Sweden, E-mail: \texttt{[email protected]}.}} \date{} \maketitle \begin{abstract} A \emph{snapshot object} simulates the behavior of an array of single-writer/multi-reader shared registers that can be read atomically. Delporte-Gallet \emph{et al.}\xspace proposed two fault-tolerant algorithms for snapshot objects in asynchronous crash-prone message-passing systems. Their first algorithm is \emph{non-blocking}; it allows snapshot operations to terminate once all write operations had ceased. It uses $\mathcal{O}(n)$ messages of $\mathcal{O}(n \cdot \nu)$ bits, where $n$ is the number of nodes and $\nu$ is the number of bits it takes to represent the object. Their second algorithm allows snapshot operations to \emph{always terminate} independently of write operations. It incurs $\mathcal{O}(n^2)$ messages. The fault model of Delporte-Gallet \emph{et al.}\xspace considers both node failures (crashes). We aim at the design of even more robust snapshot objects. We do so through the lenses of \emph{self-stabilization}---a very strong notion of fault-tolerance. In addition to Delporte-Gallet \emph{et al.}\xspace's fault model, a self-stabilizing algorithm can recover after the occurrence of \emph{transient faults}; these faults represent arbitrary violations of the assumptions according to which the system was designed to operate (as long as the code stays intact). In particular, in this work, we propose self-stabilizing variations of Delporte-Gallet \emph{et al.}\xspace's non-blocking algorithm and always-terminating algorithm. Our algorithms have similar communication costs to the ones by Delporte-Gallet \emph{et al.}\xspace and $\mathcal{O}(1)$ recovery time (in terms of asynchronous cycles) from transient faults. The main differences are that our proposal considers repeated gossiping of $\mathcal{O}(\nu)$ bits messages and deals with bounded space (which is a prerequisite for self-stabilization). Lastly, we explain how to extend the proposed solutions to reconfigurable ones. \end{abstract} \thispagestyle{empty} \section{Introduction} \label{sec:intro} We propose self-stabilizing implementations of shared memory snapshot objects for asynchronous networked systems whose nodes may fail-stop. \smallskip \noindent \textbf{Context and Motivation.~~} Shared registers are fundamental objects that facilitate synchronization in distributed systems. In the context of networked systems, they provide a higher abstraction level than simple end-to-end communication, which provides persistent and consistent distributed storage that can simplify the design and analysis of dependable distributed systems. Snapshot objects extend shared registers. They provide a way to further make the design and analysis of algorithms that base their implementation on shared registers easier. Snapshot objects allow an algorithm to construct consistent global states of the shared storage in a way that does not disrupt the system computation. Their efficient and fault-tolerant implementation is a fundamental problem, as there are many examples of algorithms that are built on top of snapshot objects; see textbooks such as~\cite{DBLP:series/synthesis/2011Welch,DBLP:series/synthesis/2018Taubenfeld}, as well as recent reviews, such as~\cite{DBLP:reference/algo/Ruppert16}. \smallskip \noindent \textbf{Task description.~~} Consider a fault-tolerant distributed system of $n$ asynchronous nodes that are prone to failures. Their interaction is based on the emulation of Single-Writer/Multi-Reader (SWMR) shared registers over a message-passing communication system. Snapshot objects can read the entire array of system registers~\cite{DBLP:journals/jacm/AfekADGMS93,DBLP:journals/dc/Anderson94}. The system lets each node update its own register via $\mathsf{write}()$ operations and retrieve the value of all shared registers via $\mathsf{snapshot}()$ operations. Note that these snapshot operations may occur concurrently with the write operations that individual nodes perform. We are particularly interested in the study of atomic snapshot objects that are \emph{linearizable}~\cite{DBLP:journals/toplas/HerlihyW90}: the operations $\mathsf{write}()$ and $\mathsf{snapshot}()$ appear as if they have been executed instantaneously, one after the other (in other words, they appear to preserve real-time ordering). \smallskip \noindent \textbf{Fault Model.~~} We consider an asynchronous message-passing system that has no guarantees on the communication delay. Moreover, there is no notion of global (or universal) clocks and we do not assume that the algorithm can explicitly access the local clock (or timeout mechanisms). Our fault model includes $(i)$ fail-stop failures of nodes, and $(ii)$ communication failures, such as packet omission, duplication, and reordering. In addition, to the failures captured in our model, we also aim to recover from \emph{transient faults}, \emph{i.e.,}\xspace any temporary violation of assumptions according to which the system and network were designed to behave, \emph{e.g.,}\xspace the corruption of control variables, such as the program counter and operation indices, which are responsible for the correct operation of the studied system, or operational assumptions, such as that at least half of the system nodes never fail. Since the occurrence of these failures can be combined, we assume that these transient faults can alter the system state in unpredictable ways. In particular, when modeling the system, we assume that these violations bring the system to an arbitrary state from which a \emph{self-stabilizing algorithm} should recover the system. Therefore, starting from an arbitrary state, the correctness proof of self-stabilizing systems~\cite{DBLP:journals/cacm/Dijkstra74} has to demonstrate the return to a ``correct behavior'' within a bounded period, which brings the system to a \emph{legitimate state}. The complexity measure of self-stabilizing systems is the length of the recovery period. As transient faults can occur at any point in a system's lifetime, self-stabilizing systems need to keep communicating its state structures for cleaning any potential corrupted (stale) information; to this respect, a self-stabilizing system cannot really terminate~\cite[Chapter 2.3]{DBLP:books/mit/Dolev2000}. Specifically, the proposed solution repeatedly broadcasts $\mathcal{O}(\nu)$-size gossip messages that facilitate the system clean-up from stale information, where $\nu$ is the number of bits it takes to represent the object. We note the trade-off between the cost related to these gossip messages and the recovery time. That is, one can balance this trade-off by, for example, reducing the rate of gossip messages, which prolongs the stabilization time. We clarify that the rate in which these repeated clean-up operations take place does not impact the execution time of the $\mathsf{write}()$ and $\mathsf{snapshot}()$ operations. \smallskip \noindent \textbf{Related work.~~} We follow the design criteria of self-stabilization, which was proposed by Dijkstra~\cite{DBLP:journals/cacm/Dijkstra74} and detailed in~\cite{DBLP:books/mit/Dolev2000}. We now overview existing work related to ours. Our review does not focus on algorithms for shared memory system; although there are examples for both non-self-stabilizing~\cite{DBLP:journals/ipl/KirousisST96,DBLP:journals/tpds/KirousisST94} and self-stabilizing~\cite{Abraham07selfstabilizing} solutions. \noindent \emph{Shared registers emulation in message-passing systems:~~} Attiya \emph{et al.}\xspace~\cite{DBLP:journals/jacm/AttiyaBD95} implemented SWMR atomic shared memory in an asynchronous networked system. They assume that the majority of the nodes do not crash or get disconnected. Their work builds on this assumption in the following manner: Any majority subset of the system nodes includes at least one non-failing node; thus, any two majority subsets of the system nodes have a non-empty intersection. They show that if a majority of the nodes acknowledge an update to the shared register, then that update can safely be considered visible to all non-failing nodes that retrieve the latest update from a majority of nodes. Attiya \emph{et al.}\xspace also show that this assumption is essential for solvability. Their seminal work has many generalizations and applications~\cite{DBLP:journals/eatcs/Attiya10}. The literature includes a large number of simulation of shared registers for networked systems, which differ in their fault tolerance properties, time complexity, storage costs, and system properties, \emph{e.g.,}\xspace~\cite{DBLP:journals/jal/Attiya00,DBLP:journals/siamcomp/DuttaGLV10,DBLP:conf/netys/HadjistasiNS17,DBLP:conf/podc/MostefaouiR16,DBLP:series/synthesis/2010Raynal2,DBLP:books/daglib/0032304}. In the context of self-stabilization, the literature includes a practically-self-stabilizing variation for the work of Attiya \emph{et al.}\xspace~\cite{DBLP:journals/jacm/AttiyaBD95} by Alon \emph{et al.}\xspace~\cite{DBLP:journals/jcss/AlonADDPT15}. Their proposal guarantees wait-free recovery from transient faults. However, there is no bound on the recovery time. Dolev \emph{et al.}\xspace~\cite{DBLP:journals/corr/abs-1806-03498} consider MWMR atomic storage that is wait-free in the absence of transient faults. They guarantee a bounded time recovery from transient faults in the presence of a fair scheduler. They demonstrate the algorithm's ability to recover from transient faults using unbounded counters and in the presence of fair scheduling. Then they deal with the event of integer overflow via a consensus-based procedure. Since integer variables can have $64$-bits, their algorithm seldom uses this non-wait-free procedure for dealing with integer overflows. In fact, they model integer overflow events as transient faults, which implies bounded recovery time from transient faults in the seldom presence of a fair scheduler (using bounded memory). They call these systems \emph{self-stabilizing systems in the presence of seldom fairness.} Our work adopts these design criteria. We also make use of their self-stabilizing quorum and gossip services~\cite[Section~13]{DBLP:journals/corr/abs-1806-03498}. \noindent \emph{Implementing a snapshot object on top of a message-passing system:~~} A straightforward way for implementing snapshot objects is to consider a layer of $n$ SWMR atomic registers emulated in a networked system. This way we can run on top of this layer any algorithm for implementing a snapshot object for a system with shared variables. Delporte-Gallet \emph{et al.}\xspace~\cite{DBLP:journals/tpds/Delporte-Gallet18} avoid this composition, obtaining, in this way, a more efficient implementation with respect to the communication costs. Specifically, they claim that when stacking the shared-memory atomic snapshot algorithm of~\cite{DBLP:journals/jacm/AfekADGMS93} on the shared-memory emulation of \cite{DBLP:journals/jacm/AttiyaBD95} (with some improvements), the number of messages per snapshot operation is $8n$ and it takes four round trips. Their proposal, instead, takes $2n$ message per snapshot operation and just one round trip to complete. The algorithms we propose in the present work follow the non-stacking approach of Delporte-Gallet and they have the same communication costs for write and snapshot operations. Moreover, they tolerate any failure (in any communication or operation invocation pattern) that~\cite{DBLP:journals/tpds/Delporte-Gallet18} can. Furthermore, our algorithms deal with transient faults by periodically removing stale information. To that end, the algorithms broadcast gossip message of $\mathcal{O}(1)$ bits, where $\nu$ is the number of bits it takes to represent the object. In the context of self-stabilization, there exist algorithms for the propagation of information with feedback, \emph{e.g.,}\xspace~\cite{DBLP:journals/jpdc/DelaetDNT10} that can facilitate the implementation of snapshot objects that can recover from transient faults, but not from node failures. For the sake of clarity, we note that ``stacking'' of self-stabilizing algorithms for asynchronous systems is not a straightforward process (since the existing ``stacking'' require schedule fairness, see~\cite[Section 2.7]{DBLP:books/mit/Dolev2000}). Moreover, we are unaware of an attempt in the literature to stack a self-stabilizing shared-memory atomic snapshot algorithm (such as the weak snapshots algorithm of Abraham~\cite{Abraham07selfstabilizing} that uses $\mathcal{O}(n)$ register size) over a self-stabilizing shared-memory emulation, such as the one of Dolev \emph{et al.}\xspace~\cite{DBLP:journals/siamcomp/DolevIM97}. \smallskip \noindent \textbf{Our Contributions.~~} We present an important module for dependable distributed systems: self-stabilizing algorithms for snapshot objects in networked systems. To the best of our knowledge, we are the first to provide a broad fault model that includes both node failures and transient faults. Specifically, we advance the state of the art as follows: \begin{enumerate} \item As a first contribution, we offer a self-stabilizing variation of the non-blocking algorithm presented by Delporte-Gallet \emph{et al.}\xspace~\cite{DBLP:journals/tpds/Delporte-Gallet18}. Their solution tolerates node failures as well as packet omission, duplication, and reordering. Each snapshot or write operation uses $\mathcal{O}(n)$ messages of $\mathcal{O}(\nu\cdot n)$ bits, where $n$ is the number of nodes and $\nu$ is the number of bits for encoding the object. The termination of a snapshot operation depends on the assumption that the invocation of all write operations cease eventually. Our solution broadens the set of failure types it can tolerate, since it can also recover after the occurrence of transient faults, which model any violation of the assumptions according to which the system was designed to operate (as long as the code stays intact). We increase the communication costs slightly by using $\mathcal{O}(n^2)$ gossip messages of $\mathcal{O}(\nu)$ bits, where $\nu$ is the number of bits it takes to represent the object. \item Our second contribution offers a self-stabilizing all-operation always-terminating variation of the snapshot-only always-terminating algorithm presented by Delporte-Gallet \emph{et al.}\xspace~\cite{DBLP:journals/tpds/Delporte-Gallet18}. Our algorithm can: (i) recover from of transient faults, and (ii) both write and snapshot operations always terminate (regardless of the invocation patterns of any operation). We achieve $(ii)$ by choosing to use \emph{safe registers} for storing the result of recent snapshot operations, rather than a \emph{reliable broadcast} mechanism, which often has higher communication costs. Moreover, instead of dealing with one snapshot task at a time, we take care of several at a time. We also consider an input parameter, $\delta$. For the case of $\delta=0$, our self-stabilizing algorithm guarantees an always-termination behavior in a way the resembles the non-self-stabilizing algorithm by Delporte-Gallet \emph{et al.}\xspace~\cite{DBLP:journals/tpds/Delporte-Gallet18} that blocks all write operation upon the invocation of any snapshot operation at the cost of $\mathcal{O}(n^2)$ messages. For the case of $\delta>0$, our solution aims at using $\mathcal{O}(n)$ messages per snapshot operation while monitoring the number of concurrent write operations. Once our algorithm notices that a snapshot operation runs concurrently with at least $\delta$ write operations, it blocks all write operations and uses $\mathcal{O}(n^2)$ messages for completing the snapshot operations. Thus, the proposed algorithm can trade communication costs with an $\mathcal{O}(\delta)$ bound on snapshot operation latency. Moreover, between any two consecutive periods in which snapshot operations block the system for write operations, the algorithm guarantees that at least $\delta$ write operations occur. \item The two proposed algorithms presented in sections~\ref{sec:aussnba} and~\ref{sec:aussata} consider unbounded counters. In Section~\ref{sec:bounded}, we explain how to bound these counters as well as how to extend our solutions to reconfigurable ones. \end{enumerate} \smallskip \noindent \textbf{Organization.} We state our system settings in Section~\ref{sec:sys}. We review the non-self-stabilizing solutions by Delporte-Gallet \emph{et al.}\xspace~\cite{DBLP:journals/tpds/Delporte-Gallet18} in Section~\ref{sec:back}. Our self-stabilizing non-blocking and always-terminating algorithms are proposed in Sections~\ref{sec:aussnba} and~\ref{sec:aussata}, respectively; they consider unbounded counters. We explain how to bound the counters of the proposed self-stabilizing algorithms in Section~\ref{sec:bounded}. We conclude in Section~\ref{sec:disc}. \section{System settings} \label{sec:sys} We consider an asynchronous message-passing system that has no guarantees on the communication delay. Moreover, there is no notion of global (or universal) clocks and we do not assume that the algorithm can explicitly access the local clock (or timeout mechanisms). The system consists of $n$ failure-prone nodes (or processors) with identifiers are unique and totally ordered in $\mathcal{P}$. \subsection{Communication model} \label{sec:commModel} The network topology is of a fully-connected graph, $K_{n}$, and any pair of nodes have access to a bidirectional communication channel that, at any time, has at most $\mathsf{capacity} \in \mathbb{N}$ packets. Every two nodes exchange (low-level messages called) \emph{packets} to permit delivery of (high-level) messages. When node $p_i \in \mathcal{P}$ sends a packet, $m$, to node $p_j \in \mathcal{P}\setminus \{p_i\}$, the operation ${send}$ inserts a copy of $m$ to $\mathit{channel}_{i,j}$, while respecting the upper bound $\mathsf{capacity}$ on the number of packets in the channel. In case $\mathit{channel}_{i,j}$ is full, \emph{i.e.,}\xspace $|\mathit{channel}_{i,j}|=\mathsf{capacity}$, the sending-side simply overwrites any message in $\mathit{channel}_{i,j}$. When $p_j$ receives $m$ from $p_i$, the system removes $m$ from $\mathit{channel}_{i,j}$. As long as $m \in \mathit{channel}_{i,j}$, we say that $m$'s message is in transit from $p_i$ to $p_j$. \subsection{Execution model} \label{sec:interModel} Our analysis considers the \emph{interleaving model}~\cite{DBLP:books/mit/Dolev2000}, in which the node's program is a sequence of \emph{(atomic) steps}. Each step starts with an internal computation and finishes with a single communication operation, \emph{i.e.,}\xspace message $send$ or $receive$. The {\em state}, $s_i$, of node $p_i \in \mathcal{P}$ includes all of $p_i$'s variables as well as the set of all incoming communication channels. Note that $p_i$'s step can change $s_i$ as well as remove a message from $channel_{j,i}$ (upon message arrival) or add a message in $channel_{i,j}$ (when a message is sent). The term {\em system state} refers to a tuple of the form $c = (s_1, s_2, \cdots, s_n)$ (system configuration), where each $s_i$ is $p_i$'s state (including messages in transit to $p_i$). We define an {\em execution (or run)} $R={c_0,a_0,c_1,a_1,\ldots}$ as an alternating sequence of system states $c_x$ and steps $a_x$, such that each system state $c_{x+1}$, except for the starting one, $c_0$, is obtained from the preceding system state $c_x$ by the execution of step $a_x$. Let $R'$ and $R''$ be a prefix, and respectively, a suffix of $R$, such that $R'$ is a finite sequence, which starts with a system state and ends with a step $a_x \in R'$, and $R''$ is an unbounded sequence, which starts in the system state that immediately follows step $a_x$ in $R$. In this case, we can use $\circ$ as the operator to denote that $R=R' \circ R''$ concatenates $R'$ with $R''$. \subsection{Fault model} We model a failure as a step that the environment takes rather than the algorithm. We consider failures that can and cannot cause the system to deviate from fulfilling its task (Figure~\ref{fig:self-stab-SDN}). The set of \emph{legal executions} ($LE$) refers to all the executions in which the requirements of the task $T$ hold. In this work, $T_{\text{snapshot}}$ denotes our studied task of snapshot object emulation and $LE_{\text{snapshot}}$ denotes the set of executions in which the system fulfills $T_{\text{snapshot}}$'s requirements. We say that a system state $c$ is {\em legitimate} when every execution $R$ that starts from $c$ is in $LE$. When a failure cannot cause the system execution (that starts in a legitimate state) to leave the set $LE$, we refer to that failure as a benign one. We refer to any temporary violation of the assumptions according to which the system was designed to operate (as long as program code remains intact) as transient faults. Self-stabilizing algorithms deals with benign failures (while fulfilling the task requirements) and they can also recover, within a bounded period, after the occurrence of transient faults. \begin{figure*}[t!] \begin{\VCalgSize} \centering \begin{tabular}{llll} \cline{2-3} \multicolumn{1}{l|}{} & \multicolumn{2}{l|}{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\textbf{Frequency}} \\ \hline \multicolumn{1}{|l|}{\textbf{Duration}} & \multicolumn{1}{l|}{\textit{Rare}} & \multicolumn{1}{l|}{\textit{Not rare}} \\ \hline \multicolumn{1}{|l|}{} & \multicolumn{1}{l|}{Any violation of the assumptions according} & \multicolumn{1}{l|}{Packet failures: omissions,} \\ \multicolumn{1}{|l|}{\textit{Transient}} & \multicolumn{1}{l|}{to which the system is assumed to} & \multicolumn{1}{l|}{duplications, reordering} \\ \multicolumn{1}{|l|}{\textit{}} & \multicolumn{1}{l|}{operate (as long as the code stays intact).} & \multicolumn{1}{l|}{(assuming communication} \\ \multicolumn{1}{|l|}{\textit{}} & \multicolumn{1}{l|}{This can result in any state corruption.} & \multicolumn{1}{l|}{fairness holds).} \\ \cline{2-3} \hline \multicolumn{1}{|l|}{\textit{Permanent}} & \multicolumn{1}{l|}{Fail-stop failures.} & \multicolumn{1}{l|}{} \\ \hline \vspace*{0.25em} \end{tabular} \includegraphics[clip=true,scale=0.7]{newSelf-stab-SDN.pdf}\\ \caption{\label{fig:self-stab-SDN}\footnotesize{The table above details our fault model and the chart illustrates when each fault set is relevant. The chart's gray shapes represent the system execution, and the white boxes specify the failures considered to be possible at different execution parts and recovery guarantees of the proposed self-stabilizing algorithm. The set of benign faults includes both packet failures and fail-stop failures.}} \end{\VCalgSize} \end{figure*} \subsubsection{Benign failures} \label{sec:benignFailures} The algorithmic solutions that we consider are oriented towards asynchronous message-passing systems and thus they are oblivious to the time in which the packets arrive and departure (and require no explicit access to clock-based mechanisms, which may or may not be used by the system underlying mechanisms, say, for congestion control at the end-to-end protocol). \paragraph{Communication fairness.~~} Recall that we assume that the communication channel handles packet failures, such as omission, duplication, reordering (Section~\ref{sec:commModel}). We consider standard terms for characterizing node failures~\cite{DBLP:series/synthesis/2011Georgiou}. A \emph{crash failure} considers the case in which a node stops taking steps forever and there is no way to detect this failure. A \emph{fail-stop failure} considers the case in which a node stops taking steps and there is a way to detect this failure, say, using unreliable failure detectors~\cite{DBLP:journals/jacm/ChandraT96}. We say that a failing node resumes when it returns to take steps without restarting its program --- the literature sometimes refer to this as an \emph{undetectable restart}. The case of a detectable restart allows the node to restart all of its variables. We assume that if $p_i$ sends a message infinitely often to $p_j$, node $p_j$ receives that message infinitely often. We refer to the latter as the \textit{fair communication} assumption. For example, the proposed algorithm sends infinitely often $\mathrm{GOSSIP}$ messages from any processor to any other. Despite the possible loss of messages, the communication fairness assumption implies that every processor receives infinitely often $\mathrm{GOSSIP}$ messages from any non-failing processor. Note that fair communication provides no bound on the channel communication delays. It merely says that a message is received within some finite time if its sender does not stop sending it (until that sender receives the acknowledgment for that message). We refer to the latter as the \textit{fair communication} assumption. We note that without the communication fairness assumption, the communication channel between any two correct nodes eventually becomes non-functional. \paragraph{Node failure.~~} We assume that the failure of node $p_i \in \mathcal{P}$ implies that it stops sending and receiving messages (and it also stops executing any other step) without any warning. We assume that the number of failing nodes is bounded by $f$ and that $2f<n$ for the sake of guaranteeing correctness~\cite{DBLP:books/mk/Lynch96}. In the absence of transient faults, failing nodes can simply crash (or fail-stop and then resume at some arbitrary time), as in Delporte-Gallet \emph{et al.}\xspace~\cite{DBLP:journals/tpds/Delporte-Gallet18}. In the presence of transient faults, we assume that failing nodes resume within some unknown finite time. The latter assumption is needed \emph{only} for recovering from transient faults; we bring more details in Section~\ref{sec:seldomFair}. In Section~\ref{sec:bounded} we discuss how to relax this assumption. \subsubsection{Transient faults} \cg{As already mentioned,} we consider arbitrary violations of the assumptions according to which the system and the communication network \cg{were designed} to operate. We refer to these violations and deviations as \emph{transient faults} and assume that they can corrupt the system state arbitrarily (while keeping the program code intact). The occurrence of a transient fault is rare. Thus, we assume that transient faults occur before the system execution \cg{starts~\cite{DBLP:books/mit/Dolev2000}.} Moreover, it leaves the system to start in an arbitrary state. \subsection{The snapshot object task} \label{sec:snapshotTask} The task of snapshot object emulation requires the fulfilment of two properties: termination and linearizability. The definition of these two terms is based on the term event, which we defined next before defining the term event histories that is needed for the definition of linearizability. \smallskip \noindent \emph{Events:~~} Let $\mathsf{op}$ be a $\mathsf{write}()$ or $\mathsf{snapshot}()$ operation. The execution of an operation $\mathsf{op}$ by a processor $p_i$ is modeled by two steps: the invocation step, denoted by $invoc(\mathsf{op})$, which calls the $\mathsf{op}$ operation, and a response event, denoted $resp(\mathsf{op})$ (termination), which occurs when $p_i$ terminates (completes) the operation. For the sake of simple presentation, by \emph{event} we refer to either an operation's start step or an operation's end step. \smallskip \noindent \emph{Effective operations:~~} We say that a $\mathsf{snapshot}()$ operation is \emph{effective} when the invoking processor does not fail during the operation's execution. We say that a $\mathsf{write}()$ operation is effective when the invoking processor does not fail during its execution, or in case it does fail, the operation's effect is returned by an effective snapshot operation. \smallskip \noindent \emph{Histories:~~} a history is a sequence of operation start and end steps that are totally ordered. We consider histories to compare in an abstract way between two executions of the studied algorithms. Given any two events $e$ and $f$, $e < f$ if $e$ occurs before $f$ in the corresponding history. A history is denoted by $\widehat{H}=(E,<)$, where $E$ is the set of events. Given an infinite history $\widehat{H}$, we require that: (i) its first event is an invocation and (ii) each invocation is followed by its matching response event. If $\widehat{H}$ is finite, then $\widehat{H}$ might not contain the matching response event of the last invocation event. \smallskip \noindent \emph{Linearizable snapshot history:~~} A snapshot-based history $\widehat{H}= (H,<)$ models a computation at the abstraction level at which the write and snapshot operations are invoked. It is linearizable if there is an equivalent sequential history $\widehat{H}_{seq}= (H,<_{seq})$ in which the sequence of effective $\mathsf{write}()$ and $\mathsf{snapshot}()$ operations issued by the processes is such that: \begin{enumerate} \item Each effective operation appears as executed at a single point of the timeline between its invocation event and its response event, and \item Each effective $\mathsf{snapshot}()$ operation returns an array $reg$ such that: (i) {$reg[i]=(v,\bullet)$} if the operation $\mathsf{write}(v)$ by $p_i$ appears previously in the sequence. (ii) Otherwise $reg[i]=\bot$. \end{enumerate} \subsection{Dijkstra's self-stabilization criterion} \label{sec:Dijkstra} An algorithm is \textit{self-stabilizing} with respect to the task of $LE$, when every (unbounded) execution $R$ of the algorithm reaches within a bounded period a suffix $R_{legal} \in LE$ that is legal. That is, Dijkstra~\cite{DBLP:journals/cacm/Dijkstra74} requires that $\forall R:\exists R': R=R' \circ R_{legal} \land R_{legal} \in LE$, where the length of $R'$ is the complexity measure, which we refer to as the \emph{recovery time} (other calls it the stabilization time). We say that a system \textit{execution is fair} when every step that is applicable infinitely often is executed infinitely often and fair communication is kept. Self-stabilizing algorithms often assume that $R$ is a fair execution. Wait-free algorithms guarantee that non-failing operations always become (within a finite number of steps) complete even in the presence of benign failures. Note that fair executions do not consider fail-stop failures (that were not detected by the system whom then excluded these failing nodes from reentering the system, as in~\cite{DBLP:conf/netys/DolevGMS17}). Therefore, we cannot demonstrate that an algorithm is wait-free by assuming that the system execution is always fair. \subsection{Self-stabilization in the presence of seldom fairness} \label{sec:seldomFair} As a variation of Dijkstra's self-stabilization criterion, Dolev \emph{et al.}\xspace~\cite{DBLP:journals/corr/abs-1806-03498} proposed design criteria in which (i) any execution $R=R_{recoveryPeriod}\circ R': R' \in LE$, which starts in an arbitrary system state and has a prefix ($R_{recoveryPeriod}$) that is fair, reaches a legitimate system state within a bounded prefix $R_{recoveryPeriod}$. (Note that the legal suffix $R'$ is not required to be fair.) Moreover, (ii) any execution $R=R'' \circ R_{globalReset}\circ R''' \circ R_{globalReset}\circ \ldots: R'',R''',\ldots \in LE$ in which the prefix of $R$ is legal, and not necessarily fair but includes at most $\mathcal{O}(n \cdot z_{\max} )$ write or snapshot operations, has a suffix, $R_{globalReset}\circ R''' \circ R_{globalReset}\circ \ldots$, such that $R_{globalReset}$ is required to be fair and bounded in length but might permit the violation of liveness requirements, \emph{i.e.,}\xspace a bounded number of operations might be aborted (as long as the safety requirement holds). Furthermore, $R'''$ is legal and not necessarily fair but includes at least $z_{\max}$ write or snapshot operations before the system reaches another $R_{globalReset}$. Since we can choose $z_{\max}\in \mathbb{Z}^+$ to be a very large value, say $2^{64}$, and the occurrence of transient faults is rare, we refer to the proposed criteria as one for self-stabilizing systems that their executions fairness is unrequited except for seldom periods. \subsection{Complexity Measures} \label{sec:timeComplexity} The main complexity measure of self-stabilizing systems is the time it takes the system to recover after the occurrence of a last transient fault. In detail, in the presence of seldom fairness this complexity measure considers the maximum of two values: (i) the maximum length of $R_{recoveryPeriod}$, which is the period during which the system recovers after the occurrence of transient failures, and (ii) the maximum length of $R_{globalReset}$. We consider systems that use bounded among of memory and thus as a secondary complexity measure we bound the memory that each node needs to have. However, the number of messages sent during an execution does not have immediate relevance in the context of self-stabilization, because self-stabilizing systems never stop sending messages~\cite[Chapter 3.3]{DBLP:books/mit/Dolev2000}. Next, we present the definitions, notations and assumptions related to the main complexity measure. \subsubsection{Message round-trips and iterations of self-stabilizing algorithms} \label{sec:messageRoundtrips} The correctness proof depends on the nodes' ability to exchange messages during the periods of recovery from transient faults. The proposed solution considers quorum-based communications that follow the pattern of request-replay as well as gossip messages for which the algorithm does not wait for any reply. The proof uses the notion of a message round-trip for the cases of request-reply messages as well as the term of algorithm iteration. We give a detailed definition of \emph{round-trips} as follows. Let $p_i \in P_C$ be a node and $p_j \in P \setminus \{p_i\}$ be a network node. Suppose that immediately after state $c$ node $p_i$ sends a message $m$ to $p_j$, for which $p_i$ awaits a reply. At state $c'$, that follows state $c$, node $p_j$ receives message $m$ and sends a reply message $r_m$ to $p_i$. Then, at state $c''$, that follows state $c'$, node $p_i$ receives $p_j$'s response, $r_m$. In this case, we say that $p_i$ has completed with $p_j$ a round-trip of message $m$. Self-stabilizing algorithms cannot terminate their execution and stop sending messages~\cite[Chapter 2.3]{DBLP:books/mit/Dolev2000}. Moreover, their code includes a do forever loop. Thus, we define a \emph{complete iteration} of a self-stabilizing algorithm. Let $N_i$ be the set of nodes with whom $p_i$ completes a message round trip infinitely often in execution $R$. Moreover, assume that node $p_i$ sends a gossip message infinitely often to $p_j \in \mathcal{P} \setminus \{p_i\}$ (regardless of the message payload). Suppose that immediately after the state $c_{begin}$, node $p_i$ takes a step that includes the execution of the first line of the do forever loop, and immediately after system state $c_{end}$, it holds that: (i) $p_i$ has completed the iteration it has started immediately after $c_{begin}$ (regardless of whether it enters branches), (ii) every request-reply message $m$ that $p_i$ has sent to any node $p_j \in P_i$ during the iteration (that has started immediately after $c_{begin}$) has completed its round trip, and (iii) it includes the arrival of at least one gossip message from $p_i$ to any non-failing $p_j \in \mathcal{P} \setminus \{p_i\}$. In this case, we say that $p_i$'s iteration (with round-trips) starts at $c_{begin}$ and ends at $c_{end}$. \subsubsection{Asynchronous cycles} \label{ss:asynchronousCycles} We measure the time between two system states in a fair execution by the number of (asynchronous) cycles between them. The definition of (asynchronous) cycles considers the term of complete iterations. The first (asynchronous) cycle (with round-trips) of a fair execution $R=R'' \circ R'''$ is the shortest prefix $R''$ of $R$, such that each non-failing node in the network executes at least one complete iteration in $R''$, where $\circ$ is the concatenation operator (Section~\ref{sec:interModel}). The second cycle in execution $R$ is the first cycle in execution $R'''$, and so on. \begin{remark} \label{ss:first asynchronous cycles} For the sake of simple presentation of the correctness proof, we assume that any message that arrives in $R$ without being transmitted in $R$ does so within $\mathcal{O}(1)$ asynchronous cycles in $R$. \end{remark} \subsection{External Building Blocks: Gossip and Quorum Services} \label{sec:spec} We utilize the $\mathsf{gossip}$ service from~\cite{DBLP:journals/corr/abs-1806-03498}, which guarantees the following: (a) every gossip message that the receiver delivers to its upper layer was indeed sent by the sender, and (b) such deliveries occur according to the communication fairness guarantees (Section~\ref{sec:benignFailures}). \emph{I.e.,}\xspace this gossip service does not guarantee reliability. We consider a system in which the nodes behave according to the following terms of service. We assume that at any time, any node runs only at most one operation (that is, either a $\mathsf{write}()$ or a $\mathsf{snapshot}()$; one at a time). These operations access the quorum sequentially, \emph{i.e.,}\xspace send one request at a time, by sending messages to all other nodes via a $\mathsf{broadcast}$ interface. The receivers of this message reply. For this request-reply behavior, the quorum-based communication functionality guarantees the following: (a) at least a quorum of nodes receive, deliver and acknowledge every message, (b) a (non-failing) sending node receives at least a majority of these replies or fulfil another return condition, \emph{e.g.,}\xspace arrival of a special message, and (c) immediately before returning from the quorum access, the sending-side of this service clears its state from information related to this quorum request. We use the above requirements in Corollary~\ref{thm:basicCorollary}; its correctness proof can be found in~\cite{DBLP:journals/corr/abs-1806-03498}. \begin{corollary}[Self-stabilizing gossip and quorum-based communications] % \label{thm:basicCorollary} % Let $R$ be an (unbounded) execution of the algorithm that appears in~\cite[Algorithm 3]{DBLP:journals/corr/abs-1806-03498} and satisfies the terms of service of the quorum-based communication functionality. Suppose that $R$ is fair and its starting system state is arbitrary. Within $\mathcal{O}(1)$ asynchronous cycles, $R$ reaches a suffix $R'$ in which % \textbf{\emph{(1)}} the gossip, and % \textbf{\emph{(2)}} the quorum-based communication functionalities are correct. % \textbf{\emph{(3)}} During $R'$, the gossip and quorum-based communication complete their operations correctly within $\mathcal{O}(1)$ asynchronous cycles. \end{corollary} \begin{algorithm*}[t!] \begin{\VCalgSize} \noindent \textbf{Definitions of $\preceq$:\label{ln:preceq}} For integers $t$ and $t'$: $(\bullet,t) \preceq (\bullet,t') \iff t \leq t'$; For arrays $tab$ and $tab'$ of $(\bullet, integer)$: $tab \preceq tab' \iff \forall p_k \in \mathcal{P} : tab[k] \preceq tab'[k]$; Also, $a \prec b \equiv a \preceq b \land a \neq b$\; \smallskip \noindent \textbf{local variables initialization (optional in the context of self-stabilization):\label{ln:varStart}} $ssn := 0; ts := 0$\tcc*{snapshout, resp., write operation indices} $reg := [\bot, \ldots ,\bot]$\tcc*{shared registers ($\bot$ is smaller than any possibly written value)\label{ln:var}} \smallskip \noindent \textbf{macro} $\mathrm{merge}(Rec)$ \label{ln:0merge} { \lFor{$p_k \in \mathcal{P}$}{$reg[k]\gets \max (\{reg[k]\} \cup \{r[k] \mid r \in Rec\})$\label{ln:0regGetsMaxRegCupMid}} } \smallskip \noindent \textbf{operation} $\mathsf{write}(v)$ \label{ln:0operationWriteV} \Begin{ $ts \gets ts+1; reg[i] \gets (v, ts)$; \textbf{let} $lReg:=reg$\label{ln:0tsPlusOne}\; \lRepeat{$\mathrm{WRITEack}(\mathnormal{regJ} \succeq lReg)$ received from a majority\label{ln:0waitUntilWRITEackReg}}{$\mathsf{broadcast~} \mathrm{WRITE}(lReg)$\label{ln:0broadcastWRITEreg};} $\mathrm{merge}(Rec)$ \textbf{where} $Rec$ is the set of $reg$ arrays received at line~\ref{ln:0waitUntilWRITEackReg}\label{ln:0mergeRecWrite}\; $\Return()$\label{ln:0writeReturn}\; } \noindent \textbf{operation} $\mathsf{snapshot}()$ \label{ln:0operationSnapshot} \Begin{ \Repeat{$prev = reg$}{ \textbf{let} $prev := reg$; $ssn \gets ssn + 1$\label{ln:0prevSsnGetsRegSsnPlusOne}\; \lRepeat{$\mathrm{SNAPSHOTack}(\bullet, \mathnormal{ssnJ} =ssn)$ received from a majority\label{ln:0waitUntilSNAPSHOTackReg}}{$\mathsf{broadcast} ~\mathrm{SNAPSHOT}(reg, ssn)$\label{ln:0ssnPlusOne};} $\mathrm{merge}(Rec)$ \textbf{where} $Rec$ is the set of $reg$ arrays received at line~\ref{ln:0waitUntilSNAPSHOTackReg}\label{ln:0mergeRecSnapshot}\; } $\Return(reg)$\label{ln:0snapshotReturn}\; } \smallskip \textbf{upon} message $\mathrm{WRITE}(\mathnormal{regJ})$ \textbf{arrival} \textbf{from} $p_j$ \label{ln:0arrivalWRITE} \Begin{ \lFor{$p_k \in \mathcal{P}$}{$reg[k] \gets \max_{\preceq}(reg[k], \mathnormal{regJ}[k])$\label{ln:0kDotRegGetsMaxPreceqRegJWrite}} \textbf{send} $\mathrm{WRITEack}(reg)$ \textbf{to} $p_j$\label{ln:0sendWRITEackReg}\; } \smallskip \textbf{upon} message $\mathrm{SNAPSHOT}(\mathnormal{regJ}, ssn)$ \textbf{arrival} \textbf{from} $p_j$ \label{ln:0arrivalSNAPSHOT} \Begin{ \lFor{$p_k \in \mathcal{P}$}{$reg[k] \gets \max_{\preceq}\{ reg[k], \mathnormal{regJ}[k] \}$\label{ln:0kDotRegGetsMaxPreceqRegJSnapshoot}} \textbf{send} $\mathrm{SNAPSHOTack}(reg, ssn)$ to $p_j$\label{ln:0sendSNAPSHOTackRegSsn}\; } \end{\VCalgSize} \caption{\label{alg:0disCongif}The non-self-stabilizing and non-blocking algorithm by Delporte-Gallet \emph{et al.}\xspace~\cite{DBLP:journals/tpds/Delporte-Gallet18} that emulates snapshot object; code for $p_i$} \end{algorithm*} \section{Background} \label{sec:back} For the sake of completeness, we review the solutions of Delporte-Gallet \emph{et al.}\xspace~\cite{DBLP:journals/tpds/Delporte-Gallet18}. \subsection{The non-blocking algorithm by Delporte-Gallet \emph{et al.}\xspace} \label{sec:nonBlock} The non-blocking solution to snapshot object emulation by Delporte-Gallet \emph{et al.}\xspace~\cite[Algorithm~1]{DBLP:journals/tpds/Delporte-Gallet18} allows all write operations to terminate regardless of the invocation patterns of the other write or snapshot operations (as long as the invoking processors do not fail during the operation). However, for the case of snapshot operations, termination is guaranteed only if eventually the system execution reaches a period in which there are no concurrent write operations. Algorithm~\ref{alg:0disCongif} presents Delporte-Gallet \emph{et al.}\xspace~\cite[Algorithm~1]{DBLP:journals/tpds/Delporte-Gallet18}. That is, we have changed some of the notation of Delporte-Gallet to fit the presentation style of this paper. Moreover, we use the $\mathsf{broadcast}$ primitive according to its definition in Section~\ref{sec:spec}. \smallskip \noindent \emph{Local variables.~~} The node state appears in lines~\ref{ln:varStart} to~\ref{ln:var} and automatic variables (which are allocated and deallocated automatically when program flow enters and leaves the variable's scope) are defined using the let keyword, \emph{e.g.,}\xspace the variable $prev$ (line~\ref{ln:0prevSsnGetsRegSsnPlusOne}). Also, when a message arrives, we use the parameter name $\mathrm{xJ}$ to refer to the arriving value for the message field $x$. Processor $p_i$ stores an array $reg$ of $|\mathcal{P}|$ elements (line~\ref{ln:var}), such that the $k$-th entry stores the most recent information about processor $p_k$'s object and $reg[i]$ stores $p_i$'s actual object value. Every entry is a pair of the form $(v,ts)$, where the field $v$ is a $\nu$-bits object value and $ts$ is an unbounded integer that stores the object timestamp. The values of $ts$ serve as the index of $p_i$'s write operations. Similarly, $p_i$ maintains an index for the snapshot operations, $ssn$ (sequence number). Algorithm~\ref{alg:0disCongif} defines also the relation $\preceq$ that compares $(v,ts)$ and $(v',ts')$ according to the write operation indices (line~\ref{ln:preceq}). \smallskip \noindent \textbf{The $\mathsf{write}(v)$ operation.~~} Algorithm~\ref{alg:0disCongif}'s $\mathsf{write}(v)$ operation appears in lines~\ref{ln:0operationWriteV} to~\ref{ln:0writeReturn} (client-side) and lines~\ref{ln:0operationSnapshot} to~\ref{ln:0snapshotReturn} (server-side). The client-side operation $\mathsf{write}(v)$ stores the pair $(v,ts)$ in $reg[i]$ (line~\ref{ln:0tsPlusOne}), where $p_i$ is the calling processor and $ts$ is a unique operation index. The primitive $\mathsf{broadcast}$ sends to all the processors in $\mathcal{P}$ the message $\mathrm{WRITE}$ about $p_i$'s local perception of $reg$'s value. Upon the arrival of a $\mathrm{WRITE}$ message to $p_i$ from $p_j$ (line~\ref{ln:0arrivalWRITE}), the server-side code is run. Processor $p_i$ updates $reg$ according to the timestamps of the arriving values (line~\ref{ln:0kDotRegGetsMaxPreceqRegJWrite}). Then, $p_i$ replies to $p_j$ with the message $\mathrm{WRITEack}$ (line~\ref{ln:0sendSNAPSHOTackRegSsn}), which includes $p_i$'s local perception of the system shared registers. Getting back to the client-side, $p_i$ repeatedly broadcasts the message $\mathrm{WRITE}$ to all processors in $\mathcal{P}$ until it receives replies from a majority of them (line~\ref{ln:0broadcastWRITEreg}). Once that happens, it uses the arriving values for keeping $reg$ up-to-date (line~\ref{ln:0mergeRecWrite}). \smallskip \noindent \textbf{The $\mathsf{snapshot}(v)$ operation.~~} Algorithm~\ref{alg:0disCongif}'s $\mathsf{snapshot}()$ operation appears in lines~\ref{ln:0operationSnapshot} to~\ref{ln:0snapshotReturn} (client-side) and lines~\ref{ln:0arrivalSNAPSHOT} to~\ref{ln:0sendSNAPSHOTackRegSsn} (server-side). Recall that Delporte-Gallet \emph{et al.}\xspace~\cite[Algorithm~1]{DBLP:journals/tpds/Delporte-Gallet18} is non-blocking with respect to the snapshot operations as long as are no concurrent write operations. Thus, the client-side is written in the form of a repeat-until loop. Processor $p_i$ tries to query the system for the most recent value of the shared registers. The success of such attempts depends on the above assumption. Therefore, before each such broadcast, $p_i$ copies $reg$'s value to $prev$ (line~\ref{ln:0prevSsnGetsRegSsnPlusOne}) and exits the repeat-until loop only when the updated value of $reg$ indicates that there are no concurrent write operations. \begin{figure*}[t!] \begin{center} \includegraphics[page=1,scale=0.5]{DrawingsCrop.pdf} ~~\\ ~~\\ \includegraphics[page=3,scale=0.5]{DrawingsCrop.pdf} \end{center} \caption{\label{fig:0nonBlockExec}Examples of Algorithm~\ref{alg:0disCongif}'s executions. The upper drawing illustrates a case of a terminating snapshot operation (dashed line arrows) that occurs between two write operations (solid line arrows). The acknowledgments of these messages are arrows that start with circles and squares, respectively. The lower drawing illustrates a case in which every execution of line~\ref{ln:ssnPlusOne} occurs concurrently with write operations (regardless of whether the algorithm is self-stabilizing or not). Thus, snapshot operations cannot terminate.} \end{figure*} Figure~\ref{fig:0nonBlockExec} depicts two examples of Algorithm~\ref{alg:0disCongif}'s execution. The upper drawing illustrates a write operation that is followed by a snapshot operation and then a second write operation. We use this example when comparing algorithms~\ref{alg:9disCongif},~\ref{alg:disCongif} and~\ref{alg:terminating}. The lower drawing illustrates a case of an unbounded sequence of write operations that disrupts a snapshot operation, which does not terminate for an unbounded period. \begin{algorithm*}[t!] \begin{\VCalgSize} \noindent \textbf{local variables initialization:} $ssn := 0; ts := 0$\tcc*{snapshout, resp., write operation indices} $reg := [\bot, \ldots ,\bot]$\tcc*{shared registers ($\bot$ is smaller than any possibly written value)} $\textbf{foreach } k,s : repSnap[k, s] := \bot$\tcc*{stores $p_k$'s snapshot task result for index $s$} \smallskip \noindent \textbf{macro} $\mathrm{merge}(Rec)$ \label{ln:9merge} { \lFor{$p_k \in \mathcal{P}$}{$reg[k]\gets \max (\{reg[k]\} \cup \{r[k] \mid r \in Rec\})$\label{ln:9regGetsMaxRegCupMid}} } \smallskip \textbf{do forever} \Begin{\label{ln:9doForever} \lIf{$(writePending \neq \bot)$}{$\mathrm{baseWrite}(writePending);writePending \gets \bot$\label{ln:backGroundWrite}} \If{\emph{(there are messages $\mathrm{SNAP}()$ received and not yet processed)\label{ln:unboundedBuffer}}}{ \textbf{let} $\mathrm{SNAP}(source, sn)$ \textbf{be} {the oldest of these messages}\; $\mathrm{baseSnapshot}(source, sn)$\; \textbf{wait} \textbf{until} $(repSnap[source, sn] \neq \bot)$\label{ln:waitUntilReadSnap}; } } \smallskip \noindent \textbf{operation} $\mathsf{write}(v)$ \Begin{ $writePending \gets v$; \textbf{wait} \textbf{until} $(writePending = \bot); \Return()$\label{ln:preWrite}; } \smallskip \noindent \textbf{operation} $\mathsf{snapshot}()$ \Begin{ $sns \gets sns + 1; \label{ln:9snspp}\mathsf{reliableBroadcast} ~\mathrm{SNAP}(i, sns)$\label{ln:reliableBroadcastout}\; \textbf{wait} \textbf{until} $(repSnap[i, sns] \neq \bot); \Return(repSnap[i, sns])$\label{ln:9repSnapIsns}\; } \smallskip \noindent \textbf{function} $\mathrm{baseWrite}(v)$ \label{ln:9baseWrite} \Begin{ $ts \gets ts + 1; reg[i] \gets (ts,v)$; \textbf{let} $lReg:=reg$\; \lRepeat{$\mathrm{WRITEack}(\mathnormal{regJ} \succeq lReg)$ received from a majority\label{ln:9waitUntilWRITEack}}{$\mathsf{broadcast~} \mathrm{WRITE}(lReg)$\label{ln:9broadcastWRITEreg2};} $\mathrm{merge}(Rec)$ \textbf{where} $Rec$ is the set of $reg$ arrays received at line~\ref{ln:9waitUntilWRITEack}\label{ln:9mergeRecWrite2}\; } \noindent \textbf{function} $\mathrm{baseSnapshot}(s, t)$ \label{ln:9baseSnapshot}\Begin{ \While{$repSnap[s, t] = \bot$\label{ln:whileStart}}{ \textbf{let} $prev := reg$; $ssn \gets ssn + 1$\label{ln:prevRegSsnPlusOne}\; \Repeat{$(\mathnormal{sJ}=s, \mathnormal{tJ}=t, \bullet, \mathnormal{ssnJ}=ssn)$ \emph{received from a majority)}\label{ln:9waitUntilSNAPSHOTackReg2}}{$\mathsf{broadcast}~\mathrm{SNAPSHOT}(s, t, reg, ssn)$\label{ln:9waitUntilSNAPSHOTack};} $\mathrm{merge}(Rec)$ \textbf{where} $Rec$ is the set of $reg$ arrays received at line~\ref{ln:9waitUntilSNAPSHOTack}\; \lIf{$prev = reg$}{$\mathsf{reliableBroadcast} ~\mathrm{END}(source, sn, prev)$\label{ln:prevReg}} } } \smallskip \textbf{upon} message $\mathrm{WRITE}(\mathnormal{regJ})$ \textbf{arrival} \textbf{from} $p_j$ \Begin{ \lFor{$p_k \in \mathcal{P}$}{$reg[k] \gets \max_{\prec_{sn}}(reg[k], \mathnormal{regJ}[k])$} \textbf{send} $\mathrm{WRITEack}(reg)$ \textbf{to} $p_j$\; } \smallskip \textbf{upon} message $\mathrm{SNAPSHOT}(s, t, \mathnormal{regJ}, \mathnormal{ssnJ})$ \textbf{arrival} \textbf{from} $p_j$ \Begin{ \lFor{$p_k \in \mathcal{P}$}{$reg[k] \gets \max_{\prec_{sn}} (reg[k], \mathnormal{regJ}[k])$} \textbf{send} $\mathrm{SNAPSHOTack}(s, t, reg, \mathnormal{ssnJ})$ \textbf{to} $p_j$\; } \smallskip \textbf{upon} message $\mathrm{END}(s, t, val)$ \textbf{arrival} \textbf{from} $p_j$ \textbf{do} { $repSnap[s, t] \gets val$\label{ln:uponEND}\; } \caption{\label{alg:9disCongif}The non-self-stabilizing and always-terminating algorithm by Delporte-Gallet \emph{et al.}\xspace~\cite{DBLP:journals/tpds/Delporte-Gallet18} that emulates snapshot object; code for $p_i$} \end{\VCalgSize} \end{algorithm*} \subsection{The always-terminating algorithm by Delporte-Gallet \emph{et al.}\xspace} \label{sec:alwaysTerm} Delporte-Gallet \emph{et al.}\xspace~\cite[Algorithm~2]{DBLP:journals/tpds/Delporte-Gallet18} guarantee termination for any invocation pattern of write and snapshot operations, as long as the invoking processors do not fail during these operations. Its advantage over Delporte-Gallet \emph{et al.}\xspace~\cite[Algorithm~1]{DBLP:journals/tpds/Delporte-Gallet18} is that it can deal with an infinite number of concurrent write operations. This is because it guarantees the non-blocking progress criterion for the snapshot operations. We present~\cite[Algorithm~2]{DBLP:journals/tpds/Delporte-Gallet18} in Algorithm~\ref{alg:9disCongif} using the presentation style of this paper. We review Algorithm~\ref{alg:9disCongif} while pointing out some key challenges that exist when considering the context of self-stabilization. \smallskip \noindent \textbf{High-level overview.~~} Delporte-Gallet \emph{et al.}\xspace~\cite[Algorithm~2]{DBLP:journals/tpds/Delporte-Gallet18} use a job-stealing scheme for allowing rapid termination of snapshot operations. Processor $p_i \in \mathcal{P}$ starts its $\mathsf{snapshot}$ operation by queueing this new task at all processors $p_j \in \mathcal{P}$. Once $p_j$ receives $p_i$'s new task and when that task reaches the queue front, $p_j$ starts the $\mathrm{baseSnapshot}(s, t)$ procedure, which is similar to Algorithm~\ref{alg:0disCongif}'s $\mathsf{snapshot}()$ operation. This joint participation in all snapshot operations makes sure that all processors are aware of all on-going snapshots operations. This joint awareness allows the system processors to make sure that no write operation can stand in the way of on-going snapshot operations. To that end, the processors wait until the oldest snapshot operation terminates before proceeding with later operations. Specifically, they defer write operations that run concurrently with snapshot operations. This guarantees termination of snapshot operations via the interleaving and synchronization of snapshot and write operations. \smallskip \noindent \textbf{Detailed description.~~} Algorithm~\ref{alg:9disCongif} extends Algorithm~\ref{alg:0disCongif} in the sense that it uses all of Algorithm~\ref{alg:0disCongif}'s variables and two additional ones, which is a second operation index, $sns$, and an array $repSnap$, which $\mathsf{snapshot}()$ operations use. The entry $repSnap[x,y]$ holds the outcome of $p_x$'s $y$-th snapshot operation, where no explicit bound on the number of invocations of snapshot operations is given. In the context of self-stabilization, the use of such unbounded variables is not possible. The reasons are that real-world systems have bounded size memory as well as the fact that a single transient fault can bring any counter to its near overflow value and fill up any finite capacity buffer. We discuss the way around this challenge in Section~\ref{sec:aussata}. \smallskip \noindent \emph{The $\mathsf{write}()$ operation and the $\mathrm{baseWrite}()$ function.~~} Since $\mathsf{write}(v)$ operations are preemptible, $p_i$ cannot always start immediately to write. Instead, $p_i$ stores $v$ in $writePending_i$ together with a unique operation index (line~\ref{ln:preWrite}). The algorithm then runs the write operation as a background task (line~\ref{ln:backGroundWrite}) using the $\mathrm{baseWrite}()$ function (lines~\ref{ln:9baseWrite} to~\ref{ln:9mergeRecWrite2}). \smallskip \noindent \emph{The $\mathsf{snapshot}()$ operation.~~} A call to $\mathsf{snapshot}()$ (line~\ref{ln:9snspp}) causes $p_i$ to reliably broadcast, via the primitive $\mathsf{reliableBroadcast}$, a new $ssn$ index in a $\mathrm{SNAP}$ to all processors in $\mathcal{P}$. Processor $p_i$ then places it as a background task (line~\ref{ln:9repSnapIsns}). We note that for our proposed solutions we do not assume access to a reliable broadcast mechanism such as $\mathsf{reliableBroadcast}$; see Section~\ref{sec:aussata} for details and an alternative approach that uses safe registers instead of the $\mathsf{reliableBroadcast}$ primitive, which often has higher communication costs. \smallskip \noindent \emph{The $\mathrm{baseSnapshot}()$ function.~~} This function essentially follows the $\mathsf{snapshot}()$ operation of Algorithm~\ref{alg:0disCongif}. That is, Algorithm~\ref{alg:0disCongif}'s snapshot repeat-until loops iterates until the retrieved $reg$ vector equals to the one that was known prior to the last repeat-until iteration. Algorithm~\ref{alg:0disCongif}'s $\mathrm{baseSnapshot()}$ procedure returns after at least one snapshot process has terminated. In detail, processor $p_i$ stores in $repSnap[s,t]$, via a reliable broadcast of the $\mathrm{END}$ message, the result of the snapshot process (line~\ref{ln:prevReg} and~\ref{ln:uponEND}). \smallskip \noindent \emph{Synchronization between the $\mathrm{baseWrite}()$ and $\mathrm{baseSnapshot}()$ functions.~~} Algorithm~\ref{alg:9disCongif} interleaves the background tasks in a do forever loop (lines~\ref{ln:backGroundWrite} to~\ref{ln:waitUntilReadSnap}). As long as there is an awaiting write task, processor $p_i$ runs the $\mathrm{baseWrite}()$ function (line~\ref{ln:backGroundWrite}). Also, if there is an awaiting snapshot task, processor $p_i$ selects the oldest task, $(source, sn)$, and uses the $\mathrm{baseSnapshot}(source, sn)$ function. Here, Algorithm~\ref{alg:9disCongif} blocks until $repSnap[source, sn]$ contains the result of that snapshot task. Note that line~\ref{ln:unboundedBuffer} implies that Algorithm~\ref{alg:9disCongif} does not explicitly assume that processor $p_i$ has bounded space for storing $\mathrm{SNAP}$ messages. In the context of self-stabilization, there must be an explicit bound on the size of all memory in use. We discuss how to overcome this challenge in Section~\ref{sec:aussata}. \begin{figure*}[t!] \begin{center} \includegraphics[page=4,scale=0.5]{DrawingsCrop.pdf} \end{center} \caption{\label{fig:9nonBlockExec}Algorithm~\ref{alg:9disCongif}'s execution for the case depicted by the upper drawing of Figure~\ref{fig:0nonBlockExec}. The drawing illustrates a case of a terminating snapshot operation (dashed line arrows) that occurs between two write operations (solid line arrows). The acknowledgments of these messages are arrows that start with circles and squares, respectively.} \end{figure*} Figure~\ref{fig:9nonBlockExec} depicts an example of Algorithm~\ref{alg:9disCongif}'s execution where a write operation is followed by a snapshot operation. Note that each snapshot operation will be handled separately and the communication costs of each such operation requires $\mathcal{O}(n^2)$ messages. \section{An Unbounded Self-stabilizing Non-blocking Algorithm} \label{sec:aussnba} We propose Algorithm~\ref{alg:disCongif} as an elegant extension of Delporte-Gallet \emph{et al.}\xspace~\cite[Algorithm~1]{DBLP:journals/tpds/Delporte-Gallet18}; we have simply added the boxed code lines to Algorithm~\ref{alg:disCongif}. Algorithms~\ref{alg:0disCongif} and~\ref{alg:disCongif} differ in their ability to deal with stale information that can appear in the system when starting in an arbitrary state. Note that we model the appearance of stale information as the result of transient faults and assume that they occur only before the system starts running. \subsection{Algorithm description} \label{sec:def} Our description refers to the values of variable $X$ at node $p_i$ as $X_i$, \emph{i.e.,}\xspace the variable name with a subscript that indicates the node identifier. Algorithm~\ref{alg:disCongif} considers the case in which any of $p_i$'s operation indices, $ssn_i$ and $ts_i$, is smaller than some other $ssn$ or $ts$ value, say, $ssn_m$ $reg_{i}[i].ts$, $reg_{j}[i].ts$ or $reg_m[i].ts$, where $X_m$ appears in the $X$ field of some in-transit message. For the case of corrupted $ssn$ values, $p_i$'s client-side simply ignores arriving message with $ssn$ values that do not match $ssn_i$ (line~\ref{ln:waitUntilSNAPSHOTackReg}). For the sake of clarity of our proposal, we also remove periodically any stored snapshot replies that their $ssn$ fields are not equal to $ssn_i$. For the case of corrupted $ts$ values, $p_i$'s do forever loop makes sure that $ts_i$ is not smaller than $reg_i[i].ts$ (line~\ref{ln:tsGetsMaxTsRegTs}) before gossiping to every processor $p_j \in \mathcal{P}$ its local copy of $p_j$'s shared register (line~\ref{ln:sendGossip}). Also, upon the arrival of such gossip messages, Algorithm~\ref{alg:disCongif} merges the arriving information with the local one (line~\ref{ln:GOSSIPupdate}). Moreover, when replies from write or snapshot messages arrive to $p_i$, it merges the arriving $ts$ value with the one in $ts_i$ (line~\ref{ln:tsRegMaxTsRegTs}). On the presentation side, we clarify that the code lines~\ref{ln:0broadcastWRITEreg} to~\ref{ln:0mergeRecWrite} and lines~\ref{ln:0ssnPlusOne} to~\ref{ln:0mergeRecSnapshot} are equivalent to lines~$3$ to~$5$ and lines~$10$ and~$12$ of \cite[Algorithm~1]{DBLP:journals/tpds/Delporte-Gallet18}, respectively, because it is merely a more detailed description of the code described in~\cite[Algorithm~1]{DBLP:journals/tpds/Delporte-Gallet18}. Figure~\ref{fig:disCongifExec} depicts an example of Algorithm~\ref{alg:disCongif}'s execution in which a write operation is followed by a snapshot operation. Note that gossip messages do not interfere with write and snapshot operations. \begin{figure*}[t!] \begin{center} \includegraphics[page=2,scale=0.5]{DrawingsCrop.pdf} \end{center} \caption{\label{fig:disCongifExec}{Algorithm~\ref{alg:disCongif}'s execution for the case depicted in the upper drawing of Figure~\ref{fig:0nonBlockExec}. The drawing illustrates a case of a terminating snapshot operation (dashed line arrows) that occurs between two write operations (solid line arrows). The acknowledgments of these messages are arrows that start with circles and squares, respectively.}} \end{figure*} \begin{algorithm*}[t!] \begin{\VCalgSize} \noindent \textbf{Definitions of $\preceq$:} For integers $t$ and $t'$: $(\bullet,t) \preceq (\bullet,t') \iff t \leq t'$; For arrays $tab$ and $tab'$ of $(\bullet, integer)$: $tab \preceq tab' \iff \forall p_k \in \mathcal{P} : tab[k] \preceq tab'[k]$; Also, $a \prec b \equiv a \preceq b \land a \neq b$\label{ln:def3}\; \smallskip \noindent \textbf{local variables initialization (optional in the context of self-stabilization):} $ssn := 0; ts := 0$\tcc*{snapshout, resp., write operation indices} ~$reg := [\bot, \ldots ,\bot]$\tcc*{shared registers ($\bot$ is smaller than any possibly written value)} \smallskip \noindent \textbf{macro} $\mathrm{merge}(Rec)$ \label{ln:merge} \Begin{ \fbox{$ts\gets \max (\{ts, reg[i].ts\} \cup \{r[i].ts \mid r \in Rec\})$\label{ln:tsRegMaxTsRegTs};} \lFor{$p_k \in \mathcal{P}$}{$reg[k]\gets \max (\{reg[k]\} \cup \{r[k] \mid r \in Rec\})$\label{ln:regGetsMaxRegCupMid}} } \smallskip \noindent \textbf{do forever} \Begin{\label{ln:disCongifDoForever} \fbox{\lForEach{$ssn'\neq ssn$}{\textbf{delete} $\mathrm{SNAPSHOTack}(-, ssn')$\label{ln:deleteSNAPSHOTack}}} \fbox{$ts\gets \max \{ts, reg[i].ts\}$\label{ln:tsGetsMaxTsRegTs};} \fbox{\lFor{$p_k \in \mathcal{P}:k\neq i$}{$\mathsf{send}~ \mathrm{GOSSIP}(reg[k])~ \mathsf{to}~ p_k$\label{ln:sendGossip}}} } \smallskip \noindent \textbf{operation} $\mathsf{write}(v)$ \label{ln:operationWriteV} \Begin{ $ts \gets ts+1; reg[i] \gets (v, ts)$; \textbf{let} $lReg:=reg$\label{ln:tsPlusOne}\; \lRepeat{$\mathrm{WRITEack}(\mathnormal{regJ} \succeq lReg)$ received from a majority\label{ln:waitUntilWRITEackReg}}{$\mathsf{broadcast~} \mathrm{WRITE}(lReg)$\label{ln:broadcastWRITEreg};} $\mathrm{merge}(Rec)$ \textbf{where} $Rec$ is the set of $reg$ arrays received at line~\ref{ln:waitUntilWRITEackReg}\label{ln:mergeRecWrite}\; $\Return()$\label{ln:writeReturn}\; } \noindent \textbf{operation} $\mathsf{snapshot}()$ \label{ln:operationSnapshot} \Begin{ \Repeat{$prev = reg$}{ \textbf{let} $prev := reg$; $ssn \gets ssn + 1$\label{ln:prevSsnGetsRegSsnPlusOne}\; \lRepeat{$\mathrm{SNAPSHOTack}(\bullet, \mathnormal{ssnJ} =ssn)$ received from a majority\label{ln:waitUntilSNAPSHOTackReg}}{$\mathsf{broadcast} ~\mathrm{SNAPSHOT}(reg, ssn)$\label{ln:ssnPlusOne};} $\mathrm{merge}(Rec)$ \textbf{where} $Rec$ is the set of $reg$ arrays received at line~\ref{ln:waitUntilSNAPSHOTackReg}\label{ln:mergeRecSnapshot}\; } $\Return(reg)$\label{ln:snapshotReturn}\; } \textbf{upon} message $\mathrm{GOSSIP}(\mathnormal{regJ})$ \textbf{arrival} \textbf{from} $p_j$ \Begin{ \fbox{$reg[i]\gets \max \{reg[i],\mathnormal{regJ}\};ts\gets \max \{ts, reg[i].ts\}$\label{ln:GOSSIPupdate};}} \smallskip \textbf{upon} message $\mathrm{WRITE}(\mathnormal{regJ})$ \textbf{arrival} \textbf{from} $p_j$ \label{ln:arrivalWRITE} \Begin{ \lFor{$p_k \in \mathcal{P}$}{$reg[k] \gets \max_{\preceq}(reg[k], \mathnormal{regJ}[k])$\label{ln:kDotRegGetsMaxPreceqRegJWrite}} \textbf{send} $\mathrm{WRITEack}(reg)$ \textbf{to} $p_j$\label{ln:sendWRITEackReg}\; } \textbf{upon} message $\mathrm{SNAPSHOT}(\mathnormal{regJ}, ssn)$ \textbf{arrival} \textbf{from} $p_j$ \label{ln:arrivalSNAPSHOT} \Begin{ \lFor{$p_k \in \mathcal{P}$}{$reg[k] \gets \max_{\preceq}\{ reg[k], \mathnormal{regJ}[k] \}$\label{ln:kDotRegGetsMaxPreceqRegJSnapshoot}} \textbf{send} $\mathrm{SNAPSHOTack}(reg, ssn)$ to $p_j$\label{ln:sendSNAPSHOTackRegSsn}\; } \end{\VCalgSize} \caption{\label{alg:disCongif}Self-stabilizing algorithm for non-blocking snapshot object; code for $p_i$. The boxed code lines mark the added code to Algorithm~\ref{alg:0disCongif}.} \end{algorithm*} \subsection{Correctness} \label{sec:cor1} Although the extension performed to Algorithm~\ref{alg:0disCongif} for obtaining Algorithm~\ref{alg:disCongif} includes only few changes, proving convergence and closure for Algorithm~\ref{alg:disCongif} is not straightforward. We proceed with the details. \smallskip \noindent \textbf{Notation and definitions} Definition~\ref{def:safeConfig} refers to $p_i$'s timestamps and snapshot sequence numbers, where $p_i \in \mathcal{P}$. The set of $p_i$'s timestamps includes $ts_{i}$, $reg_{i}[i].ts$, $reg_{j}[i].ts$ and the value of $reg_m[i].ts$ in the payload of any message $m$ that is in transient in the system. The set of $p_i$'s snapshot sequence numbers includes $ssn_{i}$ and the value of $ssn_m$ in the payload of any message $m$ that is in transient in the system. \begin{definition}[Algorithm~\ref{alg:disCongif}'s consistent operation indices] \label{def:safeConfig} (i) Let $c$ be a system state in which $ts_i$ is greater than or equal to any $p_i$'s timestamp values in the variables and fields related to $ts$. We say that the $ts$' timestamps are consistent in $c$. (ii) Let $c$ be a system state in which $ssn_i$ is greater than or equal to any $p_i$'s snapshot sequence numbers in the variables and fields related to $ssn$. We say that the $ssn$'s snapshot sequence numbers are consistent in $c$. \end{definition} Theorems~\ref{thm:mainConvergence} and~\ref{thm:closure1} show the properties required by the self-stabilization design criteria. \begin{theorem}[\textbf{Algorithm~\ref{alg:disCongif}'s convergence}] % \label{thm:mainConvergence} % Let $R$ be a fair and unbounded execution of Algorithm~\ref{alg:disCongif}. Within $\mathcal{O}(1)$ asynchronous cycles in $R$, the system reaches a state $c \in R$ in which $ts$' timestamps and $ssn$'s snapshot sequence numbers are consistent in $c$. \end{theorem} \begin{proof} The proof of the theorem follows by Lemmas~\ref{thm:eventuallyAscendingSent} and~\ref{thm:sequenceNumberRecovery}. \begin{lemma}[\textbf{Timestamp convergence}] % \label{thm:eventuallyAscendingSent} % Let $R$ be an unbounded fair execution of Algorithm~\ref{alg:disCongif}. Within $\mathcal{O}(1)$ asynchronous cycles in $R$, the system reaches a state $c \in R$ in which the value of $ts_i$ is greater than or equal to any $p_i$'s timestamp value. Moreover, suppose that node $p_i$ takes a step immediately after $c$ that includes the execution of line~\ref{ln:tsPlusOne}. Then in $c$, it holds that $ts_{i}=reg_{i}[i].ts=reg_{j}[i].ts$ as well as for every messages $m\in \mathit{channel}_{i,j},\mathit{channel}_{j,i}$ that is in transit from $p_i$ to $p_j$ or $p_j$ to $p_i$ it holds that $m.reg[i].ts=ts_{i}$. \end{lemma} \begin{proof} Claims~\ref{thm:neverRemove},~\ref{thm:neverRemoveAgain},~\ref{thm:GOSSIPregJ} and~\ref{thm:tsititTR} prove the lemma. Claim~\ref{thm:neverRemove} denotes by $X_{i,\ell}$ the $\ell$-th value stored in $X_i$ during $R$, where $\ell \in \mathbb{N}$. \begin{claim} % \label{thm:neverRemove} % The sequences $ts_{i,\ell}$, $reg_{i,\ell}[i].ts$, $reg_{j,\ell}[i].ts$, $reg_{i,\ell}[i]$ and $reg_{j,\ell}[i]$ are non-decreasing. \end{claim} \begin{claimProof} We note that Algorithm~\ref{alg:disCongif} does only the following actions on $ts$ and $reg$ fields: increment (line~\ref{ln:tsPlusOne}) and merge using the $\max$ function (lines~\ref{ln:tsRegMaxTsRegTs},~\ref{ln:regGetsMaxRegCupMid},~\ref{ln:tsGetsMaxTsRegTs},~\ref{ln:mergeRecSnapshot},~\ref{ln:GOSSIPupdate},~\ref{ln:kDotRegGetsMaxPreceqRegJWrite} and~\ref{ln:kDotRegGetsMaxPreceqRegJSnapshoot}). That is, there are no assignments. Thus, the claim is true, because the value of these fields is never decremented during $R$. \end{claimProof} \begin{claim} % \label{thm:neverRemoveAgain} % Within $\mathcal{O}(1)$ asynchronous cycles, $ts_{i} \geq reg_{i}[i].ts$. \end{claim} \begin{claimProof} Since $R$ is unbounded, it holds that node $p_j \in \mathcal{P}$ calls line~\ref{ln:sendGossip} for an unbounded number of times during $R$. Recall the line numbers that may change the value of $ts_{i}$ and $reg_{i}[i].ts$, cf. the proof of Claim~\ref{thm:neverRemove}. Note that only line~\ref{ln:tsPlusOne} change the value of $ts_{i}$, via an increment (thus we do not have a simple equality) whereas lines~\ref{ln:tsRegMaxTsRegTs},~\ref{ln:tsGetsMaxTsRegTs} and~\ref{ln:GOSSIPupdate} update $ts_i$ and $reg_{i}[i].ts$ by taking the maximum value of $ts_i$ and $reg_{i}[i].ts$. The rest of the proof is implied by Claim~\ref{thm:neverRemove}, and the fact that $p_i$ executes line~\ref{ln:tsGetsMaxTsRegTs} at least once in every $\mathcal{O}(1)$ asynchronous cycles. \end{claimProof} Algorithm~\ref{alg:disCongif} sends $\mathrm{GOSSIP}$ messages in line~\ref{ln:sendGossip}, requests messages in lines~\ref{ln:broadcastWRITEreg} and~\ref{ln:ssnPlusOne} as well as replies in lines~\ref{ln:sendWRITEackReg} and~\ref{ln:sendSNAPSHOTackRegSsn}. Claim~\ref{thm:GOSSIPregJ}'s proof considers lines~\ref{ln:broadcastWRITEreg} and~\ref{ln:ssnPlusOne} in which $p_i$ sends a request message to $p_j$, whereas Claim~\ref{thm:tsititTR}'s proof considers lines~\ref{ln:sendGossip},~\ref{ln:sendWRITEackReg} and~\ref{ln:sendSNAPSHOTackRegSsn} in which $p_j$ replies or gossips to $p_i$. \begin{claim} % \label{thm:GOSSIPregJ} % Let $m\in \mathit{channel}_{i,j}$ be a message on transit from $p_i$ to $p_j$ (during the first asynchronous cycles of $R$) and $reg_m$ the value of the $reg$ filed in $m$, where $p_i,p_j \in \mathcal{P}$ are non-failing nodes. Within $\mathcal{O}(1)$ asynchronous cycles, $reg_{i}[i].ts \geq reg_{m}[i].ts$ and $reg_{i}[i].ts \geq \mathnormal{regJ}[i].ts$ whenever $p_j$ raises the events $\mathrm{GOSSIP}(\mathnormal{regJ})$, $\mathrm{WRITE}(\mathnormal{regJ})$ or $\mathrm{SNAPSHOT}(\mathnormal{regJ},\bullet)$. \end{claim} \begin{claimProof} Suppose during the first asynchronous cycles of $R$, node $p_i$ indeed sends message $m$, \emph{i.e.,}\xspace $m$ does not appear in $R$'s starting system state. Let $a_{k} \in R$ be the first step in $R$ in which $p_i$ calls line~\ref{ln:sendGossip},~\ref{ln:broadcastWRITEreg} or~\ref{ln:ssnPlusOne} and for which there is a step $a_{depart,k} \in R$, which appears in $R$ after $a_{k}$ and in which message $m$ is sent (in a packet by the end-to-end or quorum protocol). Note that the value of $reg_{m}[i].ts$ in the message payload is defined by the value of $reg_{i}[i].ts$ in the system state that immediately precedes $a_{k}$. The rest of the proof relies on the fact that until $m$ arrives to $p_j$, the invariant $reg_{i}[i].ts \geq reg_{m}[i].ts$ holds (due to Claim~\ref{thm:neverRemove}). Let $a_{arrival,k} \in R$ be the first step that appears after $a_{depart,k}$ in $R$, if there is any such step, in which the node at $p_j$ delivers the packet (token) that $a_{depart,k}$ transmits the message $m$ (if there are several such packets, consider the last to arrive). By the correctness of the end-to-end~\cite{DBLP:journals/ipl/DolevDPT11,DBLP:conf/sss/DolevHSS12} or quorum service (Corollary~\ref{thm:basicCorollary}), step $a_{arrival,k}$ appears in $R$ within $\mathcal{O}(1)$ asynchronous cycles. During $a_{arrival,k'}$, node $p_j$ raises the message delivery event $\mathrm{GOSSIP}(\mathnormal{regJ})$ (when $a_{k}$ considers line~\ref{ln:GOSSIPupdate}), $\mathrm{WRITE}(\mathnormal{regJ})$ (when $a_{k}$ considers line~\ref{ln:arrivalWRITE}) or $\mathrm{SNAPSHOT}(\mathnormal{regJ}, ssn)$ (when $a_{k}$ considers line~\ref{ln:arrivalSNAPSHOT}), such that $reg_{i}[i].ts \geq reg_{m}[i].ts = \mathnormal{regJ}[i].ts$. Suppose that step $a_{k}$ does not appear in $R$, \emph{i.e.,}\xspace $m$ appears in $R$'s starting system state. By the definition of asynchronous rounds with round-trips (Remark~\ref{ss:first asynchronous cycles}), within $\mathcal{O}(1)$ asynchronous cycles, all messages in transit to $p_j$ arrive (or leave the communication channel). Immediately after that, the system starts an execution in which this claim holds trivially. \end{claimProof} \begin{claim} % \label{thm:tsititTR} % Let $m' \in \mathit{channel}_{j,k}$ be a message on transit from $p_j$ to $p_k$ (during the first asynchronous cycles of $R$) and $reg_{m'}$ the value of the $reg$ filed in $m'$, where $p_i,p_j,p_k \in \mathcal{P}$ are non-failing nodes and $i=k$ may or may not hold. Within $\mathcal{O}(1)$ asynchronous cycles, $reg_{j}[i].ts \geq reg_{m'}[i].ts$ and $reg_{i}[i].ts \geq \mathnormal{regJ}[i].ts$ whenever $p_k$ raises the events $\mathrm{GOSSIP}(\mathnormal{regJ})$, $\mathrm{WRITEack}(\mathnormal{regJ})$ or $\mathrm{SNAPSHOTack}(\mathnormal{regJ},\bullet)$. \end{claim} \begin{claimProof} Suppose during the first asynchronous cycles of $R$, node $p_k$ indeed sends message $m'$, \emph{i.e.,}\xspace $m'$ does not appear in $R$'s starting system state. Let $a_{k} \in R$ be the first step in $R$ in which $p_k$ calls line~\ref{ln:sendGossip},~\ref{ln:sendWRITEackReg} or~\ref{ln:sendSNAPSHOTackRegSsn} and for which there is a step $a_{depart,k} \in R$, which appears in $R$ after $a_{k}$. Note that the value of $reg_{m'}[i].ts$ in the message payload is defined by the value of $reg_{i}[i].ts$ in the system state that immediately precedes $a_{k}$. The rest of the proof relies on the fact that until $m'$ arrives to $p_j$, the invariant $reg_{i}[i].ts \geq reg_{m'}[i].ts$ holds (due to Claim~\ref{thm:neverRemove}). Let $a_{arrival,k} \in R$ be the first step that appears after $a_{depart,k}$ in $R$, if there is any such step, in which the node at $p_j$ delivers the packet (token) that $a_{depart,k}$ transmits the message $m$ (if there are several such packets, consider that the last to arrive). By the correctness of the gossip and quorum services (Corollary~\ref{thm:basicCorollary}), step $a_{arrival,k}$ appears in $R$ within $\mathcal{O}(1)$ asynchronous cycles. During $a_{arrival,k'}$, node $p_j$ raises the message delivery event $\mathrm{GOSSIP}(\mathnormal{regJ})$ (when $a_{k}$ considers line~\ref{ln:sendGossip}) $\mathrm{WRITEack}(\mathnormal{regJ})$ (when $a_{k}$ considers line~\ref{ln:sendWRITEackReg}) or $\mathrm{SNAPSHOTack}(\mathnormal{regJ},\bullet)$ (when $a_{k}$ considers line~\ref{ln:sendSNAPSHOTackRegSsn}), such that $reg_{i}[i].ts \geq reg_{m'}[i].ts = \mathnormal{regJ}[i].ts$. For the case in which step $a_{k}$ does not appear in $R$, the proof follows the same arguments that appear in the proof of Claim~\ref{thm:GOSSIPregJ}. \end{claimProof} \noindent This completes the proof of the lemma. \end{proof} \begin{lemma}[\textbf{Sequence number convergence}] % \label{thm:sequenceNumberRecovery} % Let $R$ be a fair and unbounded execution of Algorithm~\ref{alg:disCongif}. Within $\mathcal{O}(1)$ asynchronous cycles in $R$, the system reaches a state $c_x \in R$ in which the value of $ssn_i$ is greater than or equal to any $p_i$'s snapshot sequence number. \end{lemma} \begin{proof} Claims~\ref{thm:neverRemoveS},~\ref{thm:GOSSIPregJS} and~\ref{thm:tsititTRS} prove the lemma. \begin{claim} % \label{thm:neverRemoveS} % The sequence $ssn_{i,\ell}$ is non-decreasing. \end{claim} \begin{claimProof} Algorithm~\ref{alg:disCongif} only increments (line~\ref{ln:prevSsnGetsRegSsnPlusOne}), and assigns (lines~\ref{ln:ssnPlusOne} and~\ref{ln:sendSNAPSHOTackRegSsn}) $ssn$ values. Thus, the claim is true, because the value of this field is never decremented during $R$. \end{claimProof} \smallskip \noindent The proofs of Claims~\ref{thm:GOSSIPregJS} and~\ref{thm:tsititTRS} are followed by similar arguments to the ones that appear in the proofs of Claims~\ref{thm:GOSSIPregJ} and~\ref{thm:tsititTR}. \begin{claim} % \label{thm:GOSSIPregJS} % Let $m\in \mathit{channel}_{i,j}$ be a $\mathrm{SNAPSHOT}$ message on transit from $p_i$ to $p_j$ (during the first asynchronous cycles of $R$) that includes the filed $ssn$ with the value of $ssn_m$. Within $\mathcal{O}(1)$ asynchronous cycles, $ssn_{i} \geq ssn_{m'}$ including when $p_j$ raises the event $\mathrm{SNAPSHOT}(\mathnormal{regJ}, ssn_{m'})$. \end{claim} \begin{claim} % \label{thm:tsititTRS} % Let $m' \in \mathit{channel}_{j,i}$ be a $\mathrm{SNAPSHOTack}$ message on transit from $p_j$ to $p_i$ (during the first asynchronous cycles of $R$) and $ssn_{m'}$ the value of the $reg$ filed in $m'$. Within $\mathcal{O}(1)$ asynchronous cycles, $ssn_{i} \geq ssn_{m}$ including when $p_j$ raises the event $\mathrm{SNAPSHOTack}(\mathnormal{regJ}, ssn_m)$. \end{claim} \noindent This completes the proof of the lemma, which completes the proof of the theorem. \end{proof} \end{proof} \begin{theorem}[\textbf{Algorithm~\ref{alg:disCongif}'s termination and linearization}] % \label{thm:closure1} % Let $R$ be an execution of Algorithm~\ref{alg:disCongif} that starts in system state $c$, in which the timestamps and snapshot sequence numbers are consistent (Definition~\ref{def:safeConfig}). Execution $R$ is legal with respect to the task of emulating snapshot objects. \end{theorem} \begin{proof} We start the proof by observing the differences between Algorithms~\ref{alg:0disCongif} and~\ref{alg:disCongif}. Note that Algorithms~\ref{alg:0disCongif} and~\ref{alg:disCongif} use the same variables. Any message that Algorithm~\ref{alg:0disCongif} sends, also Algorithm~\ref{alg:disCongif} sends. The only exception are gossip messages: Algorithm~\ref{alg:disCongif} sends gossip messages, while Algorithm~\ref{alg:0disCongif} does not. The two algorithms differ in line~\ref{ln:tsRegMaxTsRegTs}, lines~\ref{ln:deleteSNAPSHOTack} to~\ref{ln:sendGossip} and line~\ref{ln:GOSSIPupdate}. The next step in the proof is to show that during $R$, any step that includes the execution of line~\ref{ln:GOSSIPupdate} does not change the state of the calling processor. This is due to the fact the every timestamp uniquely couples an object value (line~\ref{ln:tsGetsMaxTsRegTs}) and that timestamps are consistent in every system state throughout $R$ (Lemma~\ref{thm:eventuallyAscendingSent}). The rest of the proof considers $Alg_{noGOSSIP}$ that is obtained from the code of Algorithm~\ref{alg:disCongif} by the removal of lines~\ref{ln:sendGossip} and~\ref{ln:GOSSIPupdate}, in which the gossip messages are sent and received, respectively. We use this definition to show that $Alg_{noGOSSIP}$ simulates Algorithm~\ref{alg:0disCongif}. This means that from the perspective of its external behavior (\emph{i.e.,}\xspace its requests, replies and failure events), any trace of $Alg_{noGOSSIP}$ has a trace of Algorithm~\ref{alg:0disCongif} (as long as indeed the starting system state, $c$, encodes consistent timestamps and snapshot sequence numbers). Since Algorithm~\ref{alg:0disCongif} satisfies the task of emulating snapshot objects, it holds that $Alg_{noGOSSIP}$ also satisfies the task. This implies that Algorithm~\ref{alg:disCongif} satisfies the task as well. Recall the fact the every timestamp uniquely couples an object value (line~\ref{ln:tsGetsMaxTsRegTs}) as well as that timestamps and snapshot sequence numbers are consistent in every system state throughout $R$ (Lemma~\ref{thm:eventuallyAscendingSent}). These facts imply that also line~\ref{ln:tsRegMaxTsRegTs}, and lines~\ref{ln:deleteSNAPSHOTack} to~\ref{ln:tsGetsMaxTsRegTs} do not change the state of the calling node. \end{proof} \section{An Unbounded Self-stabilizing Always Terminating Algorithm} \label{sec:aussata} We propose Algorithm~\ref{alg:terminating} as a variation of Delporte-Gallet \emph{et al.}\xspace~\cite[Algorithm~2]{DBLP:journals/tpds/Delporte-Gallet18}. Algorithms~\ref{alg:9disCongif} and~\ref{alg:terminating} differ mainly in their ability to recover from transient faults. This implies some constraints. For example, Algorithm~\ref{alg:terminating} must have a clear bound on the number of pending snapshot tasks as well as on the number of stored results from snapshot tasks that have already terminated (see Section~\ref{sec:alwaysTerm} for details). For sack of simple presentation, Algorithm~\ref{alg:terminating} assumes that the system needs, for each processor, to cater for at most one pending snapshot task. It turns out that this assumption allows us to avoid the use of a self-stabilizing mechanism for reliable broadcast, as an extension of the non-self-stabilizing reliable broadcast that Delporte-Gallet \emph{et al.}\xspace~\cite[Algorithm~2]{DBLP:journals/tpds/Delporte-Gallet18} use. Instead, Algorithm~\ref{alg:terminating} uses a simpler mechanism for safe registers. The above opens up another opportunity: Algorithm~\ref{alg:terminating} can defer pending snapshot tasks until either (i) at least one processor was able to observe at least $\delta$ concurrent write operations, where $\delta$ is an input parameter, or (ii) no $\delta$ concurrent write operations were observed, \emph{i.e.,}\xspace $\Delta=\emptyset$ (line~\ref {ln:exceedDelta}). Our intention here is to have $\delta$ as a tunable parameter that balances the latency (with respect to snapshot operations) vs. communication costs. That is, for the case of $\delta$ being a very high (finite) value, Algorithm~\ref{alg:terminating} guarantees termination in a way that resembles~\cite[Algorithm~1]{DBLP:journals/tpds/Delporte-Gallet18}, which uses $\mathcal{O}(n)$ messages per snapshot operation, and for the case of $\delta=0$, Algorithm~\ref{alg:terminating} behaves in a way that resembles~\cite[Algorithm~2]{DBLP:journals/tpds/Delporte-Gallet18}, which uses $\mathcal{O}(n^2)$ messages per snapshot operation. \subsection{High-level description} Algorithms~\ref{alg:9disCongif} uses reliable broadcasts for informing all non-failing processors about new snapshot tasks (line~\ref{ln:reliableBroadcastout}) as well as the results of snapshot tasks that have terminated (line~\ref{ln:prevReg}). Since we assume that each processor can have at most one pending snapshot task, we can avoid the need of using a self-stabilizing mechanism for reliable broadcast. Indeed, Algorithm~\ref{alg:terminating} simply lets every processor disseminate its (at most one) pending snapshot task and use a safe register for facilitating the delivery of the task result to its initiator. That is, once a processor finishes a snapshot task, it broadcasts the result to all processors and waits for replies from a majority of processors, which may possibly include the initiator of the snapshot task (using the macro $\mathsf{safeReg}()$, line~\ref{ln:safeStoreSend}). This way, if processor $p_j$ notices that it has the result of an ongoing snapshot task, it sends that result to the requesting processor. \subsection{Algorithm details} We review Algorithm~\ref{alg:terminating}'s do forever loop (lines~\ref{ln:deleteSNAPSHOTack2} to~\ref{ln:letSexceedDeltaCall}), the $\mathrm{baseSnapshot}()$ function together with the dealing of message $\mathrm{SNAPSHOT}$ (lines~\ref{ln:SNAPSHOTarrival} to~\ref{ln:SNAPSHOTarrivalEND}), as well as the macro $\mathsf{safeReg}(s,r)$ (line~\ref{ln:safeStoreSend}) together with the dealing of message $\mathrm{SAVE}$ (lines~\ref{ln:safeStoreArrival} to~\ref{ln:safeStoreSendAck}). \smallskip \noindent \textbf{The do forever loop.~~} Algorithm~\ref{alg:terminating}'s do forever loop (lines~\ref{ln:deleteSNAPSHOTack2} to~\ref{ln:letSexceedDeltaCall}), includes a number of lines for cleaning stale information, such as out-of-synch $\mathrm{SNAPSHOTack}$ messages (line~\ref{ln:deleteSNAPSHOTack2}), out-dated operation indices (line~\ref{ln:tsGetsMaxTsRegTs2}), illogical vector-clocks (line~\ref{ln:vcFix}) or corrupted $pndTsk$ entries (line~\ref{ln:snsNegRepSnap}). The gossiping of operation indices (lines~\ref{ln:sendGossip2} and~\ref{ln:GOSSIParrival}) also helps to remove stale information (as in Algorithm~\ref{alg:disCongif} but only with the addition of $sns$ values). The synchronization between write and snapshot operations (lines~\ref{ln:writePendingExceedDelta} and~\ref{ln:letSexceedDeltaCall}) starts with a write, if there is any such pending task (line~\ref{ln:writePendingExceedDelta}), before running its own snapshot task, if there is any such pending, as well as any snapshot task (initiated by others) for which $p_i$ observed that at least $\delta$ write operations occur concurrently with it (line~\ref{ln:letSexceedDeltaCall}). \smallskip \noindent \textbf{The $\mathsf{write}()$ operation and the $\mathrm{baseWrite}()$ function.~~} As in Algorithm~\ref{alg:9disCongif}, $p_i$ does not start immediately a write operation. Node $p_i$ permits concurrent write operations by storing $v$ and a unique index in $writePending_i$ (line~\ref{ln:tsEqtsPlusOne}). The algorithm then runs the write operation as a background task (line~\ref{ln:writePendingExceedDelta}) using the $\mathrm{baseWrite}()$ function (line~\ref{ln:waitUntilWRITEackReg2}). \smallskip \noindent \textbf{The $\mathrm{baseSnapshot}()$ function and the $\mathrm{SNAPSHOT}$ message.~~} Algorithm~\ref{alg:terminating} maintains the state of every snapshot task in the array $pndTsk$. The entry $pndTsk_i[k]=(sns,vc,fnl)$ includes: (i) the index $sns$ of the most recent snapshot operation that $p_k \in \mathcal{P}$ has initiated and $p_i$ is aware of, (ii) the vector clock representation of $reg_k$ (\emph{i.e.,}\xspace just the timestamps of $reg_k$, cf. line~\ref{ln:vc}) and (iii) the final result $fnl$ of the snapshot operation (or $\bot$, in case it is still running). The $\mathrm{baseSnapshot}()$ function includes an outer loop part (lines~\ref{ln:prevSsnGetsRegSsnPlusOne2} and~\ref{ln:outerStop}), an inner loop part (lines~\ref{ln:letSprime} to~\ref{ln:waitUntilSNAPSHOTackReg2a}), and a result update part (lines~\ref{ln:prevEqReg} to~\ref{ln:vcUpdate}). The outer loop increments the snapshot index, $ssn$ (line~\ref{ln:prevSsnGetsRegSsnPlusOne2}), so that it can consider a new query attempt by the inner loop. The outer loop ends when (i) there are no more pending snapshot tasks that this call to $\mathrm{baseSnapshot}()$ needs to handle, or (ii) the only pending snapshot task for the current invocation of $\mathrm{baseSnapshot}()$ is the one of $p_i$ and $p_i$ has not observed at least $\delta$ concurrent writes. The inner loop broadcasts $\mathrm{SNAPSHOT}$ messages, which includes all the pending $(S\cap \Delta)$ that are relevant to this call to $\mathrm{baseSnapshot}()$ together with the local current value of $reg$ and the snapshot query index $ssn$. The inner loop ends when acknowledgments are received from a majority of processors and the received values are merged (line~\ref{ln:waitUntilSNAPSHOTackReg2a}). The results are updated by writing to an emulated safe shared register (line~\ref{ln:prevEqReg}) whenever $prev=reg$. In case the results do not allow $p_i$ to terminate its snapshot task (line~\ref{ln:vcUpdate}), Algorithm~\ref{alg:terminating} uses the query results for storing the timestamps in the field $vs$. This allows to balance a trade-off between snapshot operation latency and communication costs, as we explain next. \smallskip \indent \emph{The use of the input parameter $\delta$ for balancing the trade-off between snapshot operation latency and communication costs.~~} For the case of $\delta=0$, the set $\Delta$ (line~\ref{ln:exceedDelta}) includes all the nodes for which there is no stored result, \emph{i.e.,}\xspace $pndTsk[k].fnl=\bot$. Thus, no snapshot tasks are ever deferred, as in Delporte-Gallet \emph{et al.}\xspace~\cite[Algorithm~2]{DBLP:journals/tpds/Delporte-Gallet18}. The case of $\delta>0$ uses the fact that Algorithm~\ref{alg:terminating} samples the vector clock value of $reg_i$ and stores it in $pndTsk[i].vc$ (line~\ref{ln:vcUpdate}) once it had completed at least one iteration of the repeat-until loop (line~\ref{ln:waitUntilSNAPSHOTackReg2} and~\ref{ln:waitUntilSNAPSHOTackReg2a}). This way, we can be sure that the sampling of the vector clock is an event that occurred not before the start of $p_i$'s snapshot operation that has the index of $pndTsk[i].sns$. \smallskip \indent \emph{Many-jobs-stealing scheme for reduced blocking periods.~~} We note that $p_k$'s task is considered active as long as $pndTsk[k].fnl \neq \bot$. For helping all currently actives snapshot tasks, $p_i$ samples the set of currently pending task $(S_i\cap \Delta_i)$ (line~\ref{ln:letSprime}) before starting the inner repeat-until loop (lines~\ref{ln:letSprime} to~\ref{ln:waitUntilSNAPSHOTackReg2a}). Processor $p_i$ broadcasts from the client-side the $\mathrm{SNAPSHOT}$ message, which includes the most recent snapshot task information, to all processors. The reception of this $\mathrm{SNAPSHOT}$ message on the server-side (lines~\ref{ln:SNAPSHOTarrival} to~\ref{ln:SNAPSHOTarrivalEND}), updates the local information (line~\ref{ln:vcRemoteUpdate}) and prepares the response information (line~\ref{ln:prepareREsponse}) before sending the reply to the client-side (line~\ref{ln:SNAPSHOTackSend}). Note that if the receiver notices that it has the result of an ongoing snapshot task, it sends that result to the requesting processor (line~\ref{ln:sendSAVEwithA}). \smallskip \noindent \textbf{The $\mathsf{safeReg}()$ function and the $\mathrm{SAVE}$ message.~~} The $\mathsf{safeReg}()$ function considers a snapshot task that was initiated by processor $p_k \in \mathcal{P}$. This function is responsible for storing the result $r$ of this snapshot task in a safe register. It does so by broadcasting the client-side message $\mathsf{SAVE}$ to all processors in the system (line~\ref{ln:safeStoreSend}). Upon the arrival of the $\mathsf{SAVE}$ message to the server-side, the receiver stores the arriving information, as long as the arriving information is more recent than the local one. Then, the server-side replies with a $\mathrm{SAVEack}$ message to the client-side, who is waiting for a majority of such replies (line~\ref{ln:safeStoreSend}). \begin{figure*}[t!] \begin{center} \includegraphics[page=5,scale=0.5]{DrawingsCrop.pdf} \end{center} \begin{center} \includegraphics[page=6,scale=0.5]{DrawingsCrop.pdf} \end{center} \caption{\label{fig:terminatingExec}The upper drawing depicts an example of Algorithm~\ref{alg:terminating}'s execution for a case that is equivalent to the one depicted in the upper drawing of Figure~\ref{fig:9nonBlockExec}, i.e., only one snapshot operation. The lower drawing illustrates the case of concurrent invocations of snapshot operations by all nodes.} \end{figure*} Figure~\ref{fig:terminatingExec} depicts two examples of Algorithm~\ref{alg:terminating}'s execution. In the upper drawing, a write operation is followed by a snapshot operation. Note that fewer messages are considered when comparing to Figure~\ref{fig:9nonBlockExec}'s example. The lower drawing illustrates the case of concurrent invocations of snapshot operations by all nodes. Observe the potential improvement with respect to number of messages (in the upper drawing) and throughput (in the lower drawing) since Algorithm~\ref{alg:9disCongif} uses $\mathcal{O}(n^2)$ messages for each snapshot task and handles only one snapshot task at a time. \begin{algorithm*}[t!] \begin{\VCalgSize} \noindent \textbf{input:} $\delta$ a number of observed concurrent writes after which write operations block temporarily; \noindent \textbf{variables:} $ts := 0$ is $p_i$'s write operation index; $ssn,sns := 0$ are $p_i$'s snapshot operation indices; $reg[n]:= [\bot, \ldots, $ $ \bot]$ buffers all shared registers; $pndTsk[n] := [(0,\bot,\bot),\ldots,(0,\bot,\bot)]$ control variables of snapshot operations; each entry form is $(sns, vc, fnl)$, where $sns$ is an index, $vc$ is a vector clock that timestamps the snapshot operation $sns$, and $fnl$ is the operation's returned value; \noindent \textbf{macro} $\mathrm{VC}:=[ts_k]_{p_k\in\mathcal{P}}$ \textbf{where} $ts_k:=0$ \textbf{when} $reg[k]=\bot$ \textbf{otherwise} $reg[k]=(\bullet,ts_k)$\label{ln:vc}\; \noindent \textbf{macro} $\Delta := \{(k,pndTsk[k].sns,pndTsk[k].vc)|p_k \in \mathcal{P} \land pndTsk[k].fnl = \bot \land ((\delta=0\land pndTsk[k].sns>0)\lor (pndTsk[k].vc\neq \bot \land \delta \leq \sum_{\ell\in\{1,\ldots,n\}}\mathrm{VC}[\ell]-pndTsk[k].vc[\ell]))\}\cup \{(i,pndTsk[i].sns,pndTsk[i].vc):pndTsk[i].sns> 0 \land pndTsk[i].fnl= \bot\}$\label{ln:exceedDelta}; \noindent \textbf{macro} $\mathsf{safeReg}(A)$ \lRepeat{\emph{majority of $\mathrm{SAVEack}(\mathnormal{AJ}$$=$$\{(k,s)$$:$$(k,$$s,$$\bullet)$$\in$$A\})$ arrived}}{$\mathsf{broadcast}$ $\mathsf{SAVE}(A)$\label{ln:safeStoreSend}} \noindent \textbf{macro} $\mathrm{merge}(Rec)$ \label{ln:merge2} \{$ts\gets \max (\{ts, reg[i].ts\} \cup \{r[i].ts \mid r \in Rec\})$\label{ln:tsRegMaxTsRegTs2}; \lFor{$p_k \in \mathcal{P}$}{$reg[k]\gets \max (\{reg[k]\} \cup \{r[k] \mid r \in Rec\})$\label{ln:regGetsMaxRegCupMid2}\}} \textbf{do forever} \Begin{\label{ln:terminatingDoForever} \lForEach{$ssn'\neq ssn$}{\textbf{delete} $\mathrm{SNAPSHOTack}(-, ssn')$\label{ln:deleteSNAPSHOTack2}} $(ts,sns)\gets (\max \{ts, reg[i].ts\},\max \{sns, pndTsk[i].sns\})$\label{ln:tsGetsMaxTsRegTs2}\; \lFor{$k \in \{1,\ldots,n\}: pndTsk[k].vc \not \preceq \mathrm{VC}$, \textbf{where} line~\ref{ln:def3} defines the relation $\preceq$}{$pndTsk[k].vc \gets \bot$\label{ln:vcFix}} \lIf{$sns \neq pndTsk[i].sns$}{$pndTsk[i]\gets (sns,\bot,\bot)$\label{ln:snsNegRepSnap}} \lFor{$p_k \in \mathcal{P}:k\neq i$}{$\mathsf{send}~ \mathrm{GOSSIP}(reg[k],pndTsk[k].sns)~ \mathsf{to}~ p_k$\label{ln:sendGossip2}} \lIf{$writePending \neq \bot$}{$\{\mathrm{baseWrite}(writePending);writePending \gets \bot;\}$\label{ln:writePendingExceedDelta}} \lIf{$\Delta \neq \emptyset$}{$\mathrm{baseSnapshot}(\Delta)$\label{ln:letSexceedDeltaCall}} } \noindent \textbf{operation} $\mathsf{write}(v)$ \{\label{ln:tsEqtsPlusOne}$writePending \gets v$; \textbf{wait} \textbf{until} $(writePending = \bot); \Return()$;\} \noindent \textbf{operation} $\mathsf{snapshot}()$ \label{ln:operationSnapshot2}\Begin { $(sns, pndTsk[i]) \gets (sns + 1,(sns,\bot,\bot))$; \textbf{wait} \textbf{until} $(pndTsk[i].fnl \neq \bot);\label{ln:terminatingWaitUntilSnapshot} \Return(pndTsk[i].fnl)$\; } \noindent \textbf{function} $\mathrm{baseWrite}(v)$ \{$ts \gets ts + 1; reg[i] \gets (ts,v)$;\label{ln:tsIncrementWrite} \textbf{let} $lReg:=reg$; \lRepeat{$\mathrm{WRITEack}(\mathnormal{regJ} \succeq lReg)$ received from a majority\label{ln:waitUntilWRITEackReg2}}{$\mathsf{broadcast~} \mathrm{WRITE}(lReg)$\label{ln:broadcastWRITEreg2}; $\mathrm{merge}(Rec)$ \textbf{where} $Rec$ is the received $reg$ arrays\label{ln:mergeRecWrite2}\}} \noindent \textbf{function} $\mathrm{baseSnapshot}(S)$ \Begin{ \Repeat{$(S \cap \Delta)=\emptyset \lor ((S \cap \Delta) =(i, \bullet) \land pndTsk[i].sns> 0 \land pndTsk[i].fnl= \bot \land \delta \leq \sum_{\ell\in\{1,\ldots,n\}}(\mathrm{VC}[\ell]-pndTsk[i].vc[\ell]))$\label{ln:outerStop}}{ $ssn \gets ssn + 1$\label{ln:prevSsnGetsRegSsnPlusOne2}; \textbf{let} $prev:=reg$\label{ln:letSprime}; \Repeat{$(S \cap \Delta)=\emptyset$ \emph{or majority of} $(\mathrm{SNAPSHOTack}(\bullet, \mathnormal{ssnJ} =ssn)$ \emph{arrived)}\label{ln:waitUntilSNAPSHOTackReg2}}{ $\mathsf{broadcast} ~\mathrm{SNAPSHOT}((S \cap \Delta), reg, ssn)$\label{ln:ssnPlusOne2}\; } $\mathrm{merge}(Rec)$ \textbf{where} $Rec$ is the set of $reg$ arrays received at line~\ref{ln:ssnPlusOne2}\label{ln:waitUntilSNAPSHOTackReg2a}\; \lIf{$prev = reg \land (S \cap \Delta) \neq \emptyset$\label{ln:prevEqReg}}{$\mathsf{safeReg}(\{(k, pndTsk[k].sns, prev):(k, s, \bullet) \in S\})$} \lElseIf{$((i, \bullet) \in (S \cap \Delta)) \land (pndTsk[i].vc=\bot)$\label{ln:vcUpdateCond}}{$pndTsk[i].vc\gets \mathrm{VC}$\label{ln:vcUpdate}} } } \textbf{upon} message $\mathrm{SAVE}(\mathnormal{AJ})$ \textbf{arrival} \textbf{from} $p_j$\label{ln:safeStoreArrival} \Begin{ \lForEach{$(k, s, r) \in \mathnormal{AJ}:pndTsk[k].sns<s \lor pndTsk[k]=(s, \bullet,\bot)$}{$(pndTsk[k].sns,pndTsk[k].fnl)\gets (s,r)$\label{ln:safeStoreUpon}} \textbf{send} $\mathrm{SAVEack}(\{(k, s) :(k, s, \bullet) \in \mathnormal{AJ}\})$ \textbf{to} $p_j$\label{ln:safeStoreSendAck}\; } \textbf{upon} message $\mathrm{GOSSIP}(\mathnormal{regJ}, \mathnormal{snsJ})$ \textbf{arrival} \textbf{from} $p_j$ \label{ln:GOSSIParrival}\Begin{ $reg[i]\gets \max \{reg[i],\mathnormal{regJ}\};(ts, sns)\gets (\max \{ts, reg[i].ts\}, \max \{sns, \mathnormal{snsJ}\})$\label{ln:GOSSIPupdate2};} \textbf{upon} message $\mathrm{WRITE}(\mathnormal{regJ})$ \textbf{arrival} \textbf{from} $p_j$ \Begin{ \lFor{$p_k \in \mathcal{P}$}{$reg[k] \gets \max_{\prec_{sn}}(reg[k], \mathnormal{regJ}[k])$} \textbf{send} $\mathrm{WRITEack}(reg)$ \textbf{to} $p_j$\; } \textbf{upon} message $\mathrm{SNAPSHOT}(\mathnormal{SJ}, \mathnormal{regJ}, \mathnormal{ssnJ})$ \textbf{arrival} \textbf{from} $p_j$ \label{ln:SNAPSHOTarrival} \Begin{ \lFor{$p_k \in \mathcal{P}$}{$reg[k] \gets \max_{\prec_{sn}} (reg[k], \mathnormal{regJ}[k])$\label{ln:SNAPSHOTarrivalEND}} \lForEach{$(s,sn,vc) \in \mathnormal{SJ}: pndTsk[s].sns<sn\lor pndTsk[s]=(sn,\bot,\bot)$}{$pndTsk[s]\gets (sn,vc,\bot)$\label{ln:vcRemoteUpdate}} \textbf{let} $A:=\{(k,pndTsk[k].sns,pndTsk[k].fnl):(k,\bullet) \in \mathnormal{SJ} \land pndTsk[k].fnl \neq \bot \}$\label{ln:prepareREsponse}\; \textbf{send} $\mathrm{SNAPSHOTack}(reg, \mathnormal{ssnJ})$ \textbf{to} $p_j$\label{ln:SNAPSHOTackSend}; \lIf{$A\neq \emptyset$}{\textbf{send} $\mathsf{SAVE}(A)$ \textbf{to} $p_j$ \label{ln:sendSAVEwithA} (* piggyback messages *)}} \end{\VCalgSize} \caption{\label{alg:terminating}{Self-stabilizing always-terminating snapshot objects; code for $p_i$}} \end{algorithm*} \subsection{Correctness} \label{sec:cor2} We now prove the convergence (recovery), termination and linearization of Algorithm~\ref{alg:terminating}. \begin{definition}[Algorithm~\ref{alg:terminating}'s consistent system states and executions] \label{def:safeConfigTerminating} (i) Let $c$ be a system state in which $ts_i$ is greater than or equal to any $p_i$'s timestamp values in the variables and fields related to $ts$. We say that the $ts$' timestamps are consistent in $c$. (ii) Let $c$ be a system state in which $ssn_i$ is greater than or equal to any $p_i$'s snapshot sequence numbers in the variables and fields related to $ssn$. We say that the $ssn$'s snapshot sequence numbers are consistent in $c$. (iii) Let $c$ be a system state in which $sns_i$ is greater than or equal to any $p_i$'s snapshot operation index in the variables and fields related to $sns$. Moreover, $\forall p_i \in \mathcal{P}: sns_i = pndTsk_i[i].sns$ and $\forall p_i,p_j \in \mathcal{P}: pndTsk_j[i].sns \leq pndTsk_i[i].sns$. We say that the $sns$'s snapshot sequence numbers are consistent in $c$. (iv) Let $c$ be a system state in which $\forall p_i,p_k \in \mathcal{P}:pndTsk_i[k].vc\preceq \mathrm{VC}_i$ holds, where $\mathrm{VC}_i$ is the returned value from a macro defined in line~\ref{ln:vc} when executed by processor $p_i$. We say that the vector clock values are consistent in $c$. We say that system state $c$ is consistent if it is consistent with respect to invariants (i) to (iv). Let $R$ be an execution of Algorithm~\ref{alg:terminating} that all of its system states are consistent and $R'$ be a suffix of $R$. We say that execution $R'$ is consistent (with respect to $R$) if any message arriving in $R'$ was indeed sent in $R$ and any reply arriving in $R'$ has a matching request in $R$. \end{definition} \begin{theorem}[\textbf{Algorithm~\ref{alg:terminating}'s convergence}] \label{thm:terminatingAlgConvergence} % Let $R$ be a fair and unbounded execution of Algorithm~\ref{alg:disCongif}. Within $\mathcal{O}(1)$ asynchronous cycles in $R$, the system reaches a consistent state $c \in R$ (Definition~\ref{def:safeConfigTerminating}). Within $\mathcal{O}(1)$ asynchronous cycles after $c$, the system starts a consistent execution~$R'$. \end{theorem} \begin{proof} Note that Lemmas~\ref{thm:eventuallyAscendingSent} and~\ref{thm:sequenceNumberRecovery} imply invariants (i), and respectively, (ii) of Definition~\ref{def:safeConfigTerminating} also for the case of Algorithm~\ref{alg:terminating}, because they use the similar code lines for asserting these invariants. We now consider the proof of invariant (iii) of Definition~\ref{def:safeConfigTerminating}. Note that the variables and fields of $sns$ and the data structure $pndTsk$ in Algorithm~\ref{alg:terminating} follow the same patterns of information as the variables and fields of $ts$ and the data structure $reg$ in Algorithm~\ref{alg:disCongif}. Moreover, within one asynchronous cycle, every processor $p_i \in \mathcal{P}$ executes line~\ref{ln:snsNegRepSnap} at least once. Therefore, the proof of invariant (iii) can follow similar arguments to the ones appearing in the proof of Lemma~\ref{thm:eventuallyAscendingSent}. Specifically, $\forall p_i,p_j \in \mathcal{P}: pndTsk_j[i].sns \leq pndTsk_i[i].sns$ holds due to arguments that appear in the proof of Claim~\ref{thm:GOSSIPregJ} with respect to the variables and the fields of $ts$ and the structure $reg$. The proof of invariant (iv) is implied by the fact that within one asynchronous cycle, every processor $p_i \in \mathcal{P}$ executes line~\ref{ln:vcFix} at least once and the fact that $\mathrm{VC}_i$ is assigned to $pndTsk_i[k].vc$ in line~\ref{ln:vcUpdate}. Note that these are the only lines of code that assign values to $pndTsk_i[k].vc$ and that value of every entry in $\mathrm{VC}_i$ is not decreasing (Claim~\ref{thm:neverRemove}). By the definition of asynchronous cycles (Section~\ref{ss:asynchronousCycles}), within one asynchronous cycle, $R$ reaches a suffix $R'$, such that every received message during $R'$ was sent during $R$. By repeating the previous argument, it holds that within $\mathcal{O}(1)$ asynchronous cycles, $R$ reaches a suffix $R'$ in which for every received reply message, we have that its associated request message was sent during $R$. Thus, $R'$ is consistent. \end{proof} \smallskip The proof of Theorem~\ref{thm:livenessAll} considers both complete and not complete $\mathsf{snapshot}()$ operations. We say that a $\mathsf{snapshot}()$ operation is \emph{complete} if it starts due to a step $a_i$ in which $p_i$ calls the $\mathsf{snapshot}()$ operation (line~\ref{ln:operationSnapshot2}) and its operation index, $s$, is greater than any of $p_i$'s snapshot indices in the system state that appears immediately before $a_i$. Otherwise, was say that it is not complete. \begin{theorem}[\textbf{Algorithm~\ref{alg:terminating}'s termination and linearization}] % \label{thm:livenessAll} % Let $R$ be a consistent execution (as defined by Definition~\ref{def:safeConfigTerminating}) with respect to some execution of Algorithm~\ref{alg:terminating}. Suppose that there exists $p_i \in \mathcal{P}$, such that in $R$'s second system state (which immediately follows $R$'s first step that may include a call to the $\mathsf{snapshot}()$ operation in line~\ref{ln:operationSnapshot2}) it holds that $pndTsk_i[i]=(s,\bullet,\bot)$ and $s>0$. Within $\mathcal{O}(\delta)$ asynchronous cycles, the system reaches a state $c \in R$ in which $pndTsk_i[i]=(s,\bullet,x):x\neq\bot$. \end{theorem} \begin{proof} Lemmas~\ref{thm:livenessI},~\ref{thm:livenessII} and~\ref{thm:linearizationII} prove the theorem. These lemmas use the function $\mathcal{S}_i()$ that we define next. Whenever $p_i$'s program counter is outside of the function $\mathrm{baseSnapshot}()$, the $\mathcal{S}_i()$ function returns the value of $\Delta_i$. Otherwise, the function returns the value of $(S_i \cap \Delta_i)$. \begin{lemma}[\textbf{Algorithm~\ref{alg:terminating}'s termination --- part I}] \label{thm:livenessI} Let $R$ be a consistent execution (Definition~\ref{def:safeConfigTerminating}) with respect to some execution of Algorithm~\ref{alg:terminating}. Suppose that there exists $p_i \in \mathcal{P}$, such that in $R$'s second system state (which immediately follows $R$'s first step that may include a call to the $\mathsf{snapshot}()$ operation in line~\ref{ln:operationSnapshot2}) it holds that $pndTsk_i[i]=(s,\bullet,\bot)$ and $s>0$. Within $\mathcal{O}(\delta)$ asynchronous cycles, the system reaches a state $c \in R$ in which either: (i) for any non-failing processor $p_j \in \mathcal{P}$ it holds that $(i, \bullet) \in \mathcal{S}_j()$ (line~\ref{ln:exceedDelta}) and $pndTsk_j[i]=(s,\bullet,\bot)$, (ii) any majority $M \subseteq \mathcal{P}:|M|>|\mathcal{P}|/2$ include at least one $p_j \in M$, such that $pndTsk_j[i]=(s,\bullet,x):x\neq\bot$ or (iii) $pndTsk_i[i]=(s,\bullet,x):x\neq\bot$. \end{lemma} \begin{proof} Towards a proof in the way of contradiction, suppose that the lemma is false. That is, $R$ has a prefix $R'$ that includes $\mathcal{O}(\delta)$ asynchronous cycles, such that none of the lemma invariants hold during $R'$. The proof uses claims~\ref{thm:livenessInoStep} and~\ref{thm:livenessIcv} for demonstrating a contradiction with the above assumption in Claim~\ref{thm:livenessIatLeastDelta}. \begin{claim} \label{thm:livenessInoStep} $R'$ does not include a step in which processor $p_i$ evaluates the if-statement condition in line~\ref{ln:prevEqReg} to be true (or at least one of the lemma invariants holds). \end{claim} \begin{claimProof} Arguments (1), (2) and (3) show that during $a_i \in R'$ processor $p_i$ calls the function $\mathsf{safeReg}(\{(k, pndTsk[k].sns, prev):(k, s, \bullet) \in S\})$. Argument (4) shows that this implies that invariant (ii) holds. Thus, we reached a contradiction with the assumption in the lemma proof. \smallskip \noindent Argument (1): \emph{a call to $\mathrm{baseWrite}()$ ends within $\mathcal{O}(1)$ asynchronous cycles.~~} A call to $\mathrm{baseWrite}(v)$ starts with $p_i$ incrementing $ts_i$ and sorting it in $reg_i[i]$ (line~\ref{ln:tsIncrementWrite}) to a value that is unique (in the system state that immediately follows) with respect to $ts$'s variables and fields that are associated with $p_i$ (Theorem~\ref{thm:eventuallyAscendingSent}). We note that the repeat-until loop in line~\ref{ln:waitUntilWRITEackReg2} terminates due to the correctness of the quorum service (Corollary~\ref{thm:basicCorollary}) and the uniqueness of $ts_i$'s value. \smallskip \noindent Argument (2): \emph{the repeat-until loop in lines~\ref{ln:letSprime} to~\ref{ln:waitUntilSNAPSHOTackReg2a} ends within $\mathcal{O}(1)$ asynchronous cycles.~~} The call to $\mathrm{baseSnapshot}(S_i): (i, \bullet) \in S_i$ starts with $p_i$ incrementing $ssn_i$ (line~\ref{ln:prevSsnGetsRegSsnPlusOne2}) to a value that is unique (in the system state that immediately follows) with respect to $ssn$'s variables and fields that are associated with $p_i$ (Theorem~\ref{thm:eventuallyAscendingSent}). We note that the repeat-until loop in line~\ref{ln:waitUntilSNAPSHOTackReg2} terminates due to the correctness of the quorum service (Corollary~\ref{thm:basicCorollary}) and the uniqueness of $ssn_i$'s value (or the fact that $\mathcal{S}_i()=\emptyset$, which implies the lemma since then invariant (iii) holds). \smallskip Argument (3) consider a call that $p_i$ performs to $\mathrm{baseSnapshot}()$ with the parameter $S_i$. \noindent Argument (3): \emph{showing that within $\mathcal{O}(1)$ asynchronous cycles, $p_i \in \mathcal{P}$ executes $\mathrm{baseSnapshot}_i(S_i): (i, \bullet) \in S_i$ where it takes a step $a_i$ that includes the execution of the if-statement in line~\ref{ln:prevEqReg}.~~} \indent The assumption that invariant (iii) does not hold in $R'$ implies that $(i, \bullet) \in \mathcal{S}_i$ whenever processor $p_i$ takes a step that includes the execution of $\mathrm{baseSnapshot}_i(S_i)$ or line~\ref{ln:letSexceedDeltaCall}, which is part of Algorithm~\ref{alg:terminating}'s do forever loop. The latter occurs within $\mathcal{O}(1)$ asynchronous cycles (due to Argument (1) of this claim) and it includes the call to $\mathrm{baseSnapshot}_i()$ (line~\ref{ln:letSexceedDeltaCall}). Thus, the execution of line~\ref{ln:prevEqReg} is implied by the fact that the repeat-until loop in lines~\ref{ln:letSprime} to~\ref{ln:waitUntilSNAPSHOTackReg2a} eventually ends due to Argument (2) of this claim. \smallskip \noindent Argument (4): \emph{showing that invariant (ii) holds.~~} \indent The function $\mathsf{safeReg}_i()$, which $p_i$ calls in line~\ref{ln:safeStoreSend}, repeatedly sends to all processors the message $\mathrm{SAVE}$ until $p_i$ receives matching $\mathrm{SAVEack}$ messages from a majority of processors. Theorem~\ref{thm:terminatingAlgConvergence} and the assumption that $R'$ is consistent imply that every received $\mathrm{SAVEack}$ message can be associated with a matching $\mathrm{SAVE}$ message that was indeed sent during $R$. Thus, the rest of the proof shows that the existence of this majority of acknowledgments from processors $p_j \in \mathcal{P}$ implies that invariant (ii) holds (due to the intersection property of majority groups). According to lines~\ref{ln:safeStoreArrival} to~\ref{ln:safeStoreSendAck}, the arrival of the message $\mathrm{SAVE}$ to $p_j \in \mathcal{P}$ assures that $pndTsk_j[i].fnl \neq \bot$ before sending the message $\mathrm{SAVEack}$ back to $p_i$. This is due to Theorem~\ref{thm:terminatingAlgConvergence} and the assumption that $R$ is consistent. \end{claimProof} \begin{claim} \label{thm:livenessIcv} Within $\mathcal{O}(1)$ asynchronous cycles, the system reaches a state $c' \in R'$ in which for any non-faulty processor $p_j \in \mathcal{P}$ it holds that $pndTsk_j[i]=(s,y,\bullet):y\neq\bot$ (or at least one of the lemma invariants holds). \end{claim} \begin{claimProof} We first consider the case of $j=i$ before considering the case of $j \neq i$. \smallskip \textbf{The $\mathbf{j=i}$ case.~~} Within $\mathcal{O}(1)$ asynchronous cycles, $p_i$ calls $\mathrm{baseSnapshot}(S_i): (i, \bullet) \in S_i$ (line~\ref{ln:letSexceedDeltaCall}) due to Argument (3) in Claim~\ref{thm:livenessInoStep}. This, Argument (2) in Claim~\ref{thm:livenessInoStep} and Claim~\ref{thm:livenessInoStep} imply the execution of line~\ref{ln:vcUpdateCond} in every call for $\mathrm{baseSnapshot}(S_i)$. Hence, the claim for the case of $j=i$. \smallskip \textbf{The $\mathbf{j\neq i}$ case.~~} By the arguments of the case of $j=i$, within two asynchronous cycles, processor $p_i$ executes lines~\ref{ln:letSprime} and~\ref{ln:ssnPlusOne2} in which $p_i$ broadcasts the record $(i,pndTsk_i[i].sns$, $pndTsk_i[i].vc) \in S'$ to all processors in the system via $\mathrm{SNAPSHOT}(S',\bullet)$ messages. Note that $pndTsk_i[i].vc\neq \bot$ holds by the above case of $j=i$. Moreover, once processor $p_j$ receives this $\mathrm{SNAPSHOT}$ message, $pndTsk_j[i].vc\neq \bot$ holds (line~\ref{ln:vcRemoteUpdate}). The above arguments for the case of $j\neq i$ can be repeated as long as invariant (iii) does not hold. Thus, the arrival of such a $\mathrm{SNAPSHOT}$ message to all $p_j \in \mathcal{P}$ occurs within $\mathcal{O}(1)$ asynchronous cycles (or one of the lemma invariants holds). \end{claimProof} \begin{claim} \label{thm:livenessIatLeastDelta} Let $c' \in R'$ be a system state in which for any non-faulty processor $p_j \in \mathcal{P}$ it holds that $pndTsk_j[i]=(s,y,\bullet):y\neq\bot$ (as Claim~\ref{thm:livenessIcv} showed existence). Let $x$ be the (finite or infinite) number of iterations of Algorithm~\ref{alg:terminating}'s outer loop in $\mathrm{baseSnapshot}()$ function (lines~\ref{ln:prevSsnGetsRegSsnPlusOne2} and~\ref{ln:outerStop}) that processor $p_i$ takes between $c'$ and $c'' \in R'$, where $c''$ is a system state after which it takes at most $\mathcal{O}(\delta)$ asynchronous cycles until the system reach the state $c'''$ in which at least one of the lemma invariants holds. The value of $x$ is actually finite and $x\leq\delta$. \end{claim} \begin{claimProof} Arguments (1) to (3) show that $x\leq\delta$. Moreover, between $c''$ and $c'''$ there are $\mathcal{O}(\delta)$ asynchronous cycles. \smallskip \noindent Argument (1): \emph{as long as none of the proof invariants hold, whenever processor $p_i$ iterates over the outer loop in $\mathrm{baseSnapshot}()$ function (lines~\ref{ln:prevSsnGetsRegSsnPlusOne2} and~\ref{ln:outerStop}), $p_i$ takes a step in which it tests the if-statement condition at line~\ref{ln:prevEqReg} and that condition does \emph{not} hold.} \indent Within $\mathcal{O}{(1)}$ asynchronous cycle, $p_i$ takes a step that includes a call to $\mathrm{baseSnapshot}(S_i): (i, \bullet) \in S_i$ (line~\ref{ln:letSexceedDeltaCall}) at least once (Argument (3) in Claim~\ref{thm:livenessInoStep}). By Claim~\ref{thm:livenessInoStep}, that call includes the execution of line~\ref{ln:prevEqReg} in which the if-statement condition does not hold (because then Argument (4) in Claim~\ref{thm:livenessInoStep} implies that invariant (ii) holds). \smallskip \noindent Argument (2): \emph{suppose that there are at least $x$ consecutive and complete iterations of $p_i$'s outer loop in the $\mathrm{baseSnapshot}()$ function (lines~\ref{ln:prevSsnGetsRegSsnPlusOne2} and~\ref{ln:outerStop}) between $c'$ and $c''$ in which the if-statement condition at line~\ref{ln:prevEqReg} does not hold. There are at least $x$ write operations that run concurrently with the snapshot operation that has the index of $s$.} \indent The only way that the if-statement condition in line~\ref{ln:prevEqReg} does not hold in a repeated manner is by repeated changes of $ts$ field values in $reg_i$ during the different executions of lines~\ref{ln:prevSsnGetsRegSsnPlusOne2} to~\ref{ln:waitUntilSNAPSHOTackReg2a}. Such changes can only happen due to increments of $ts_j:p_j \in \mathcal{P}$ (line~\ref{ln:tsEqtsPlusOne}) at the start of $\mathsf{write}()$ operations. \smallskip \noindent Argument (3): \emph{there exists $x'\leq \delta$ for which $(i, \bullet) \in \mathcal{S}_i()$ (or at least one of the lemma invariants hold), where $x'$ is the number of consecutive and complete iterations of the outer loop in the $\mathrm{baseSnapshot}()$ function (lines~\ref{ln:prevSsnGetsRegSsnPlusOne2} and~\ref{ln:outerStop}) between $c'$ and $c''$ in which the if-statement condition at line~\ref{ln:prevEqReg} does not hold.} \indent Argument (2) implies that the number of iterations continues to grow (as long as none of the lemma invariants holds). The proof of Argument (2) and Claim~\ref{thm:neverRemove} imply that during every such iteration there are increments of at least one of the summation $\sum_{\ell\in\{1,\ldots,n\}}\mathrm{VC}_i[\ell]-pndTsk_i[i].vc[\ell]$ until that summation is at least $\delta$. Recall that $pndTsk[i].vc\neq\bot$ (Claim~\ref{thm:livenessIcv}) and $pndTsk_i[i].fnl = \bot$ (the assumption that none of the lemma invariants hold in $R'$). Thus, $(i, \bullet) \in \mathcal{S}_i()$ holds (line~\ref{ln:exceedDelta}, for the case of $k=i$). \smallskip \noindent Argument (4): \emph{suppose that $p_i$ has taken at least $x'$ iterations of the outer loop in $\mathrm{baseSnapshot}()$ function (lines~\ref{ln:prevSsnGetsRegSsnPlusOne2} and~\ref{ln:outerStop}) after system state $c'$ (which is defined in Claim~\ref{thm:livenessIcv}). After these $x'$ iterations, suppose that the system has reached a state $c''$ in which $(i, \bullet) \in \mathcal{S}_i()$, as in Argument (3). Within $\mathcal{O}(1)$ asynchronous cycles after $c''$, the system reaches the state $c'''$ in which $(i, \bullet) \in \mathcal{S}_j()$ holds for any non-failing processor $p_j \in \mathcal{P}$ (or at least one of the two other lemma invariants holds).} \indent Claim~\ref{thm:livenessIcv} states that in $c'$ it holds for any non-faulty processor $p_j \in \mathcal{P}$ that $pndTsk_j[i]=(s,y,\bullet):y\neq\bot$ (or at least one of the lemma invariants holds) and $y \preceq VC_j$ (otherwise, $R$ is not a consistent execution). Within $\mathcal{O}(1)$ asynchronous cycles after $c''$ (which Argument (3) defines), it holds that $reg_j$'s $ts$ fields are not smaller than the ones of $reg_i$'s $ts$ fields in $c''$. This is because in every iteration of the outer loop in $\mathrm{baseSnapshot}()$ function (lines~\ref{ln:prevSsnGetsRegSsnPlusOne2} and~\ref{ln:outerStop}), processor $p_i$ broadcasts $reg_i$ to all processors (line~\ref{ln:ssnPlusOne2}). These $\mathrm{SNAPSHOT}$ messages arrive within one asynchronous cycle to all non-faulty processors $p_j\in\mathcal{P}$ and upon their arrival $p_j$ updates $reg_j$ (lines~\ref{ln:SNAPSHOTarrival} to~\ref{ln:SNAPSHOTarrivalEND}). The rest of the proof shows that $(i, \bullet) \in \mathcal{S}_j()$ holds (line~\ref{ln:exceedDelta} for the case of $k=i$); the reasons for that are similar to the ones that appear in the proof of Argument (3). \end{claimProof} \noindent This completes the proof of the lemma. \end{proof} \smallskip We note that invariants (i) and (i) of lemmas~\ref{thm:livenessI} and~\ref{thm:livenessII} match and invariant (iii) of Lemma~\ref{thm:livenessI} implies that the theorem holds. \begin{lemma}[\textbf{Algorithm~\ref{alg:terminating}'s termination --- part II}] % \label{thm:livenessII} % Let $R$ be a consistent execution of Algorithm~\ref{alg:terminating} (Definition~\ref{def:safeConfigTerminating}) and $p_i \in \mathcal{P}$. Moreover, suppose that either (i) in any system state of $R$, it holds that $pndTsk_i[i]=(s,\bullet,\bot)$, $s>0$ as well as for any non-failing processor $p_j \in \mathcal{P}$ it holds that $(i,\bullet)\in \mathcal{S}_j()$ (line~\ref{ln:exceedDelta}) and $pndTsk_j[i]=(s,\bullet,\bot)$, or (ii) in any system state of $R$, it holds that $pndTsk_i[i]=(s,\bullet,\bot)$, $s>0$ as well as any majority $M \subseteq \mathcal{P}:|M|>|\mathcal{P}|/2$ include at least one $p_j \in M$, such that $pndTsk_j[i]=(s,\bullet,x):x\neq\bot$. Within $\mathcal{O}(1)$ asynchronous cycles, the system reaches a state $c \in R$ in which $pndTsk_i[i]=(s,\bullet,x):x\neq\bot$. \end{lemma} \begin{proof} The proof is implied by Claims~\ref{thm:livenessIImajority} and~\ref{thm:livenessIIexceedDelta}. \begin{claim} % \label{thm:livenessIImajority} % Suppose that $pndTsk_i[i].sns> 0$ holds in any system state of $R$ and that for any majority $M \subseteq \mathcal{P}:|M|>|\mathcal{P}|/2$ includes at least one $p_j \in M$, such that $pndTsk_j[i]=(s,\bullet,x):x\neq\bot$. Within $\mathcal{O}(1)$ asynchronous cycles, the system reaches a state $c \in R$ in which $pndTsk_i[i]=(s,\bullet,x):x\neq\bot$. \end{claim} \begin{claimProof} Towards a proof in the way of contradiction, suppose that the lemma is false. That is, $R$ has a prefix $R'$ that includes at least $\mathcal{O}(1)$ asynchronous cycles, such that $pndTsk_i[i]=(s,\bullet,x):x=\bot$ holds in any system state in $R'$. Arguments (1) to (2) show the needed contradiction. Recall that by Argument (3) in Claim~\ref{thm:livenessInoStep} it holds that every iteration of the do forever loop during $R'$ includes a call to $\mathrm{baseSnapshot}(S_i):(i, \bullet) \in S_i$ (line~\ref{ln:letSexceedDeltaCall}). \smallskip \noindent Argument (1): \emph{within $\mathcal{O}(1)$ asynchronous cycles, a majority of nodes acknowledge the message $\mathrm{SNAPSHOT}(\bullet,reg_i, ssn_i)$, such that for at least one $\mathrm{SNAPSHOTack}(\mathnormal{AJ} ,\bullet,\mathnormal{ssnJ})$ acknowledgment, it holds that $\mathnormal{ssnJ} =ssn_i$, $(s, pndTsk_i[s].sns,\bullet, x) \in \mathnormal{AJ}$ and $\bot \neq x = pndTsk_j[s].fnl$.~~} \indent We show that within $\mathcal{O}(1)$ asynchronous cycles, for at least one $\mathrm{SNAPSHOTack}(\mathnormal{AJ} ,\bullet,\mathnormal{ssnJ})$ message, say the one from $p_j$, it holds that $\mathnormal{ssnJ} =ssn_i$, $(s, pndTsk_i[s].sns,\bullet, x) \in \mathnormal{AJ}$ and $\bot \neq x = pndTsk_j[s].fnl$. This is followed from the fact that line~\ref{ln:ssnPlusOne2} broadcasts repeatedly the $\mathrm{SNAPSHOT}(\bullet, ssn_i)$ message until at least a majority receives it and acknowledges it. By Argument (2) in Claim~\ref{thm:livenessInoStep}, the repeat-until loop in lines~\ref{ln:letSprime} to~\ref{ln:waitUntilSNAPSHOTackReg2a} ends within $\mathcal{O}(1)$ asynchronous cycles. Moreover, by the proof of Argument (2) in Claim~\ref{thm:livenessInoStep}, the received acknowledgments indeed refer to these messages, and at least one of these acknowledgments includes $(s, pndTsk_i[s].sns,\bullet, x) \in \mathnormal{AJ}:\bot \neq x = pndTsk_j[s].fnl$ due to the claim assumption about $M$. \smallskip \noindent Argument (2): \emph{within $\mathcal{O}(1)$ asynchronous cycles, $pndTsk_i[i].fnl\neq \bot$ holds.~~} \indent By the proof of Argument (1), a majority $M$ of processors successfully acknowledge the message $\mathrm{SNAPSHOT}$ (line~\ref{ln:SNAPSHOTackSend}). By the claim assumption and the intersection property of majority sets, for at least one of the acknowledging node, say, $p_k$, it holds that $pndTsk_k[i]=(s,\bullet,x):x\neq\bot$. Since line~\ref{ln:SNAPSHOTackSend} piggyback the $\mathrm{SNAPSHOTack}(reg, \mathnormal{ssnJ})$ and $\mathsf{SAVE}(A)$ messages, the message $\mathsf{SAVE}(A)$ successfully arrives from $p_k$ to $p_i$. The proof is done by the fact that once the message $\mathsf{SAVE}$ arrives to $p_i$, line~\ref{ln:safeStoreUpon} updates $pndTsk_i[i]=(s,\bullet,x):x\neq\bot$. \end{claimProof} \begin{claim} % \label{thm:livenessIIexceedDelta} % Suppose that, during the first $\mathcal{O}(1)$ asynchronous cycles of $R$, for any non-failing processor $p_j \in \mathcal{P}$ it holds that $(i, \bullet) \in \mathcal{S}_j()$ (line~\ref{ln:exceedDelta}) and $pndTsk_j[i]=(s,\bullet,\bot)$. Within $\mathcal{O}(1)$ asynchronous cycles, the system reaches a state $c \in R$ in which $pndTsk_i[i]=(s,\bullet,x):x\neq\bot$. \end{claim} \begin{claimProof} The proof is by a sequence of statements, \emph{i.e.,}\xspace arguments (1) to (3). \smallskip \noindent Argument (1): \emph{within $\mathcal{O}(1)$ asynchronous cycles, there are no active write operations.~~} \indent Note that during $R$, any processor that executes the $\mathsf{write}()$ function, returns from this call to $\mathsf{write}()$ within $\mathcal{O}(1)$ asynchronous cycles (Argument (1) in Claim~\ref{thm:livenessInoStep}). Thus, $p_i$ calls $\mathrm{baseSnapshot}_i(S_i)$ with the parameter $S_i$, such that $(i, \bullet) \in S_i$ follows (Argument (3) in Claim~\ref{thm:livenessInoStep}). By this claim assumption that $\forall p_j \in \mathcal{P} : (i, \bullet) \in \mathcal{S}_j()$, it holds that the repeat-until loop (lines~\ref{ln:prevSsnGetsRegSsnPlusOne2} to~\ref{ln:outerStop}) does not end during the first $\mathcal{O}(1)$ asynchronous cycles of $R$ (due to the fact that the end condition cannot hold). By the same assumptions and similar arguments as above, the same holds for any $ p_j \in \mathcal{P}$ within $\mathcal{O}(1)$ asynchronous cycles. Thus, within $\mathcal{O}(1)$ asynchronous cycles the system execution reaches a suffix, $R'$, during which there are no active write operations. This completes the proof of Argument (1.) \smallskip \noindent The rest of the proof shows that $p_i$'s snapshot operation terminates within the first $\mathcal{O}(1)$ asynchronous cycles of $R'$. Towards a proof in the way of contradiction, suppose that the statement is false. That is, let $R''$ be a prefix of $R'$ (that includes at least $\mathcal{O}(1)$ asynchronous cycles), in which $p_i$'s snapshot operation does not terminate. In other words, in every system state of $R''$, it holds that $pndTsk_i[i]=(s,\bullet,\bot)$. By Argument (2) of Claim~\ref{thm:livenessInoStep}, the repeat-until loop in lines~\ref{ln:ssnPlusOne2} to~\ref{ln:waitUntilSNAPSHOTackReg2a} terminates. By line~\ref{ln:waitUntilSNAPSHOTackReg2}, this happens only when (i) $(S \cap \Delta) \neq \emptyset$ or (ii) majority of matching $\mathrm{SNAPSHOTack}$ messages arrived. The former case implies that the proof is done, because the only way in which $(i,\bullet)$ leaves the set $(S \cap \Delta)$ is by having $pndTsk_i[i]=(s,\bullet,x):x\neq\bot$ (due to the execution of line~\ref{ln:safeStoreUpon}). For the latter case, we note that Argument (1) implies that the if-statement condition in line~\ref{ln:prevEqReg} holds. We complete the proof with Argument (2), which show the needed contradiction. \smallskip \noindent Argument (2): \emph{a call to $\mathsf{safeReg}_i()$ during $R''$ implies the claim.~~} \indent Suppose that the if-statement condition in line~\ref{ln:prevEqReg} holds after the execution of lines~\ref{ln:ssnPlusOne2} to~\ref{ln:waitUntilSNAPSHOTackReg2a}. The call to $\mathsf{safeReg}_i(\{(\bullet,r_i):r_i\neq \bot\})$ causes $p_i$ to send the message $\mathsf{SAVE}(\{(\bullet,r_i):r_i\neq \bot\})$ to itself and the reception of this message assigns $r_i\neq \bot$ to $pndTsk_i[i].fnl$ (line~\ref{ln:safeStoreUpon}). (Since there is no need to actually send this message, this is done within an atomic step.) \end{claimProof} \noindent This completes the proof of the lemma. \end{proof} \begin{lemma}[\textbf{Algorithm~\ref{alg:terminating}'s linearization}] % \label{thm:linearizationII} % Algorithm~\ref{alg:terminating} respects the sequential specification of the snapshot object. \end{lemma} \begin{proof} We note that the $\mathrm{baseWrite}()$ functions in Algorithms~\ref{alg:9disCongif} and~\ref{alg:terminating} are identical. Moreover, Algorithm~\ref{alg:9disCongif}'s lines~\ref{ln:prevRegSsnPlusOne} to~\ref{ln:9waitUntilSNAPSHOTack} are similar to Algorithm~\ref{alg:terminating}'s lines~\ref{ln:prevSsnGetsRegSsnPlusOne2} to~\ref{ln:waitUntilSNAPSHOTackReg2a}, but differ in the following manner: (i) the dissemination of the operation tasks is done outside of Algorithm~\ref{alg:9disCongif}'s lines~\ref{ln:prevRegSsnPlusOne} to~\ref{ln:9waitUntilSNAPSHOTack} but inside of Algorithm~\ref{alg:terminating}'s lines~\ref{ln:prevSsnGetsRegSsnPlusOne2}, and (ii) Algorithm~\ref{alg:9disCongif} considers one snapshot operation at a time whereas Algorithm~\ref{alg:terminating} considers many snapshot operations. The proof is based on observing that the definition of linearizability (Section~\ref{sec:snapshotTask}) allows concurrent snapshot operations to have the same result (as long as they each individually respect all the other constraints that appear in the definition of linearizability). Moreover, by the same definition, the linearizability property does not depend on the way in which the snapshot tasks (and their results) are disseminated. (Indeed, the linearizability proof of Delporte-Gallet \emph{et al.}\xspace~\cite[Lemma~7]{DBLP:journals/tpds/Delporte-Gallet18} does not consider the way in which the snapshot tasks, and their results, are disseminated when selecting linearization points. These linearization points are selected according to some partition, defined in~\cite[Lemma~7]{DBLP:journals/tpds/Delporte-Gallet18}. The proof there explicitly allows the same partition to include more than one snapshot result.) \end{proof} \noindent This completes the proof of the theorem. \end{proof} \section{Bounded Variations on Algorithms~\ref{alg:disCongif} and~\ref{alg:terminating}} \label{sec:bounded} In this section, we discuss how we can obtain bounded variations of our two unbounded self-stabilization algorithms. Dolev \emph{et al.}\xspace~\cite[Section 10]{DBLP:journals/corr/abs-1806-03498} present a solution to a similar transformation: They show how to take a self-stabilizing atomic MWMR register algorithm for message passing systems that uses unbounded operation indices and transform it to an algorithm that uses bounded indices. We review the techniques that Dolev \emph{et al.}\xspace use and explain how a similar transformation can also be used for Algorithms~\ref{alg:disCongif} and~\ref{alg:terminating} with respect to their different operation indices. The procedure by Dolev \emph{et al.}\xspace~\cite[Section 10]{DBLP:journals/corr/abs-1806-03498} considers operation indices, which they call tags, whereas the proposed algorithms refer to operation indices as (i) $ts$ values in the variables and message fields, as well as (ii) $ssn$ and $sns$ values in the variables and message fields. That is, Dolev \emph{et al.}\xspace consider just one type of operation index whereas we consider several types. For sack of simple presentation, when describing next the procedure by Dolev \emph{et al.}\xspace, we refer to the case of many types of operation indices. \begin{enumerate} \item\label{ln:stop} Once node $p_i \in \mathcal{P}$ stores an operation index that is at least $\mathrm{MAXINT}$, node $p_i$ disables the invocation of all operations (of all types) while allowing the completion of the existing ones (until all nodes agree on the highest index for each type of operation, cf. item~\ref{ln:restart}), where $\mathrm{MAXINT} \in \mathbb{Z}^+$ is a very large constant, say, $\mathrm{MAXINT} = 2^{64}-1$. \item\label{ln:restart} While the invocation of new operations (of all types) is disabled (by item~\ref{ln:stop}), the gossip procedure keeps on propagating the maximal operation indices (and merge the arriving information with the local one). Eventually, all nodes share the same operation indices (for all types). At that point in time, the procedure for dealing with integer overflow events uses a consensus-based global reset procedure for replacing, per operation type, the highest operation index with its initial value $0$, while keeping the values of all shared registers unchanged. \end{enumerate} \noindent \textbf{Self-stabilizing global reset procedure.~~} The implementation of the self-stabilizing procedure for global reset can be based on existing mechanisms, such as the one by Awerbuch \emph{et al.}\xspace~\cite{DBLP:conf/wdag/AwerbuchPVD94}. We note that the system settings of Awerbuch \emph{et al.}\xspace~\cite{DBLP:conf/wdag/AwerbuchPVD94} assume execution fairness. This assumption is allowed by our system settings (Section~\ref{sec:seldomFair}). This is because we assume that reaching $\mathrm{MAXINT}$ can only occur due to a transient fault. Thus, execution fairness, which implies all nodes are eventually alive, is seldom required (only for recovering from transient faults). \smallskip \noindent \textbf{An extension: quorum reconfiguration.~~} We consider an extension of our system settings that include quorum reconfiguration. The advantage here is two folded: (i) systems that can reconfigure the set $\mathcal{P}$ are more durable since they can replace failing nodes with new ones, and (ii) they allow us to relax the assumption that failing node eventually restart (Section~\ref{sec:sys}). As an alternative approach for implementing the self-stabilizing procedure for global reset, we propose to base the reset procedure on a self-stabilizing consensus algorithm, \emph{e.g.,}\xspace~\cite{DBLP:conf/netys/BlanchardDBD14}, and quorum reconfiguration~\cite{DBLP:conf/netys/DolevGMS17}. Note that the system settings of ~\cite{DBLP:conf/netys/BlanchardDBD14,DBLP:conf/netys/DolevGMS17} assume the availability of failure detector mechanisms, and the relevant liveness conditions for implementing these mechanisms. Moreover, quorum reconfiguration requires the use of state transfer procedure after every reconfiguration. In the context of the proposed solutions, the array $reg$ should be adjusted by adding new entries for every joining node and removing entries associated with nodes that are no longer part of the quorum configuration. The reconfiguration-based reset procedure is similar to the above procedure described in items~\ref{ln:stop} and~\ref{ln:restart}. The only difference is that between these two steps, a quorum reconfiguration needs to be imposed to assure that all nodes in $\mathcal{P}$ are up and connected. \section{Conclusions} \label{sec:disc} We showed how to transform the two non-self-stabilizing algorithms of Delporte-Gallet \emph{et al.}\xspace~\cite{DBLP:journals/tpds/Delporte-Gallet18} into ones that can recover after the occurrence of transient faults. This requires some non-trivial considerations that are imperative for self-stabilizing systems, such as the explicit use of bounded memory and the reoccurring clean-up of stale information. Interestingly, these considerations are not restrictive for the case of Delporte-Gallet \emph{et al.}\xspace~\cite{DBLP:journals/tpds/Delporte-Gallet18}. For our self-stabilizing atomic snapshot algorithm that always terminates, we chose to use safe registers for storing the results of recent snapshot operations, rather than a mechanism for reliable broadcast, which is more expensive to implement. Moreover, instead of dealing with one snapshot operation at a time, we deal with several at a time. In addition, we consider a tunable input parameter, $\delta$, for allowing the system to balance a trade-off between the latency of snapshot operations and communications costs, which range from $\mathcal{O}(n)$ to $\mathcal{O}(n^2)$ messages per snapshot operation. One future direction emanating from this work is to consider the $\mathcal{O}(n)$ gap in the number of messages when designing future applications. For example, one might prefer the use of repeated snapshots (using the proposed solution) over a replicated state machine, which always costs $\mathcal{O}(n^2)$ messages per state transition. Another future direction is to consider the techniques presented here for providing self-stabilizing versions of more advanced snapshot algorithms, such as the one by Imbs \emph{et al.}\xspace~\cite{DBLP:conf/icdcn/ImbsMPR18}. \bibliographystyle{plain}
{'timestamp': '2019-06-18T02:02:51', 'yymm': '1906', 'arxiv_id': '1906.06420', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06420'}
arxiv
\section{Introduction} Natural Language Processing (NLP) in biomedical domain is an essential and challenging task. With the availability of the data in electronic form it is possible to apply Artificial intelligence (AI), machine learning and deep learning technologies to build data driven automated tools. These automated tools will be helpful in the field of medical science. An ACL-BioNLP 2019 shared task, namely the MEDIQA challenge aims to attract further research efforts in NLI, RQE and their application in QA in medical domain. The motivation of this shared task is in a need to develop relevant methods, techniques, and gold standard data for inference and recognizing question entailment in medical domain and their application to improve domain specific Information Retrieval (IR) and Question Answering (QA) systems. The MEDIQA has defined several tasks related to \textit{Natural Language Inference, Question Entailment and Question Answering} in medical domain. We participated in all the three tasks defined in this shared task. We offer multiple systems for each the tasks. The workshop comprises of three tasks namely \textit{viz. i. Natural Language Inference (NLI): This task involves in identifying three inference relations between two sentences: i.e. Entailment, Neutral and Contradiction \cite{romanov-shivade-2018-lessons} ii. Recognizing Question Entailment (RQE): This task focuses on identifying entailment relation between two questions in the context of QA. The definition of question entailment is as follows: "a question A entails a question B if every answer to B is also a complete and/or partial answer to A" \cite{abacha2019question} and iii. Question Answering (QA): The goal of this task is to filter and improve the ranking of automatically retrieved answers. The existing medical QA system namely \textit{CHiQA} is applied to generate the input ranks. \cite{harabagiu-hickl-2006-methods,abacha2017overview,abacha2019question}}. We participated in all the three tasks defined above and submitted the results. Our proposed systems produce encouraging results. \section{Proposed Method} We propose multiple runs for each of the three tasks. The following subsections will discuss the methods applied to tackle each of these tasks. \subsection{Natural Language Inference} In the task 1 the system has to decide the entailment relationship between a pair of texts i.e. either they are \textit{Entailment, Contradiction or Neutral}. The input to this task are sentence pairs and as output we wish to get the entailment relation between those two pieces of texts. We propose five runs for this task. The following set of hyper parameters are applied for the following runs. \textbf{Batch Size} = 32, \textbf{Learning Rate} = 2e-5, \textbf{Maximum Sequence Length} = 128, \textbf{number of epochs} = 10. The following points will discuss the approaches (i.e. runs). \\ \textit{\textbf{Run 1:}} Our first proposed method is based on a BioBERT \cite{lee2019biobert} model, i.e. a Bidirectional Encoder Representation from Transformer model pre-trained on biological data (both on Pub Med abstracts and PMC full-text articles). After getting the vector corresponding to the special classification token ([CLS]) from final hidden layer of this mode, we use it for classification. We use 2 dense (feed forward) layers and a softmax activation function at the end. Only the feed forward part is trained end to end for 10 epochs after getting output vector from BioBERT. In this method no fine tuning is used. This method yields an accuracy of 60.8\%.\\ \textit{\textbf{Run 2:}} The second approach is based on the Bidirectional Encoder Representation from Transformer (BERT) model (bert-base-uncased) \cite{devlin-etal-2019-bert}. We make use of this to get the embedding of the inputs to this system. Instead of using 2 feed forward layers at the end, we choose to use only 1 feed forward layer. The full model is then trained in an end to end manner. All of the parameters of BERT and the last feed forward layer are fine-tuned jointly for 10 epochs to maximize the log-probability of the correct label (Entailment, Neutral or Contradiction). This model produces an accuracy of 71.7\%. \\ \textit{\textbf{Run 3:}} We use a BioBERT model for this system. This BioBERT model is pre-trained on PubMed abstracts only. We apply only one feed forward layer at the end. The full model is fine tuned as described for the system in run 2. This method gives output with an accuracy of 77.1\%.\\ \textit{\textbf{Run 4:}} The system proposed in this run is same as the model of Run 3. The differences between them are as follows: \begin{itemize} \item The BioBERT model we used is a pre-trained model on both the PubMed abstracts and PMC full-text articles instead of only PubMed abstracts as in case of in run 3. \item Here, we combine the full dataset of MedNLI (14049 sentence pairs) for training. Whereas in the previous run we made use only 11232 sentence pairs for training. \end{itemize} Following these changes in run 4, the accuracy increases from 77.1\% in run 3 to 80.3\% in run 4.\\ \textit{\textbf{Run 5:}} This model is the combination of three BioBERT models. Two of them are pre-trained on both the PubMed abstracts and PMC full text articles and the third one is pre-trained only on PubMed abstracts. We fine tune each of the models following the fine tuning process of run 4. We ensemble their predictions by voting each of them for a sentence pair. The label which gets the most vote is selected for final prediction. The accuracy increases to 81.8\%.\\ \subsection{Recognizing Question Entailment (RQE)} Recognizing Question Entailment is an important task. The objective of this task is to identify entailment between the two questions in the context of Question-Answering(QA). We use the following definition of question entailment: “a question A entails a question B if every answer to B is also a complete or partial answer to A”. We make use of the dataset provided by the task organizers'. We submit five runs which are broadly based on two approaches. The approaches are as follows: \begin{itemize} \item One is based on Siamese architecture \cite{mueller2016siamese}. This Siamese is based on the recurrent architectures for learning sentence similarity (Mueller et al., 2016). Here we feed the two questions (inputs) to two Bidirectional Long Short Term Memory (Bi-LSTM) \cite{hochreiter1997long}, respectively. Both of their weights are initialized to the same. After obtaining the last hidden representations from both of these Bi-LSTMs, we concatenate them. This vector represents our input sentence pair. We feed this vector to a feed forward neural network layer. At the end, there is a softmax layer to perform a 2-class classification (to Yes/No). \item In another one, we train (fine-tuned) a BioBERT model as described in the NLI task. We used the BioBERT model to perform a 3-way classification of a sentence pair into entailment, neutral or contradiction. The same approach is used here in RQE to classify a pair of questions into Yes or No. The hyper-parameters used in fine-tuning the BioBERT model are same as of task 1 (NLI) except here the training iteration is (i.e. epoch) 5. This is done so because the loss is decreasing rapidly between two training epochs, indicating over fitting on the train set. \end{itemize} Our proposed approaches are based on these methods with slight variations. The following points will show them.\\ \textit{\textbf{Run 1:}} Each question pair is having two questions (namely chq and faq). We assume the first question as the premise and the second one as the hypothesis. We extract these two questions from the training set. We obtain the vector representation of each word using Gensim Word2Vec \cite{rehurek_lrec}. The vector size is 50. Then vector representations of the words for both the question are fed to Siamese Network of Bidirectional LSTMs. We train the model with 50 epoch and achieve 53.2\% accuracy in test set.\\ \textit{\textbf{Run 2:}} In this method we make use of the BioBERT model. The model is pre-trained on PubMed abstracts and PMC full text articles. This task is essentially a sentence pair classification task. For each sentence pair we obtain a vector corresponding to ‘([CLS])’ token at the last layer. The vector is subsequently fed into two dense layers followed by a final layer having softmax activation function layer. No fine-tuning is used here. We obtain an accuracy of 50.6\%. \\ \textit{\textbf{Run 3:}} Here also we use BioBERT, but it is pre-trained on PubMed abstracts only. We fine tune the model on the RQE training set consisting of 8588 pairs. A feed forward layer with final layer with softmax activation is used at the end for 2-way classification. We obtain an accuracy of 48.1\%.\\ \textit{\textbf{Run 4:}} Instead of training word vector representation from scratch using Gensim Word2Vec, as in run 1, we obtain the vector representations of words from a trained Google News corpus (3 billion running words) word vector model (3 million 300-dimension English word vectors). The architecture is same as what is there in the run 1. We obtain an accuracy of 50.2\%.\\ \textit{\textbf{Run 5:}} We use a BioBERT model pre-trained on both PubMed abstracts and PMC full text articles. Then we fine tune on the RQE train set. Everything else is same as in run 3. The accuracy decreases to 48.9\%.\\ \subsection{Question Answering (QA)} The objective of this Question Answering task is to filter and improve the ranking of automatically retrieved answers. The input ranks are generated by the existing medical QA system \textit{CHiQA}. We use BERT to predict the reference score between pairs and BM25 \cite{robertson2009probabilistic} to rank between them. First of all, the BERT is used as a sentence pair classifier model. The first token of every sequence is always the special classification token ([CLS]). The final hidden state (i.e., output of Transformer) corresponding to this token is used as the aggregate sequence representation for classification tasks. This final hidden state is a 768 dimensional vector (for bert-base) representing the input sentence pair. This vector is fed subsequently into one or more feed-forward layers with softmax activation function layer. We fine tune the whole system for 10 epochs to predict the reference score of test dataset. The predicted values of these reference score are subsequently used in the BM25 model. \textit{All the hyper parameters setting are same as in Task-1 except here a batch size of 28 is used because the maximum length of sequence is increased from 128 to 256.} It is to be noted that, it is too much memory consuming to train a BERT model with a batch size of 32 and a maximum sequence length of 256. We propose four runs to combat this problem.\\ \textit{\textbf{Pre-processing:}} The training dataset is divided into two files (QA-TrainingSet1-LiveQAMed and TrainingSet2-Alexa) both are containing 104 questions. They had 8.80 and 8.34 answers for every question on average, respectively. For a question with \textit{N} answers are converted to \textit{N} pairs with each pair containing the question, one of the answers, and their reference score.\\ \textit{\textbf{Run 1:}} All reference scores from training dataset are replaced by 1 if it is 3 or 4, and with 0 otherwise. The range of reference score (as given) is between 1 to 4 in dataset. Here we fine tune a BERT model (bert-base-uncased) with a feed forward layer at the end for 10 epochs to classify a sentence pair into 2 labels (0 or 1). The trained model is then used to predict reference score of test set. From the predicted result obtained from BERT, BM25 score for every question and their corresponding answers are calculated. All answers for a question whose predicted labels are 1 ('YES') are sorted in decreasing order of their BM25 scores. After that all the 'YES' labels are retrieved, and the same procedure is applied for all answers for the same question whose predicted label is 0 (NO). The obtained accuracy is 57.3\%.\\ \textit{\textbf{Run 2:}} All reference scores are kept intact, i.e. between 1 to 4. Here we use the BERT model (bert-base-uncased) and fine tune it on train set with a feed forward net at the end. From the predicted result obtained from BERT, pairs whose reference score is 4 or 3 are marked as 'YES' and whose reference score are 2 or 1 are marked as 'NO'. BM25 score for every question and their corresponding answer is calculated. All answers for a question whose predicted label is 4 are sorted by decreasing order of their BM25 score. Same procedure is applied for all answers for the same question whose predicted label is 3,2 and 1, respectively. We obtain an accuracy of 65.1\% in this run.\\ \textit{\textbf{Run 3:}} Here the validation dataset is also included to the training set. We merged them. Instead of using a BERT model here we use BioBERT model which is pre-trained on PubMed abstracts and PMC full text articles. We fine tune this model as explained in run 1. The rest of the procedures are same as in run 2. The accuracy increases to 67.8\%.\\ \textit{\textbf{Run 4:}} This method is an ensemble of 5 BioBERT (PubMed-PMC) models and fine tuned on the train dataset. Each of the models is then evaluated on the validation set (which is included in training set of Run 3). It is seen that one of those models performs well than the ensemble of 5 models. The model is then used to predict reference score of the test set. The rest of the procedures is same as what is there in the Run 3. The accuracy is 71.7\% for this run.\\ \section{Experiments, Results and Discussions} We submitted system results (runs) for all the three tasks. In all these tasks, we make use of the dataset released as a part of this shared task. In the following we discuss the dataset, evaluation results and the necessary analysis of the results obtained. \\ \textit{\textbf{Data:}} In the NLI task, the training and test instances are having 14049 and 405 number of sentence pairs, respectively. In task 2 (i.e. RQE), the training set is having 8588 number of pairs, out of which 4655 and 3933 pairs are having \textit{True} and \textit{False} class, respectively. The validation and test set are having 302 (true: 129 and false: 173) and 230 (true: 115 and false: 115) number of instances. In the QA task, training sets are provided from two domains \textit{viz. LiveQAMed and ii. Alexa}, each having 104 number of questions and at an average of 8.80 and 8.34 number of answers per question. There are 25 number of questions and at an average of 10.44 answers per question are there in the validation set. The test set for this task is having 150 question pairs and on an average 8.5 answer per question. \textit{\textbf{Task 1(NLI):}} In the first task, we propose five runs. In all the tasks, we make use of either BERT or BioBERT models. We merge the input sentences pairs into a single sequence having maximum length of 128. They are separated by a special token ([SEP]). The first token of every sequence is always a special classification token ([CLS]). The final hidden state (i.e., output of Transformer) corresponding to this token is used as the aggregate sequence representation for the classification tasks. This final hidden state is a 768 dimensional vector (for bert-base) representing the input sentence pair. This vector is fed subsequently into one or more feed-forward layers with soft-max activation at the end for 3-way classification (Entailment, Neutral or Contradiction). The results for this task are shown in the Table \ref{resu-task1}. \begin{table}[] \centering \begin{tabular}{|c|c|} \hline \textbf{Runs} & \textbf{Result(Accuracy(\%))} \\ \hline 1 & 60.8 \\ \hline 2 & 71.7 \\ \hline 3 & 77.1 \\ \hline 4 & 80.3 \\ \hline 5 & \textbf{81.8} \\ \hline \end{tabular} \caption{Submission results of all the five runs for the NLI task (Task-1)} \label{resu-task1} \end{table} We have discussed the way we can use a BERT model to perform sentence classification in medical domain. It is observed that an absolute improvement of 5.4\% in accuracy has been achieved by using a BioBERT (pre-trained on PubMed abstracts) model in run 3 instead of using the original BERT-base-uncased model (Pre-trained on Wikipedia and Book Corpus (as used in run 2)). The increase in result may be the effect of BioBERT, because the other experimental set up remain same. The reason for using 1 feed forward layer at the end of BERT models in all the runs except the run 1 (no fine tuning), using only one feed forward layer was putting the model into an under fitting state. While in case of fine tuning a large model, one feed forward is enough as suggested by \cite{devlin-etal-2019-bert}. Up to run 3, we make use of 11232 sentence pairs for the training. Those sentence pairs are same as the one used to train several models used in \cite{romanov-shivade-2018-lessons}. We use the remaining 2817 sentence pairs for validation. The validation set accuracy is always around 3-4\% higher than the test case accuracy for all the runs up to run 3. For getting the higher accuracy we combine all the 14049 pairs in the subsequent run. We get the accuracy of 81.8 \% which is the highest among all the proposed methods. As per our knowledge, in the official results of NLI task we stand at 12th position among the 17 official teams which participated for the NLI task.\\ \textit{\textbf{Task 2 (RQE):}} In the second task i.e. task of Recognising Question Entailment, we propose five runs. The results are shown in the Table \ref{resu-task2}. \begin{table}[] \centering \begin{tabular}{|c|c|} \hline \textbf{Runs} & \textbf{Result(Accuracy(\%))} \\ \hline 1 & \textbf{53.2} \\ \hline 2 & 50.6 \\ \hline 3 & 48.1 \\ \hline 4 & 50.2 \\ \hline 5 & 48.9 \\ \hline \end{tabular} \caption{Submission results in all the five runs for the RQE Task (Task-2)} \label{resu-task2} \end{table} It is interesting to note the variation in accuracy for the different runs. Siamese architecture performs much better here. Another peculiarity is that fine tuning BERT hurts the performance while using pre-trained BERT embedding without fine tuning seems to be more useful. This is concluded by observing the results of run 2 and run 3. In run 2, we used only pre-trained BERT embedding for ([CLS]) token for classification, whereas in run 3, we fine tuned the BERT model. The highest accuracy is achieved by a Siamese Model consisting of 2 Bi-LSTMs with shared weights and a dense layers. In this task, 12 teams submitted their systems, and we stood the 10th position. \\ \textit{\textbf{Task 3 (QA):}} In this task, we offer 4 runs to tackle the problem. The results for this are shown in the Table \ref{resu-task3}. \begin{table}[] \scriptsize \centering \begin{tabular}{|c|c|c|c|c|} \hline & \multicolumn{4}{c|}{Results} \\ \hline \textbf{Runs} & \textbf{Accuracy(\%)} & \textbf{Spearman’s Rho} & \textbf{MRR} & \textbf{Precision} \\ \hline 1 & 57.3 & 0.053 & 0.8241 & 0.5610 \\ \hline 2 & 65.1 & 0.042 & 0.7811 & 0.7235 \\ \hline 3 & 67.8 & 0.034 & 0.8366 & 0.7421 \\ \hline 4 & \textbf{71.7} & 0.024 & 0.8611 & 0.7936 \\ \hline \end{tabular} \caption{Results obtained in all the four runs for the QA Task (Task - 3), where, MRR: Mean Reciprocal Rank} \label{resu-task3} \end{table} As we can see from the above discussions, the systems we build for this task comprises of two components, they are BERT and BM25. The BERT is used to predict the reference score of the test dataset. We rank the predicted scores using BM25. The BM25 part of the system is same for all the runs. In this task, participants are encouraged to compute the Mean Reciprocal Rank (MRR), Precision, and Spearman's Rank Correlation Coefficient as the evaluation measures in addition to Accuracy. We actually used BioBERT instead of original BERT from the run 3, which increases the accuracy with an absolute margin of 2.7\% (65.1 to 67.8\%). Using BioBERT we observe an improvement in MRR by 5.5\%. Our best run with an accuracy of 71.7\% attains the position of 6th among 10 teams in the official result.\\ \section{Conclusion and Future Work} In this paper, we present our system details and the results of various runs that reported as a part of our participation in the MEDIQA challenge. In this shared task three tasks, namely \textit{viz. i. Natural Language Inference ii. Question Entailment and iii. Question Answering} were introduced in the medical domain. We offer multiple systems (runs) for each of these tasks. Most of the proposed models are based on BERT/Bio-BERT embedding and BM25. These models yields encouraging performance in all the tasks In future we would like to extend our work as follows: \begin{itemize} \item Detailed analysis of the top-scoring models to understand their techniques and findings. \item We can do the task of NLI by fostering an \textit{Embedding from Language model (EMLo)} based model and do a comparative analysis with BERT based model. \end{itemize}
{'timestamp': '2019-06-18T02:00:14', 'yymm': '1906', 'arxiv_id': '1906.06332', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06332'}
arxiv
\section{Conclusion} We presented a VTQA model that combines visual and paragraph-captioning features to significantly improve visual question answering accuracy, via a model that performs early, late, and later fusion. While our model showed promising results, it still used a pre-trained paragraph captioning model to obtain the textual symbolic information. In future work, we are investigating whether the VTQA model can be jointly trained with the paragraph captioning model. \section*{Acknowledgments} We thank the reviewers for their helpful comments. This work was supported by NSF Award \#1840131, ARO-YIP Award \#W911NF-18-1-0336, and faculty awards from Google, Facebook, Bloomberg, and Salesforce. The views, opinions, and/or findings contained in this article are those of the authors and should not be interpreted as representing the official views or policies, either expressed or implied, of the funding agency. \section{Attention Visualization \label{app:visu}} As shown in Figure~\ref{fig:att_visu_sup}, paragraph captions contain direct or indirect clues for answering questions. \paragraph{The upper left figure} This is the case that a sentence in the paragraph caption can give obvious clue for answering the given question. By looking at the sentence ``a boy is standing on the beach'', this question can be answered correctly. \paragraph{The upper right figure} The sentence ``two cows are grazing in a field '' gives the correct answer ``2'' directly. \paragraph{The bottom left figure} There is no direct clue like ``he is playing tennis'', but the correct answer can be inferred by integrating the information from different sentences such as ``the man is holding a tennis racket'' and ``a man is standing on a tennis court''. \paragraph{The bottom right figure} This case seems tricky, but the answer can be inferred by associating the blue sky with daytime. \section{Experimental Setup} \noindent\textbf{Paragraph Caption}: We use paragraph annotations of images from Visual Genome \cite{krishnavisualgenome} collected by \citet{krause2017hierarchical}, since this dataset is the only dataset (to our knowledge) that annotates long-form paragraph image captions. We follow the dataset split of 14,575 / 2,487 / 2,489 (train / validation / test). \noindent\textbf{Visual Question Answering Pairs}: We also use the VQA pairs dataset from Visual Genome so as to match it with the provided paragraph captions. We almost follow the same image dataset split as paragraph caption data, except that we do not include images that do not have their own question-answer pairs in the train and evaluation sets. The total number of candidate answers is 177,424. Because that number is too huge to train, we truncate the question-answer pairs whose answer's frequency are under 30, which give us a list of 3,453 answers. So, the final number of question-answering pairs are 171,648 / 29,759 / 29,490 (train / validation / test). \noindent\textbf{Training Details}: Our hyperparameters are selected using validation set. The size of the visual feature of each object is set to 2048 and the dimension of the hidden layer of question encoder and caption encoder are 1024 and 2048 respectively. We use AdaMax~\cite{kingma2014adam} for the optimizer and a learning rate of 0.002. We modulate the final credit, which is added to the final logit of the model, by multiplying a scalar value \(c\) (we tune this to 1.0). \section{Introduction} Understanding visual information along with natural language have been studied in different ways. In visual question answering (VQA) \cite{VQA, balanced_vqa_v2, lu2016hierarchical, fukui2016multimodal, xu2016ask, yang2016stacked, zhu2016visual7w, Anderson2017up-down}, models are trained to choose the correct answer given a question about an image. On the other hand, in image captioning tasks \cite{karpathy2015deep, densecap, Anderson2017up-down, krause2017hierarchical, liang2017recurrent, melaskyriazi2018paragraph}, the goal is to generate sentences which should describe a given image. Similar to the VQA task, image captioning models should also learn the relationship between partial areas in an image and the generated words or phrases. While these two tasks seem to have different directions, they have the same purpose: understanding visual information with language. If their goal is similar, can the tasks help each other? In this work, we propose an approach to improve a VQA model by exploiting textual information from a paragraph captioning model. Suppose you are assembling furniture by looking at a visual manual. If you are stuck at a certain step and you are given a textual manual which more explicitly describes the names and shapes of the related parts, you could complete that step by reading this additional material and also by comparing it to the visual counterpart. With a similar intuition, paragraph-style descriptive captions can more explicitly (via intermediate symbolic representations) explain what objects are in the image and their relationships, and hence VQA questions can be answered more easily by matching the textual information with the questions. We provide a VQA model with such additional `textual manual' information to enhance its ability to answer questions. We use descriptive captions generated from a paragraph captioning model which capture more detailed aspects of an image than a single-sentence caption (which only conveys the most obvious or salient single piece of information). We also extract properties of objects, i.e., names and attributes from images to create simple sentences in the form of ``[object name] is [attribute]". Our VTQA model takes these paragraph captions and attribute sentences as input in addition to the standard input image features. The VTQA model combines the information from text and image with early fusion, late fusion, and later fusion. With early fusion, visual and textual features are combined via cross-attention to extract related information. Late fusion collects the scores of candidate answers from each module to come to an agreement. In later fusion, expected answers are given an extra score if they are in the recommendation list which is created with properties of detected objects. Empirically, each fusion technique provides complementary gains from paragraph caption information to improve VQA model performance, overall achieving significant improvements over a strong baseline VQA model. We also present several ablation studies and attention visualizations. \section{Models} \vspace{-5pt} The basic idea of our approach is to provide the VQA model with extra text information from paragraph captions and object properties (see Fig.~\ref{fig:model}). \subsection{Paragraph Captioning Model} Our paragraph captioning module is based on \citet{melaskyriazi2018paragraph}'s work, which uses CIDEr~\cite{vedantam2015cider} directly as a reward to train their model. They make the approach possible by employing self-critical sequence training (SCST)~\cite{rennie2017self}. However, only employing RL training causes repeated sentences. As a solution, they apply \(n\)-gram repetition penalty to prevent the model from generating such duplicated sentences. We adopt their model and approach to generate paragraph captions. \subsection{VTQA Model} \subsubsection{Features} \noindent\textbf{Visual Features}: We adopt the bottom-up and top-down VQA model from \newcite{Anderson2017up-down}, which uses visual features from the salient areas in an image (bottom-up) and gives them weights using attention mechanism (top-down) with features from question encoding. Following \citet{Anderson2017up-down}, we also use Faster R-CNN \cite{ren2015faster} to get visual features \(V \in \mathbb{R} ^{O\times d}\), where \(O\) is \#objects detected and \(d\) is the dimension of each visual feature of the objects. \noindent\textbf{Paragraph Captions}: These provide diverse aspects of an image by describing the whole scene. We use GloVe \cite{pennington2014glove} for the word embeddings. The embedded words are sequentially fed into the encoder, for which we use GRU \cite{cho2014learning}, to create a sentence representation, \(s_{i} \in \mathbb{R}^d\): $s_i = \textrm{ENC}_{sent}(w_{0:T})$, where \(T\) is the number of words. The paragraph feature is a matrix which contains each sentence representation in each row, \(P \in \mathbb{R}^{K\times d} \), where \(K\) is the number of sentences in a paragraph. \noindent\textbf{Object Property Sentences}: The other text we use is from properties of detected objects in images (name and attribute), which can provide explicit information of the corresponding object to a VQA model. We create simple sentences like, ``[object name] is [attributes]". We then obtain sentence representations by following the same process as what we do with the paragraph captions above. Each sentence vector is then attached to the corresponding visual feature, like \lq name tag\rq{}, to allow the model to identify objects in the image and their corresponding traits. \subsubsection{Three Fusion Levels} \noindent\textbf{Early Fusion}: In the early fusion stage, visual features are fused with paragraph caption and object property features to extract relevant information. For visual and paragraph caption features, cross-attention is applied to get similarity between each component of visual features (objects) and a paragraph caption (sentences). We follow \citet{seo2016bidirectional}'s approach to compute the similarity matrix, \(S \in \mathbb{R}^{O\times K} \). From the similarity matrix $V^p = \textrm{softmax}(S^{T})V$ and the new paragraph representation, \(P^f\) is obtained by concatenating \(P\) and \(P*V^p\): $P^f = [P;P*V^p]$, where * is element-wise product operation. For visual feature and object property feature \(C\), they are already aligned and the new visual feature \(V^f\) becomes $V^f = [V;V*C]$. Given the fused representations, the attention mechanism is applied over each row of the representations to weight more relevant features to the question. \vspace{-5pt} \begin{align} a_i &= w_a^T(\textrm{ReLU}(W_{sa}s^f_i) * \textrm{ReLU}(W_{qa}q)) \\ \mathbf{\alpha} &= \textrm{softmax}(a) \end{align} where, \(s^f_i\) is a row vector of new fused paragraph representation and \(q\) is the representation vector of a question which is encoded with GRU unit. \(w_a^T\), \(W_{sa}\), and \(W_{qa}\) are trainable weights. Given the attention weights, the weighted sum of each row vector, \(s^f_i\) leads to a final paragraph vector $p = \sum_{i=1}^K \alpha_is^f_i$. The paragraph vector is fed to a nonlinear layer and combined with question vector by element-wise product. \vspace{-5pt} \begin{align} p^q &= \textrm{ReLU}(W_{p}p) * \textrm{ReLU}(W_{q}q) \\ L_p &= \textrm{classifier}(p^q) \end{align} where \(W_{p}\) and \(W_{q}\) are trainable weights, and \(L_p\) contains the scores for each candidate answer. The same process is applied to the visual features to obtain $L_v = \textrm{classifier}(v^q)$. \noindent\textbf{Late Fusion}: In late fusion, logits from each module are integrated into one vector. We adopt the approach of~\newcite{wang2016temporal}. Instead of just adding the logits, we create two more vectors by max pooling and averaging those logits and add them to create a new logit $L_{new} = L_1 + L_2 + ... + L_n + ... + L_{max} + L_{avg}$, where \(L_{n}\) is \(n\)th logit, and \(L_{max}\) and \(L_{avg}\) are from max-pooling and averaging all other logits. The intuition of creating these logits is that they can play as extra voters so that the model can be more robust and powerful. \noindent\textbf{Answer Recommendation or `Later Fusion'}: Salient regions of an image can draw people's attention and thus questions and answers are much more likely to be related to those areas. Objects often denote the most prominent locations of these salient areas. From this intuition, we introduce a way to directly connect the salient spots with candidate answers. We collect properties (name and attributes) of all detected objects and search over answers to figure out which answer can be extracted from the properties. Answers in this list of expected answers are given extra credit to enhance the chance to be selected. If logit \(L_{\text{before}}\) from the final layer contains scores of each answer, we want to raise the scores to logit \(L_{\text{after}}\) if the corresponding answers are in the list \(l_c\): \begin{equation} \begin{split} &L_{\text{before}} = \{a_1, a_2, ..., a_n, ..\} \\ &L_{\text{after}} = \{\hat{a}_1, \hat{a}_2, ..., \hat{a}_n, ..\} \\ \end{split} \end{equation} \vspace{-15pt} \begin{equation} \hat{a}_n = \left\{ \begin{array}{rl} a_n + c \cdot \textrm{std}(L_{before}) &\mbox{ if } n \in l_c\\ a_n \qquad \qquad &\mbox{ otherwise} \end{array} \right. \end{equation} where the \(\textrm{std}(\cdot)\) operation calculates the standard deviation of a vector and \(c\) is a tunable parameter. \(l_c\) is the list of the word indices of detected objects and their corresponding attributes. The indices of the objects and the attributes are converted to the indices of candidate answers. \section{Related Work} \noindent\textbf{Visual Question Answering (VQA)}: VQA has been one of the most active areas among efforts to connect language and vision~\cite{malinowski2014multi, tu2014joint}. The recent success of deep neural networks, attention modules, and object plus salient region detection has made more effective approaches possible \cite{VQA, balanced_vqa_v2, lu2016hierarchical, fukui2016multimodal, xu2016ask, yang2016stacked, zhu2016visual7w,Anderson2017up-down}. \noindent\textbf{Paragraph Image Captioning}: Another thread of research which deals with combined visual and language problem is the translation of visual contents to natural language. The first approach to this included using a single-sentence image captioning model \cite{karpathy2015deep}. However, this task is not able to accommodate the variety of aspects of a single image. \citet{densecap} expanded single-sentence captioning to describe each object in an image via a dense captioning model. Recently, paragraph captioning models \cite{krause2017hierarchical, liang2017recurrent,melaskyriazi2018paragraph} attempt to capture the many aspects in an image more coherently. \section{Results, Ablations, and Analysis} \vspace{-5pt} \begin{table}[t] \small \begin{center} \begin{tabular}{|c|l|c|} \hline & Model & Test accuracy (\%)\\ \hline 1 & VQA baseline & 44.68 \\ 2 & VQA + MFB baseline & 44.94 \\ \hline 3 & VTQA (EF+LF+AR) & 46.86 \\ \hline \end{tabular} \end{center} \vspace{-10pt} \caption{Our VTQA model significantly outperforms (\(p < \) 0.001) the strong baseline VQA model (we do not apply MFB to our VTQA model, since it does not work for the VTQA model). \label{tbl:VQAvsVTQA}} \vspace{-5pt} \end{table} \begin{table}[t] \small \begin{center} \begin{tabular}{|c|l|c|} \hline & Model & Val accuracy (\%) \\ \hline 1 & VTQA + EF (base model) & 45.41\\ 2 & VTQA + EF + LF & 46.36\\ 3 & VTQA + EF + AR & 46.95\\ 4 & VTQA + EF + LF + AR & 47.60\\ \hline \end{tabular} \end{center} \vspace{-10pt} \caption{Our early (EF), late (LF), and later fusion (or Answer Recommendation AR) modules each improves the performance of our VTQA model.\label{tbl:eflfar}} \vspace{-10pt} \end{table} \paragraph{VQA vs. VTQA} As shown in Table \ref{tbl:VQAvsVTQA}, our VTQA model increases the accuracy by 1.92\% from the baseline VQA model for which we employ \citet{Anderson2017up-down}'s model and apply multi-modal factorized bilinear pooling (MFB) \cite{yu2017multiMFB}. This implies that our textual data helps improve VQA model performance by providing clues to answer questions. We run each model five times with different seeds and take the average value of them. For each of the five runs, our VTQA model performs significantly better (\(p<0.001\)) than the VQA baseline model. \paragraph{Late Fusion and Later Fusion Ablations} As shown in row 2 of Table \ref{tbl:eflfar}, late fusion improves the model by 0.95\%, indicating that visual and textual features complement each other. As shown in row 3 and 4 of Table \ref{tbl:eflfar}, giving an extra score to the expected answers increases the accuracy by 1.54\% from the base model (row 1) and by 1.24\% from the result of late fusion (row 2), respectively. This could imply that salient parts (in our case, objects) can give direct cues for answering questions.\footnote{Object Properties: Appending the encoded object properties to visual features improves the accuracy by 0.15\% (47.26 vs. 47.41). This implies that incorporating extra textual information into visual features could help a model better understand the visual features for performing the VQA task.} \begin{table}[t] \small \begin{center} \begin{tabular}{|c|l|c|} \hline & Model & Val accuracy (\%) \\ \hline 1 & TextQA with GT & 43.96\\ 2 & TextQA with GenP & 42.07 \\ \hline \end{tabular} \end{center} \vspace{-10pt} \caption{ TextQA with GT model outperforms TextQA with GenP (we run each model five times with different seeds and average the scores. GT: Ground-Truth, GenP: Generated Paragraph). \label{tbl:textQA} } \vspace{-10pt} \end{table} \begin{table}[t] \small \begin{center} \begin{tabular}{|c|l|c|} \hline & Human Eval. & Accuracy (\%) \\ \hline 1 & with GT & 55.00\\ 2 & with GenP & 42.67\\ \hline \end{tabular} \end{center} \vspace{-10pt} \caption{ Human evaluation only with paragraph captions and questions of the validation dataset. Human evaluation with GT shows better performance than human evaluation with GenP. \label{tbl:humanEval} } \vspace{-10pt} \end{table} \vspace{-2pt} \paragraph{Ground-Truth vs. Generated Paragraphs \label{para:textqa}} We manually investigate (300 examples) how many questions can be answered only from the ground-truth (GT) versus generated paragraph (GenP) captions. We also train a TextQA model (which uses cross-attention mechanism between question and caption) to evaluate the performance of the GT and GenP captions. As shown in Table \ref{tbl:textQA}, the GT captions can answer more questions correctly than GenP captions in TextQA model evaluation. Human evaluation with GT captions also shows better performance than with GenP captions as seen in Table \ref{tbl:humanEval}. However, the results from the manual investigation have around 12\% gap between GT and generated captions, while the gap between the results from the TextQA model is relatively small (1.89\%). This shows that paragraph captions can answer several VQA questions but our current model is not able to extract the extra information from the GT captions. This allows future work: (1) the TextQA/VTQA models should be improved to extract more information from the GT captions; (2) paragraph captioning models should also be improved to generate captions closer to the GT captions.\footnote{We also ran our full VTQA model with the ground truth (GT) paragraph captions and got an accuracy value of 48.04\% on the validation dataset (we ran the model five times with different seeds and average the scores), whereas the VTQA result from generated paragraph captions was 47.43\%. This again implies that our current VTQA model is not able to extract all the information enough from GT paragraph captions for answering questions, and hence improving the model to better capture clues from GT captions is useful future work.} \begin{figure}[t] \includegraphics[width=80mm]{new_att_visu_1.pdf} \vspace{-24pt} \caption{Attention Visualization for an example answered correctly by our model. \label{fig:att_visu_1}} \vspace{-15pt} \end{figure} \vspace{-5pt} \paragraph{Attention Analysis} Finally, we also visualize the attention over each sentence of an input paragraph caption w.r.t. a question. As shown in Figure~\ref{fig:att_visu_1}, a sentence which has a direct clue for a question get much higher weights than others. This explicit textual information helps a VQA model handle what might be hard to reason about only-visually, e.g., `two (2) cows'. Please see \autoref{app:visu} for more attention visualization examples.
{'timestamp': '2019-06-17T02:14:50', 'yymm': '1906', 'arxiv_id': '1906.06216', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06216'}
arxiv
\section{Introduction} \IEEEPARstart{T}{he} very vision of Industry 4.0---making the industrial processes intelligent, efficient, and safer---is tied to real-time automation and control of dynamic industrial systems over wireless networks. However, what is achievable by existing wireless networking solutions in terms of communication reliability and latency is not sufficient for critical machine-type communication (cMTC). Instead, ultra-reliable and low-latency communication (URLLC) is required. Yet, the key sectors in cMTC---factory automation, power distribution, vehicular communication, live audio/video production, etc.~\cite{3gpp.22.804}---require precise time synchronization up to device level. If we take discrete manufacturing as an example, devices require synchronized coordination for timely/sequential execution of tasks such as assembly, picking, welding, and palletizing. In power distribution, monitoring and fault localization require perfectly synchronized measurement units. Hence in cMTC applications, where ultra-reliability is vital for the safety of processes, equipment and users, and low latency for real-time functionality of applications, time synchronization is intrinsic to real-time coordination and interaction among devices. Supporting determinism, in terms of reliability of $10^{-5}--10^{-6}$ and latency up to \SI{1}{\milli\second}, and synchronism with jitter below \SI{1}{\micro\second} is the focus of 3GPP uses cases within 5G URLLC. These requirements add challenges to the design of the radio access network (RAN) from the physical layer leading up to the radio resource control (RRC) layer. 3GPP Rel-15 and 16 specify new features for New Radio (NR) including faster scheduling, short and robust transmissions, repetitions, faster retransmissions, preemption, and packet duplication as well as multiconnectivity architectures~\cite{Sachs}. However, the importance of time synchronization, which is a crucial component of the new RAN technologies and services, moves beyond RAN to provide an accurate time instant on a common time base to the devices and is perceived as a key enabler for cMTC applications. The devices can achieve perfect time alignment to the coordinated universal time (UTC) by employing a global positioning system (GPS) receiver; however, such a solution is expensive and mainly impractical for indoor industrial deployments. In industrial measurement and control systems, time is synchronized separately from the data flow~\cite{TSN_Finn}. Since many application require synchronization, it is an essential part of the Ethernet-based networks such as PROFINET and the rapidly evolving open standard: time-sensitive networking (TSN) by IEEE~802.1 task group~\cite{TSN2}. TSN defines a series of standards to support URLLC use cases over best-effort Ethernet networks. The synchronization procedures for industrial systems are rooted in precision time protocol (PTP), defined by the IEEE~1588 standard. All the Ethernet-based automation networks utilize IEEE~1588 variants, known as PTP profiles. In TSN, for instance, the transport of precise timing and synchronization is performed using the IEEE~802.1AS standard. Establishing over-the-air (OTA) accurate time reference at device level requires transfer/exchange of timestamps between controller (i.e., BS) and devices. Additionally, 5G is expected to coexist with existing industrial Ethernet and emerging TSN-based industrial Ethernet even in greenfield deployments. Therefore, the integration of 5G into existing industrial connectivity fabric would require devices to maintain synchronization with local time domains within a mixed 5G-Ethernet network as depicted in Fig.~\ref{fig:usecases}. The transfer of precise timing reference (absolute or local domain time) via the 5G system to the devices using OTA synchronization procedure is currently being investigated in 3GPP Rel-16~\cite{3gpp.22.104}. \begin{figure*}[!t] \centering \includegraphics[width=0.80\linewidth]{uCasesV2.png} \caption{Critical machine type communication (cMTC) use cases requiring device-level time synchronization and an enabling solution over 5G-TSN network.} \label{fig:usecases} \vspace{-10pt} \end{figure*} Nevertheless, securing a robust distribution of reference time into the network has many associated challenges. Following the existing procedures in cellular systems, the devices must compensate for the propagation delay in the reference time. Typically, this is achieved using timing advance (TA)---the frame alignment procedure as used in LTE and the 5G NR radio interface. However, TA is an approximation of device-to-BS (D2B) propagation time since each TA value corresponds to a certain range of time of arrival (TOA) values. Both, the limited granularity of TA and the random perturbations in TOA due to the measurement and multipath errors, respectively, can introduce inaccuracy in reference time. Therefore, the impact of TA-related errors need a careful investigation and correction to meet the device-level synchronization target. In the rest of this article, we present the role of time synchronization in multiple cMTC use cases in Section~\ref{sec:UseCases}. Section~\ref{sec:ExistingSolution} discusses the transition of 5G into industrial networks. Section~\ref{sec:OTA} presents the 5G NR procedures and the associated timing errors to enable device-level synchronization. In Section~\ref{sec:Prop}, we quantify the errors in propagation delay due to TA and propose an improvement. Outline of new research directions to enhance synchronization accuracy in 5G concludes the paper. \section{Use Cases of Device-Level Time Synchronization} \label{sec:UseCases} Any application requiring imperceptible lag in executing orders or reporting remote events are the potential uses cases of device-level time synchronization. Albeit 5G-cMTC outlines several URLLC cases in \cite{3gpp.22.804}, we now elaborate the ones with device-level synchronization requisites (see Fig.~\ref{fig:usecases}). \subsection{Factory Automation} \label{subsec:IndustrialAutomation} \subsubsection{Isochronous real-time communication} Critical industrial automation applications exhibit stringent requirement on communication latency and reliability, as well as on time-synchronized coordination among machines and robots. In particular, in closed-loop motion control---in packaging, printing and symmetrical welding/polishing---machines execute meticulously sequenced real-time tasks isochronously. Typically, a sequence of real-time control command/response frames is communicated over the communication links between controller and devices. To ensure smooth and deterministic execution of the production cycle, timely coordination among devices/machines must be accomplished, which is possible only if the devices are synchronized to a common time reference with clock disparity of less than \SI{1}{\micro\second}~\cite{3gpp.22.104}. \subsubsection{Data fusion} Robust and accurate synchronization is required for meaningful sensor fusion, post-processing, and network analytics. In low-latency time-sensitive applications, the responses from various sensors must be fused to drive the logic behind the control systems. Such data fusion requires a synchronized collection of the events. Besides, the industrial IoT is meant to increase the operational efficiency based on data analytics of sensory information; however, the time context of sensor events must be factored in to make analytics definitive. \subsection{Power Distribution Networks} \label{subsec:PowerDistribution} Managing power distribution networks---with an increasing amount of distributed energy resources and an increasing need of reliability, efficiency, and flexibility---requires enhanced communication technologies/services for functions as protection, control and remote monitoring~\cite{ABB5GSG}. \subsubsection{Fault protection} In a transmission/distribution line, usually a line differential protection system detects faults based on a periodic sampling of electric current between the two relay devices~\cite{ABB5GSG}. When the relays differ in measurements, the system triggers the fault protection procedure, i.e., it sends a trip command to the relevant breaker. For such fault detection procedure to work correctly, relays are synchronized with an accuracy of \SI{< 20}{\micro\second}. \subsubsection{Control and optimization} With the increasing penetration of renewable resources, control and optimization are required at both the transmission and distribution level. A vital control task is to match power supply and demand as per the voltage and frequency regulations, where a control strategy, either centralized or distributed, is devised based on fine-grained information of measured electrical values of the load and the source. Although reliability and latency of reporting such information are specific to a control strategy, time synchronization accuracy is less demanding. \subsubsection{Monitoring and diagnostics} Situational awareness and insights on the condition of distribution systems depend on measurements and analytics. There is a growing interest in instrumenting power distribution systems with phase measurement units (PMU)-like technology. PMUs take time-synchronized measurements of voltage and current to activate monitoring system for fault diagnosis. For instance, by synchronously measuring electric wave generated by a fault location at two points along the distribution line, the monitoring system can estimate the fault location based on the reported timing information. Precision in physical measurements, time synchronization accuracy, and the ability to cross-reference event locations offer more in-depth insights into the distribution network. Usually, synchronization accuracy of higher than \SI{1}{\micro\second} is required to keep fault location uncertainty below \SI{300}{\meter}~\cite{Aamir_OTA}. \subsection{Vehicular Communication} Vehicular communication is about wireless transactions among nearby vehicles and infrastructure---vehicle to everything (V2X) communication---that can enable cooperative intelligent transport systems capable of reducing traffic congestion and improving road safety. Ensuring timely and robust delivery of safety-related messages is critical. The examples of safety-related operations are forward collision warning and emergency electronic brake lights, which alert the drivers about possible collisions ahead. To execute these operations, vehicles need to exchange position, event timestamp, brake status, and heading information from onboard GPS. Furthermore, to function such coordination as per the age of information, the applications require that all the involved vehicles are synchronized to the same reference clock, usually provided by GPS. However, for such critical operations, a backup time synchronization service must be provided by the roadside communication infrastructure to handle GPS signal blockages and outages~\cite{HASAN_V2V}. \subsection{Wireless Live Audio/Video Production} \label{subsec:AV} Wireless audio/video (A/V) equipment used for real-time production of audio-visual information, be it in the entertainment industry or live events and conferences, are denoted by the term program making and special events (PMSE). Usually, the wireless A/V production equipment includes cameras, microphones, in-ear monitors (IEM), conference systems, and mixing consoles. PMSE use cases are diverse, while each commonly being used for a limited duration in a confined local geographical area. In terms of communication requirements of typical live audio/video production setups, low-latency and ultra-reliable transmissions are pivotal to avoid failures and perceptible corruption of the media content. Moreover, perfect synchronization is crucial to minimize jitter among captured samples by multiple devices to render audio-video content~\cite{PMSE}. For instance, in a demanding live audio performance, the microphone signal is streamed over a wireless channel to an audio mixing console where different incoming audio streams are mixed, and the in-ear audio mixes are streamed back to the microphone users via the wireless IEM system. For this, the audio sampling of microphones' signals must be perfectly synchronized to the system clock, which is usually integrated into the mixing console used for capturing, mixing, and playback of the audio signals. For immersive 3D audio effects, devices required synchronization accuracy of \SI{1}{\micro\second}, which is higher than the audio sampling clock~\cite{PMSE,3gpp.22.804}. \section{Keeping Devices in Sync: Existing Solutions and Emerging Requirements} \label{sec:ExistingSolution} The above-studied use cases manifest that embedded shared understanding of time at devices is essential for cMTC applications. To use 5G therein, a synchronization solution over the 5G system is a key URLLC enabler. Apart from delivering the desired accuracy, it should support the scenarios ranging from standalone operation to integration with existing/emerging solutions. \subsection{Existing Industrial Networks} \subsubsection{Fragmented legacy solutions} in factory automation, the field devices---industrial devices and controller---are connected by various wired fieldbus and real-time Ethernet networks such as PROFIBUS, PROFINET, EtherCAT, Sercos and Modbus. While in power systems, the IEC 61850 series of standards specify networks for substation automation with profiles such as generic object-oriented substation event (GOOSE) and sampled values (SV). GOOSE is used for exchanging status, measurements, and interlocking signals between intelligent electrical devices (IEDs) while SV is used to transmit periodically sampled voltage and current measurements from measuring devices to IEDs~\cite{WirelessHP}. The wireless solutions (e.g., WirelessHART, ISA 100.11a, WIA-PA, WIA-FA) constitute only a small fraction of the installed base, and are used for non-critical connectivity of sensors over unlicensed bands. \subsubsection{Time-sensitive networking (TSN)} the connectivity of industrial networks is expected to harmonize with the introduction of \textit{Ethernet with TSN support}---an open standard being developed by IEEE~802.1---where a TSN profile for industrial automation is being developed by the IEC/IEEE~60802~\cite{IEC-IEEE60802-TSN}. TSN includes the new features to standard Ethernet as \cite{TSN_Finn}: a) deterministic and bounded latency without congestion loss, b) priority queuing with resource allocation, c) reliability with redundant flows, and d) time synchronization among devices. \subsubsection{Precision time protocol} pertaining to the transport of precise time and synchronization in industrial applications, variants (profiles) of IEEE 1588 (PTP) protocol are used. For example, PTP profile in TSN is IEEE 802.1AS while the synchronization profile in IEC 61850 is IEC/IEEE~61850-9-3. However, synchronization is kept separable from the rest of networking stack, thus reliability and timeliness features are independent of any particular synchronization protocol. \definecolor{Gray}{gray}{0.9} \definecolor{Gray1}{gray}{0.7} \bgroup \def1.2{1.2} \begin{table*}[t] \caption{Timing Errors Associated to Delivery of Reference Time from BS to Devices~\cite{3gpp.TdocR1_1901252}} \centering \begin{tabular}{|p{0.23\linewidth}|p{0.47\linewidth}|p{0.20\linewidth}|} \hline \textbf{Timing error source} & \textbf{Description} & \textbf{Typical values for SCS \newline [15 30 60 120] \SI{}{\kilo\hertz}} \\ \hline \rowcolor{Gray} \multicolumn{3}{|l|}{\textbf{\textit{Reference time indication errors}}}\\ \hline Time alignment error & Refers to desired synchronization accuracy among BSs for perfect frame timing required by new NR technologies and services. (see Section~\ref{subsec:BSasMaster}) & \hfil Tx diversity: $\sim$\SI{65}{ \nano\second} \newline \hspace*{23pt} Positioning: $\sim$ \SI{10}{\nano\second}\\ \hline Reference time granularity& SIB16 granularity to transport reference time information. & \hfil \SI{250}{\nano\second}\\ \hline UE DL frame timing estimation & Detection error of DL signal at UE, and the device's processing jitter & \hfil [390 260 227 114] ns\\ \hline \rowcolor{Gray} \multicolumn{3}{|l|}{\textbf{\textit{TA related errors}}} \\ \hline TA estimation error & TOA estimation is perturbed by measurement noise and multipath errors depending on the signal bandwidth and SNR of the direct path (Section~\ref{sec:Prop}). & \hfil Environment dependent \\ \hline TA granularity & Error introduced by limited TA granularity, $ \pm 8 \cdot 16 \cdot T_c /2^\mu$ (Section~\ref{subsec:TA}) & \hfil [260 130 65 32.5] ns\\ \hline TA adjustment error & The error at UE comprising systematic and dynamic factors. & \hfil [130 130 65 16] ns\\ \hline Asymmetric DL/UL propagation \newline delay & TA estimates UL propagation delay while reference time indication needs adjustment with DL propagation delay. Asymmetry in DL/UL propagation delay (FDD) will introduce inaccuracy in TA-compensated reference time. & \hfil Negligible in TDD\\ \hline UE UL transmit timing error & The jitter in UL transmit time contributes to TOA estimation error, which could be considered to be negated by DL frame timing error. & Same as "UE DL frame timing estimation error" \\ \hline \rowcolor{Gray} \multicolumn{3}{|l|}{\textbf{\textit{Other errors}}}\\ \hline UE modem to host interface \newline chipset delay & Delay introduced by the interface between the device modem and the host chipset maintaining clock information. & \hfil $\sim$\SI{65}{ \nano\second}\\ \hline \end{tabular} \label{tab:TimingErrors} \vspace{-7pt} \end{table*} \egroup \subsection{5G Synchronization Requirements} \subsubsection{Timing service in RAN} GPS could provide an accurate but costly solution to establish UTC time-reference at devices. Further, jamming and weak signal reception raise concerns in indoor deployments. In indoor deployments, although a GPS antenna could be installed outdoors to enhance signal reception, long feeder cable with an amplifier from the antenna to the receiver is required, which is costly and inflexible. Consequently, there is an interest in built-in timing service over cellular networks. The 5G network can be considered stable and scalable; however, there is a need to upgrade the 5G air interface to distribute accurate time reference to the devices. \subsubsection{Unified 5G-TSN network} 5G is expected to satisfy most of the cMTC applications with new RAN features like faster scheduling, short/robust transmissions, faster retransmissions, preemption and packet duplication, as well as diversity techniques. However, it will replace the existing systems in multiple phases, primarily driven by the benefits (cost, capabilities) of introducing 5G connectivity. Even in greenfield industrial deployments, not all industrial networks will be migrated to 5G. Therein, the 5G local industrial network will coexist with traditional networks and might even require transparent integration to transport industrial Ethernet or TSN. In such scenarios, collaborative actions of devices belonging to different domains need to be coordinated in time. Accordingly, the 5G system will need to relate/synchronize devices to a master clock of one or more time domains to enable time-scheduled coordination over a combined 5G-TSN network~\cite{5GSmartManufactu}. \section{Synchronization in 5G RAN} \label{sec:OTA} In this section, we study the 5G radio interface to transport reference time from BS to the devices. Usually, a common notion of time can be maintained by periodically broadcasting timestamps of reference time from master (i.e., BS) to the slave devices. The devices use timestamp information to align their clocks after removing any time progress from the timestamping-to-reception instance of the message~\cite{Aamir_OTA}. The synchronization period depends on the frequency and phase stability of the onboard oscillators in devices, causing clock skew and drift. In this process, the main disrupting elements to synchronization accuracy are: \begin{itemize}[leftmargin=*] \item[--] \textit{BS related}: time alignment error (TAE), timestamping to transmission delay, and timestamping granularity. \item[--] \textit{Channel related}: propagation time and its variations (jitter), asymmetry uplink/ downlink propagation, and scheduling/medium access delays. \item[--] \textit{Device related}: time adjustment errors at device, 5G device to IIoT host interface delay. \end{itemize} In reference to a synchronization procedure currently being investigated in 3GPP release-16, we discuss in the following, (a) possible TAE at BS, (b) reference time indication procedure from BS to devices, and (c) propagation delay adjustment in reference time. Table~\ref{tab:TimingErrors} summarizes the timing errors associated with the synchronization steps (b) inclusive of (a) and (c). \subsection{Time Alignment Error at BS} \label{subsec:BSasMaster} Any TAE at the BS will add up in time uncertainty at the devices. The TAE requirements for new 5G technologies/services are summarized as follows~\cite{TS_5G}. \begin{itemize}[leftmargin=*] \item \textit{T\text{\normalfont x} diversity}: TAE requirement for MIMO and Tx diversity is \SI{+-65}{\nano\second}. \item \textit{Carrier aggregation (CA)}: enables the use of multiple contiguous or non-contiguous intra-band/inter-band carriers to increase throughput. CA can be performed at intra-BS and inter-BS level where TAE for inter-BS CA must be \SI{<260}{\nano\second}. \item \textit{Coordinated multi-point (CoMP)}: joint transmission from multiple BSs requires time offset at a device within $[-0.5, 2]~$\SI{}{\micro\second}, which includes TAE and the difference in propagation delays where inter-site $\mathrm{TAE}\leq$\SI{260}{\nano\second} is required. \item \textit{New frame structure}: to avoid overlap in uplink and downlink timeslots in TDD systems, new 5G frame structure requires accuracy of \SI{+-390}{\nano\second} in D2B alignment. \item \textit{Positioning}: 5G positioning services seeking \SI{3}{\meter} location accuracy require $\mathrm{TAE}$ of \SI{+-10}{\nano\second} among BSs. \end{itemize} \subsection{Reference Time Indication (RTI)} RTI is concerned with the distribution of reference time in 5G RAN, from BS to devices. The reference time could be either the 5G or TSN network's clock. To distribute the 5G network clock as a reference, 3GPP considers 5G radio interface signaling as dedicated RRC or system information block (SIB) broadcasts~\cite{3gpp.TdocR2_1817172}. Whereas, to support the distribution of TSN clock, the 5G system acts as an IEEE~802.1AS time-aware system by adding TSN translators (TTs) in the wireless edge, i.e., before a BS and after each device~\cite{3gpp.Tdoc_Joa}. Only TTs support the IEEE~802.1AS operations; particularly, the timestamping of a PTP sync message at TTs using 5G clock and forwarding of the PTP sync via user plane PDU. The difference in egress and ingress timestamps of a PTP sync message determines the \textit{residence time} in the 5G system. Hence, distribution of the 5G system clock is a prerequisite to establish any reference time at devices, while the following aspects of SIB/RRC signaling can introduce time uncertainty: \begin{itemize}[leftmargin=*] \item[] \textit{Time progression adjustment:} BS needs to adjust the acquired reference time with a projected time of transmission: that is, up to a reference point in RTI frame occurring at the antenna reference point. \item[] \textit{Granularity:} timestamping granularity of SIB messages could introduce time uncertainty of up to \SI{250}{\nano\second}. \end{itemize} \subsection{Propagation Delay Compensation} \label{subsec:TA} Accurate estimation of propagation delay is a key factor to enable device-level synchronization. It is required to adjust the time progression after SIB timestamping/transmission. However, the need for propagation delay compensation depends on the service area. In the case of a small area (e.g., \SI{10}{\meter\squared}) the propagation delay is almost negligible (i.e., \SI{0.3}{\nano\second}), and the timing inaccuracy is the sum of reference time indication errors as listed in Table~\ref{tab:TimingErrors}. For larger areas, 3GPP resort to utilizing timing advance (TA) in combination with SIB16. In LTE and 5G systems, TA is used to adjust the uplink transmission time of the devices based on their respective propagation delays in order to avoid collisions at the BS. TA is negotiated during network access and RRC connected state using uplink reference signals: PRACH, SRS, and DMRS. During network access, BS estimates TA from \textit{network access request} from a device and issues a TA command in \textit{random access response} with $N_{\textrm{TA}}$ values with index $T_A = 0,1,2,\cdots,3846$. The value of time alignment with subcarrier spacing (SCS) of $2^\mu\cdot$ \SI{15}{\kilo\hertz} is multiple of $T_\mu = 16 \cdot 64 \cdot T_c / 2^\mu$~sec before the start of the corresponding downlink frame. Here, $\mu=0,1,2,\cdots$ defines the NR numerology, $T_c = 1/(\Delta f_{\max} \cdot N_f)$ is the 5G basic time unit with $\Delta f_{\max} =$ \SI{480}{\kilo\hertz} and $N_f=4096$. In RRC connected state, TA is negotiated with periodic control messages to adjust the uplink timing relative to current timing. The time alignment has the index value $T_A = 0,1,\cdots, 63$, which adjusts the current uplink timing by $(T_A-31) \cdot T_\mu$~sec. As mentioned earlier, a device can use TA as an approximation of TOA---the propagation time from the device to BS---in the absence of original TOA measurement. As each TA corresponds to a range of TOA measurements with timeslot $T = T_\mu/2$ of limited granularity, TA can yield a maximum synchronization error of $\pm T = 8 \cdot 16 \cdot T_c/2^\mu$. Moreover, the random errors in the original TOA could lead to wrong TA selection. The impact of random errors on TOA estimation from TA is further discussed in Section~\ref{sec:Prop}. \subsection{Other Timing Errors} The above-discussed radio parameters have other associated timing errors, which must be considered in BS-to-device time offset budget to find synchronization inaccuracy. The components that could impact the accuracy are elaborated in Table~\ref{tab:TimingErrors} and can be logically visualized in Fig.~\ref{fig:TA}. \begin{figure*}[!t] \centering \includegraphics[width=0.75\linewidth]{TAV2.png} \caption{Transport of reference time information to the devices: Principles and error components.} \label{fig:TA} \vspace{-10pt} \end{figure*} \section{Analysis of Error in Time of Arrival} \label{sec:Prop} We analyze the error in estimating TOA from TA while considering measurement errors in true TOA. A BS measures the unknown TOA $\tau$ of a radio signal with a certain random error $\sigma$, which is a function of signal bandwidth and signal-to-noise ratio (SNR)~\cite{gentile2012geolocation}. For TOA values in a timeslot with width $T$ and center at $t_i$, the BS assigns the TA bin $i$ as illustrated in Fig.~\ref{fig:TA}. If $\tau$ falls within one or two $\sigma$ of timeslot borders $t_i \pm T/2$, then there is a non-negligible probability that a wrong TA bin is selected. Selection of a wrong timeslot adds at least $T/2$ to the error in $\tau$. Thus, both the random error $\sigma$ and the timeslot width $T$ must be considered to find the value of $\tau$ from TA. We studied the error in true TOA and the estimated TOA extracted from reported TA by simulations. We assume a uniform distribution of true TOA in timeslot $t_i \pm T/2$, where true TOA is perturbed by Gaussian errors with $\sigma = T/2$ and $\sigma_2 = T$ but without any bias. It implies that the $\sigma$ reduces with the increase in SCS; a receiver's ability to resolve TOA of multipath signal components improves with increase in subcarrier spacing. Fig.~\ref{fig:num} shows the cumulative distribution functions (CDFs) of the studied error for different SCSs. The CDF curves are useful to define the confidence level in synchronization accuracy when adjusting the propagation delay in reference time indication. The point on the $x$-axis with $P(X \leq x) = 1$ guarantees that the synchronization error introduced by TA is less than equal to $x$ with 100\% confidence, and must be used in the device synchronization budget. If we denote this point as $P_e$, it can be observed that as SCS increases the $P_e$ reduces. Note that if the timing errors in Table~\ref{tab:TimingErrors} are taken into account, $P_e$ for SCS \SI{15}{\kilo\hertz} is high enough not to satisfy \SI{1}{\micro\second} target. \begin{figure}[!t] \centering \includegraphics[width=1\linewidth]{numV2.pdf} \caption{CDFs of the difference between true TOA and estimated TOA from reported TA, where $\sigma$ is the variance of measurement error in true TOA.} \label{fig:num} \vspace{-10pt} \end{figure} \begin{figure}[!t] \centering \includegraphics[width=1\linewidth]{ta_avgV2.pdf} \caption{Error reduction by averaging multiple TAs for \SI{15}{\kilo\hertz} subcarrier spacing. Solid curves: $\sigma=T/2$, dashed curves: $\sigma=T$.} \label{fig:TA_avg} \vspace{-10pt} \end{figure} One solution to reduce the error $P_e$ is to take an average of two or more consecutive TAs. The averaging reduces the error caused by the TOA measurements that are assigned TA values to the sides of true TA. For SCS \SI{15}{\kilo\hertz}, Fig.~\ref{fig:TA_avg} shows that error reduction obtained by averaging multiple consecutive TAs is substantial. Therefore, a required synchronization accuracy target can be achieved by appropriate selection of averaging size for a given measurement random error, which is influenced by the propagation conditions. \textbf{Random error under multipath fading}: Fig.~\ref{fig:num} shows that TOA estimation from TA depends on the amount of perturbation in true TOA. In densely cluttered environments, the true TOA is perturbed by both the measurement noise and LOS/NLOS multipath error. In LOS multipath environments, multipath signals tend to arrive close to the direct path. The signals combine to create a cluster in power delay profile, making it challenging to extract TOA of the direct path. As a result, depending on the structure of the propagation environment, TOA estimation from TA may lead to varying synchronization errors. The statistics of LOS multipath errors can be modeled as a zero-mean Gaussian with variance directly related to the variations in the multipath structure~\cite{gentile2012geolocation}. Contrarily, NLOS multipath environment is challenging because of multipath errors, where the TOA estimation depends on the detection of direct path (DP). If the attenuated DP is detectable (consider light obstructions), better TOA estimation can be achieved. On the other hand, in case the DP is buried in noise, it will create a bias ($b_p$ in Fig.~\ref{fig:TA}) towards a longer first non-DP. Since shadowing introduces fluctuations in the detection of the first arrival path, the variance of multipath error is also time varying. Clearly, NLOS introduces bias as well as other perturbations in TOA estimation. One technique to remove bias could be to introduce some correction for it. The other issue is the asymmetric distribution of random errors that may require a TOA estimator other than the timeslot center. \section{Conclusions and Research Directions} Sharing a common time-base among devices is essential for cMTC applications to perform various tasks; ranging from coordination, sampling and fusion, and event reconstruction. Together with low-latency and ultra-reliability, enabling ultra-tight time synchronization can be regarded as the third dimension of 5G RAN enhancements. To operate either in standalone or in cohesion with TSN/Ethernet solutions, transport of reference time over the 5G air interface is currently being investigated in 3GPP release 16 in order to enable device-level synchronization across multiple domains. In this paper, we discussed enabling radio parameters in 5G NR and focused on propagation time compensation in reference time based on timing advance (TA). Timing advance corresponds to a set of TOA values, which is perturbed by signal propagation conditions, and could lead to substantial errors in time synchronization. We studied the TA-dependent timing error and observed that the averaging of multiple TAs could reduce the error and satisfy the overall accuracy target. Nevertheless, there are still many research areas to be addressed, for instance: i) impact of mobility on TA averaging, ii) TOA uplink and downlink asymmetry, iii) bias and TOA error asymmetry in NLOS conditions. \bibliographystyle{IEEEtran}
{'timestamp': '2019-06-18T02:02:08', 'yymm': '1906', 'arxiv_id': '1906.06380', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06380'}
arxiv
\section{VisGel Dataset} \lblsec{data} \vspace{-2mm} Here we describe our data collection procedure including the tactile sensor we used, the way that robotic arms interacting with objects, and a diverse object set that includes $195$ different everyday items from a wide range of categories. \myparagraph{Data collection setup} \reffig{overview}a illustrates the setup in our experiments. We use KUKA LBR iiwa industrial robotic arms to automate the data collection process. The arm is equipped with a GelSight sensor~\cite{yuan2017gelsight} to collect raw tactile images. We set up a webcam on a tripod at the back of the arm to capture videos of the scenes where the robotic arm touching the objects. We use recorded timestamps to synchronize visual and tactile images. \myparagraph{GelSight sensor} The GelSight sensor~\cite{johnson2009retrographic,johnson2011microgeometry,yuan2017gelsight} is an optical tactile sensor that measures the texture and geometry of a contact surface at very high spatial resolution~\cite{johnson2011microgeometry}. The surface of the sensor is a soft elastomer painted with a reflective membrane that deforms to the shape of the object upon contact, and the sensing area is about $1.5\text{cm} \times 1.5\text{cm}$. Underneath this elastomer is an ordinary camera that views the deformed gel. The colored LEDs illuminate the gel from different directions, resulting in a three-channel surface normal image (\reffig{overview}b). GelSight also uses markers on the membrane and recording the flow field of the marker movement to sketched the deformation. The 2D image format of the raw tactile data allows us to use standard convolutional neural networks (CNN)~\cite{lecun1998gradient} for processing and extracting tactile information. \reffig{overview}c and d show a few examples of collected raw tactile data. \myparagraph{Objects dataset} \reffig{objects} shows all the $195$ objects used in our study. To collect such a diverse set of objects, we start from Yale-CMU-Berkeley (YCB) dataset~\cite{calli2017ycb}, a standard daily life object dataset widely used in robotic manipulation research. We use $45$ objects with a wide range of shapes, textures, weight, sizes, and rigidity. We discard the rest of the $25$ small objects (e.g., plastic nut) as they are occluded by the robot arm from the camera viewpoint. To further increase the diversity of objects, we obtain additional $150$ new consumer products that include the categories in the YCB dataset (i.e., food items, tool items, shape items, task items, and kitchen items) as well as new categories such as fabrics and stationery. We use $165$ objects during our training and $30$ seen and $30$ novel objects during test. Each scene contains $4\sim 10$ randomly placed objects that sometimes overlap with each other. \input{figText/dataset.tex} \myparagraph{Generating touch proposals} A random touch at an arbitrary location may be suboptimal due to two reasons. First, the robotic arm can often touch nothing but the desk. Second, the arm may touch in an undesirable direction or unexpectedly move the object so that the GelSight Sensor fails to capture any tactile signal. To address the above issues and generate better touch proposals, we first reconstruct 3D point clouds of the scene with a real-time SLAM system called ElasticFusion~\cite{whelan2015elasticfusion}. We then sample a random touch region whose surface normals are mostly perpendicular to the desk. The touching direction is important as it allows robot arms to firmly press the object without moving it. \myparagraph{Dataset Statistics} We have collected synchronized tactile images and RGB images for $195$ objects. \reftbl{dataset} shows the basic statistics of the dataset for both training and test. To our knowledge, this is the largest vision-touch dataset. \begin{table}[t] \begin{center} \begin{tabular}{ | l || r | r | } \hline & \# touches & \# total vision-touch frames \\ \hline Train & 10,000 & 2,500,000 \\ \hline Test & 2,000 & 500,000 \\ \hline \end{tabular} \end{center} \vspace{-5pt} \caption{{\bf Statistics of our VisGel dataset.} We use a video camera and a tactile sensor to collect a large-scale synchronized videos of a robot arm interacting with household objects. } \lbltbl{dataset} \vspace{-10pt} \end{table} \section{Discussion} \lblsec{conclusion} \vspace{-2mm} In this work, we have proposed to draw connections between vision and touch with conditional adversarial networks. Humans heavily rely on both sensory modalities when interacting with the world. Our model can produce promising cross-modal prediction results for both known objects and unseen objects. In the future, vision-touch cross-modal connection may help downstream vision and robotics applications, such as object recognition and grasping in a low-light environment, and physical scene understanding. \section{Experiments} \lblsec{experiments} \vspace{-2mm} We evaluate our method on cross-modal prediction tasks between vision and touch using the VisGel dataset. We report multiple metrics that evaluate different aspects of the predictions. For vision $\rightarrow$ touch prediction, we measure (1) perceptual realism using AMT: whether results look realistic, (2) the moment of contact: whether our model can predict if a GelSight sensor is in contact with the object, and (3) markers' deformation: whether our model can track the deformation of the membrane. Regarding touch $\rightarrow$ vision direction, we evaluate our model using (1) visual realism via AMT and (2) the sense of touch: whether the predicted touch position shares a similar feel with the ground truth position. We also include the evaluations regarding full-reference metrics in the supplement. We feed reference images to all the baselines, as they are crucial for handling the scale discrepancy (\reffig{reference}). Please find our code, data, and more results on our \href{http://visgel.csail.mit.edu}{website}. \subsection{Vision $\rightarrow$ Touch} We first run the trained models to generate GelSight outputs frame by frame and then concatenate adjacent frames together into a video. Each video contains exactly one action with $64$ consecutive frames. An ideal model should produce a perceptually realistic and temporal coherent output. Furthermore, when humans observe this kind of physical interaction, we can roughly infer the moment of contact and the force being applied to the touch; hence, we would also like to assess our model's understanding of the interaction. In particular, we evaluate whether our model can predict the moment of contact as well as the deformation of the markers grid. Our baselines include pix2pix\xspace~\cite{isola2017image} and different variants of our method. \myparagraph{Perceptual realism (AMT)} \begin{table} \centering \scalebox{0.8} { \begin{tabular}{lcc} & \textbf{Seen objects} & \textbf{Unseen objects} \\ \textbf{Method} & \begin{tabular}{@{}c@{}}\% Turkers labeled \\ \emph{real}\end{tabular} & \begin{tabular}{@{}c@{}}\% Turkers labeled \\ \emph{real}\end{tabular} \\ \hline pix2pix\xspace~\cite{isola2017image} & 28.09 \% & 21.74\% \\ pix2pix\xspace~\cite{isola2017image} w/ temporal & 35.02\% & 27.70\%\\ Ours w/o temporal & 41.44\% & 31.60\% \\ Ours w/o rebalancing & 39.95\% & 34.86\% \\ {\bf Ours} & {\bf 46.63\% } & {\bf 38.22\% } \\ \end{tabular} } \vspace{2pt} \caption {{\bf Vision2Touch AMT ``real vs fake" test.} Our method can synthesize more realistic tactile signals, compared to both pix2pix\xspace~\cite{isola2017image} and our baselines, both for seen and novel objects.} \vspace{-15pt} \lbltbl{AMT1} \end{table} Human subjective ratings have been shown to be a more meaningful metric for image synthesis tasks~\cite{zhang2016colorful,isola2017image} compared to metrics such as RMS or SSIM. We follow a similar study protocol as described in Zhang et al.~\cite{zhang2016colorful} and run a real vs. fake forced-choice test on Amazon Mechanical Turk (AMT). In particular, we present our participants with the ground truth tactile videos and the predicted tactile results along with the vision inputs. We ask which tactile video corresponds better to the input vision signal. As most people may not be familiar with tactile data, we first educate the participants with $5$ typical ground truth vision-touch video pairs and detailed instruction. In total, we collect $8,000$ judgments for $1,250$ results. \reftbl{AMT1} shows that our full method can outperform the baselines on both seen objects (different touches) and unseen objects. \myparagraph{The moment of contact} The deformation on the GelSight marker field indicates whether and when a GelSight sensor touches a surface. We evaluate our system by measuring how well it can predict the \textit{moment of contact} by comparing with the ground truth contact event. We track the GelSight markers and calculate the average $L_2$ distance for each marker. For each touch sequence, we denote the largest deformation distance as $d_\text{max}$ and the smallest deformation as $d_\text{min}$, we then set a cutoff threshold at $r\cdot(d_\text{max} - d_\text{min}) + d_\text{min}$, where $r$ is set to $0.6$ in our case. We mark the left most and right most cutoff time point as $t_l$ and $t_r$ individually. Similarly, we compute the ground truth cutoff time as $t_l^\text{gt}$ and $t_r^\text{gt}$; then the error of the \textit{moment of contact} for this sequence is determined as $|t_l - t_l^\text{gt}| + |t_r - t_r^\text{gt}|$. \input{figText/vision2touch_quanti.tex} \input{figText/using_temporal.tex} As shown in \reffig{vision2touch_quantitative}a, the methods without temporal cues produce a large error due to temporal misalignment. \reffig{vision2touch_quantitative}a also shows that our model works better on seen objects than unseen objects, which coincides with the empirical observation that humans can better predict the touch outcomes if they have interacted with the object before. We also show deformation curves for several torch sequences. \reffig{motion_scale}a illustrates a case where all the methods perform well in detecting the ground truth \textit{moment of contact}. \reffig{motion_scale}b shows an example where the model without temporal cues completely missed the contact event. \reffig{motion_scale}c shows another common situation, where the \textit{moment of contact} predicted by the method without temporal cues shifts from the ground truth. \reffig{motion_scale} shows several groundtruth frames and predicted results. As expected, a single-frame method fails to accurately predict the contact moment. \myparagraph{Tracking markers' deformation} The flow field of the GelSight markers characterizes the deformation of the membrane, which is useful for representing contact forces as well as detecting slippery~\cite{dong2017improved}. In this section, we assess our model's ability by comparing the predicted deformation with the ground truth deformation. We calculate the average $L_2$ distance between each corresponding markers in the ground truth and the generated touch image. \reffig{vision2touch_quantitative}b shows that the single-frame model performs the worst, as it misses important temporal cues, which makes it hard to infer information like force and sliding. \input{figText/vis.tex} \myparagraph{Visualizing the learned representation} We visualize the learned representation using a recent network interpretation method~\cite{zhou2014object}, which can highlight important image regions for final decisions (\reffig{vis}a and b). Many meaningful patterns emerge, such as arms hovering in the air or touching flat area and sharp edges. This result implies that our representation learns shared information across two modalities. Please see our supplemental material\xspace for more visualizations. \subsection{Touch $\rightarrow$ Vision} We can also go from touch to vision - by giving the model a reference visual image and tactile signal, can the model imagine where it is touching? It is impossible to locate the GelSight if the sensor is not in contact with anything; hence, we only include vision-touch pairs where the sensor touches the objects. An accurate model should predict a reasonable touch position from the geometric cues of the touch images. \myparagraph{The Sense of Touch} Different regions and objects can stimulate similar senses of touch. For example, our finger may feel the same if we touch various regions on a flat surface or along the same sharp edge. Therefore, given a tactile input, it is unrealistic to ask a model to predict the exact same touch location as the ground truth. As long as the model can predict a touch position that feels the same as the ground truth position, it is still a valid prediction. To quantify this, we show the predicted visual image as well as the ground truth visual image. Then we ask human participants whether these two touch locations feel similar or not. We report the average accuracy of each method over $400$ images ($200$ seen objects and $200$ unseen objects). Table~\ref{tab:touch} shows the performance of different methods. Our full method can produce much more plausible touch positions. We also compare our method with a baseline trained with explicit supervision provided by humans. Specifically, we hand-label the position of the GelSight on $1,000$ images, and train a Stacked Hourglass Network~\cite{newell2016stacked} to predict plausible touch positions. Qualitative and quantitative comparisons are shown in~\reffig{quali} and Table~\ref{tab:touch}. Our self-supervised method is comparable to its fully-supervised counterpart. \begin{table} \centering \scalebox{0.8} { \begin{tabular}{clcc} & & \textbf{Seen objects} & \textbf{Unseen objects} \\ &\textbf{Method} & \begin{tabular}{@{}c@{}}\% Turkers labeled \\ \emph{Feels Similar}\end{tabular} & \begin{tabular}{@{}c@{}}\% Turkers labeled \\ \emph{Feels Similar}\end{tabular} \\ \hline \multirow{4}{*}{\rotatebox[origin=c]{90}{\parbox[c]{1.5cm}{\centering Self-Supervised}}} & pix2pix\xspace~\cite{isola2017image} & 44.52\% & 25.21\% \\ & pix2pix\xspace w/ temporal & 53.27\% & 35.45\%\\ & Ours w/o temporal & 81.31\% & 78.40\% \\ & {\bf Ours} & {\bf 89.20\%} & {\bf 83.44\%} \\ \hline & Supervised prediction & {\bf 90.37\%} & {\bf 85.29\%} \\ \end{tabular} } \vspace{2pt} \caption {{\bf Touch2Vision ``Feels Similar vs Feels Different" test}. Our self-supervised method significantly outperforms baselines. The accuracy is comparable to fully supervised prediction method trained with ground truth annotations.} \vspace{-5pt} \label{tab:touch} \end{table} \myparagraph{Perceptual Realism (AMT)} Since it is difficult for humans participants to imagine a robotic manipulation scene given only tactile data, we evaluate the quality of results without showing the tactile input. In particular, we show each image for $1$ second, and AMT participants are then given unlimited time to decide which one is fake. The first $10$ images of each HITs are used for practice and we give AMT participants the correct answer. The participants are then asked to finish the next $40$ trials. In total, we collect $8,000$ judgments for $1,000$ results. Table~\ref{tab:AMT} shows the fooling rate of each method. We note that results from pix2pix~\cite{isola2017image} suffer from severe mode collapse and always produce identical images, although they look realistic according to AMT participants. See our website for a more detailed comparison. We also observe that the temporal cues do not always improve the quality of results for touch $\rightarrow$ vision direction as we only consider vision-touch pairs in which the sensor touches the objects. \begin{table}[t] \centering \scalebox{0.8} { \begin{tabular}{lcc} & \textbf{Seen objects} & \textbf{Unseen objects} \\ \textbf{Method} & \begin{tabular}{@{}c@{}}\% Turkers labeled \\ \emph{real}\end{tabular} & \begin{tabular}{@{}c@{}}\% Turkers labeled \\ \emph{real}\end{tabular} \\ \hline pix2pix\xspace~\cite{isola2017image} & 25.80\% &{\bf 26.13\%} \\ pix2pix\xspace~\cite{isola2017image} w/ temporal & 23.61\% & 19.67\%\\ Ours w/o temporal & {\bf 30.80\%} & 20.74\% \\ {\bf Ours} & 30.50\% & 24.22\% \\ \end{tabular} } \vspace{2pt} \caption {{\bf Touch2Vision AMT ``real vs fake" test}. Although pix2pix achieves the highest score for unseen objects, it always produces identical images due to mode collapse. \reffig{quali} shows a typical collapsed mode, where pix2pix always places the arm at the top-right corner of the image. More qualitative results can be found in our supplementary material.} \vspace{-10pt} \label{tab:AMT} \end{table} \myparagraph{Visualizing the learned representation} The visualization of the learned representations (\reffig{vis}c and d) show two units that focus on different geometric cues. Please see our supplemental material\xspace for more examples. \section{Introduction} \lblsec{intro} \vspace{-2mm} \input{figText/overview.tex} People perceive the world in a multi-modal way where vision and touch are highly intertwined~\cite{lederman1986perception,yau2009analogous}: when we close our eyes and use only our fingertips to sense an object in front of us, we can make guesses about its texture and geometry. For example in \reffig{overview}d, one can probably tell that s/he is touching a piece of delicate fabric based on its tactile ``feeling"; similarly, we can imagine the feeling of touch by just seeing the object. In \reffig{overview}c, without directly contacting the rim of a mug, we can easily imagine the sharpness and hardness of the touch merely by our visual perception. The underlying reason for this cross-modal connection is the shared physical properties that influence both modalities such as local geometry, texture, roughness, hardness and so on. Therefore, it would be desirable to build a computational model that can extract such shared representations from one modality and transfer them to the other. In this work, we present a cross-modal prediction system between vision and touch with the goals of \textit{learning to see by touching} and \textit{learning to feel by seeing}. Different from other cross-modal prediction problems where sensory data in different domains are roughly spatially aligned~\cite{isola2017image,aytar2017cross}, the scale gap between vision and touch signals is huge. While our visual perception system processes the entire scene as a whole, our fingers can only sense a tiny fraction of the object at any given moment. To investigate the connections between vision and touch, we introduce two cross-modal prediction tasks: (1) synthesizing plausible temporal tactile signals from vision inputs, and (2) predicting which object and which object part is being touched directly from tactile inputs. \reffig{overview}c and d show a few representative results. To accomplish these tasks, we build a robotic system to automate the process of collecting large-scale visual-touch pairs. As shown in \reffig{overview}a, a robot arm is equipped with a tactile sensor called GelSight~\cite{johnson2011microgeometry}. We also set up a standalone web camera to record visual information of both objects and arms. In total, we recorded $12,000$ touches on $195$ objects from a wide range of categories. Each touch action contains a video sequence of $250$ frames, resulting in $3$ million visual and tactile paired images. The usage of the dataset is not limited to the above two applications. Our model is built on conditional adversarial networks~\cite{goodfellow2014generative,isola2017image}. The standard approach~\cite{isola2017image} yields less satisfactory results in our tasks due to the following two challenges. First, the scale gap between vision and touch makes the previous methods~\cite{isola2017image,wang2017high} less suitable as they are tailored for spatially aligned image pairs. To address this scale gap, we incorporate the scale and location information of the touch into our model, which significantly improves the results. Second, we encounter severe mode collapse during GANs training when the model generates the same output regardless of inputs. It is because the majority of our tactile data only contain flat regions as often times, robots arms are either in the air or touching textureless surface, To prevent mode collapse, we adopt a data rebalancing strategy to help the generator produce diverse modes. We present both qualitative results and quantitative analysis to evaluate our model. The evaluations include human perceptual studies regarding the photorealism of the results, as well as objective measures such as the accuracy of touch locations and the amount of deformation in the GelSight images. We also perform ablation studies regarding alternative model choices and objective functions. Finally, we visualize the learned representations of our model to help understand what it has captured. \section{Cross-Modal Prediction} \vspace{-2mm} \input{figText/model.tex} We propose a cross-modal prediction method for predicting vision from touch and vice versa. First, we describe our basic method based on conditional GANs~\cite{isola2017image} in \refsec{method:cGANs}. We further improve the accuracy and the quality of our prediction results with three modifications tailored for our tasks in \refsec{method:improve}. We first incorporate the scale and location of the touch into our model. Then, we use a data rebalancing mechanism to increase the diversity of our results. Finally, we further improve the temporal coherence and accuracy of our results by extracting temporal information from nearby input frames. In \refsec{method:details}, we describe the details of our training procedure as well as network designs. \subsection{Conditional GANs} \lblsec{method:cGANs} Our approach is built on the pix2pix\xspace method~\cite{isola2017image}, a recently proposed general-purpose conditional GANs framework for image-to-image translation. In the context of vision-touch cross-modal prediction, the generator $G\xspace$ takes either a vision or tactile image $x$ as an input and produce an output image in the other domain with $y=G\xspace(x)$. The discriminator $D\xspace$ observes both the input image $x$ and the output result $y$: $D\xspace(x, y) \rightarrow [0, 1]$. During training, the discriminator $D\xspace$ is trained to reveal the differences between synthesized results and real images while the objective of the generator $G\xspace$ is to produce photorealistic results that can fool the discriminator $D\xspace$. We train the model with vision-touch image pairs $\{(\mathbf{x},\mathbf{y})\}$. In the task of touch $\rightarrow$ vision, $\mathbf{x}$ is a touch image and $\mathbf{y}$ is the corresponding visual image. The same thing applies to the vision $\rightarrow$ touch direction, i.e., $(\mathbf{x},\mathbf{y}) = (\text{visual image}, \text{touch image})$. Conditional GANs can be optimized via the following min-max objective: \begin{equation} G\xspace^*=\arg \min_{G\xspace} \max_{D\xspace} \mathcal{L}_{\text{GAN}}(G\xspace, D\xspace) + \lambda \mathcal{L}_1(G\xspace) \lbleq{minimax} \end{equation} where the adversarial loss $\mathcal{L}_{\text{GAN}}(G\xspace,D\xspace)$ is derived as: \begin{equation} \mathbb{E}\xspace_{(\mathbf{x},\mathbf{y})}[\log D\xspace(\mathbf{x},\mathbf{y})]+ \mathbb{E}\xspace_{\mathbf{x}}[\log (1- D\xspace(\mathbf{x},G\xspace(\mathbf{x}))], \lbleq{gan_problem} \end{equation} where the generator $G\xspace$ strives to minimize the above objective against the discriminator's effort to maximize it, and we denote $\mathbb{E}_{\mathbf{x}} \triangleq \mathbb{E}_{\mathbf{x}\sim p_{\text{data}}(x)}$ and $ \mathbb{E}_{(\mathbf{x},\mathbf{y})} \triangleq \mathbb{E}_{(\mathbf{x},\mathbf{y}) \sim p_{\text{data}}(\mathbf{x}, \mathbf{y})}$ for brevity. In additional to the GAN loss, we also add a direct regression $L_1$ loss between the predicted results and the ground truth images. This loss has been shown to help stabilize GAN training in prior work~\cite{isola2017image}: \begin{equation} \mathcal{L}_1(G\xspace) = \mathbb{E}\xspace_{(\mathbf{x},\mathbf{y})} ||\mathbf{y} - G\xspace(\mathbf{x})||_1 \lbleq{l1} \end{equation} \subsection{Improving Photorealism and Accuracy} \lblsec{method:improve} We first experimented with the above conditional GANs framework. Unfortunately, as shown in the \reffig{reference}, the synthesized results are far from satisfactory, often looking unrealistic and suffering from severe visual artifacts. Besides, the generated results do not align well with input signals. To address the above issues, we make a few modifications to the basic algorithm, which significantly improve the quality of the results as well as the match between input-output pairs. We first feed tactile and visual reference images to both the generator and the discriminator so that the model only needs to learn to model cross-modal changes rather than the entire signal. Second, we use a data-driven data rebalancing mechanism in our training so that the network is more robust to mode collapse problem where the data is highly imbalanced. Finally, we extract information from multiple neighbor frames of input videos rather than the current frame alone, producing temporal coherent outputs. \myparagraph{Using reference tactile and visual images} As we have mentioned before, the scale between a touch signal and a visual image is huge as a GelSight sensor can only contact a very tiny portion compared to the visual image. This gap makes the cross-modal prediction between vision and touch quite challenging. Regarding touch to vision, we need to solve an almost impossible `extrapolation' problem from a tiny patch to an entire image. From vision to touch, the model has to first localize the location of the touch and then infer the material and geometry of the touched region. \reffig{reference} shows a few results produced by conditional GANs model described in \refsec{method:cGANs}, where no reference is used. The low quality of the results is not surprising due to self-occlusion and big scale discrepancy. We sidestep this difficulty by providing our system both the reference tactile and visual images as shown in \reffig{overview}c and d. A reference visual image captures the original scene without any robot-object interaction. For vision to touch direction, when the robot arm is operating, our model can simply compare the current frame with its reference image and easily identify the location and the scale of the touch. For touch to vision direction, a reference visual image can tell our model the original scene and our model only needs to predict the location of the touch and hallucinate the robotic arm, without rendering the entire scene from scratch. A reference tactile image captures the tactile response when the sensor touches nothing, which can help the system calibrate the tactile input, as different GelSight sensors have different lighting distribution and black dot patterns. \input{figText/using_reference.tex} In particular, we feed both vision and tactile reference images $\mathbf{r} = (\mathbf{x}^{\text{ref}}, \mathbf{y}^{\text{ref}})$ to the generator $G\xspace$ and the discriminator $D\xspace$. As the reference image and the output often share common low-level features, we introduce skip connections~\cite{ronneberger2015u,he2016deep} between the encoder convolutional layers and transposed-convolutional layers in our decoder. \myparagraph{Data rebalancing} In our recorded data, around $60$ percentage of times, the robot arm is in the air without touching any object. This results in a huge data imbalance issue, where more than half of our tactile data has only near-flat responses without any texture or geometry. This highly imbalanced dataset causes severe model collapse during GANs training~\cite{goodfellow2016nips}. To address it, we apply data rebalancing technique, widely used in classification tasks~\cite{farabet2013learning,zhang2016colorful}. In particular, during the training, we reweight the loss of each data pair $(\mathbf{x}^t, \mathbf{r}, \mathbf{y}^t)$ based on its rarity score $\mathbf{w}^t$. In practice, we calculate the rarity score based on a ad-hoc metric. We first compute a residual image $\|\mathbf{x}^t - \mathbf{x}^{\text{ref}}\|$ between the current tactile data $\mathbf{x}^t$ and its reference tactile data $\mathbf{x}^{\text{ref}}$. We then simply calculate the variance of Laplacian derivatives over the difference image. For IO efficiency, instead of reweighting, we sample the training data pair $(\mathbf{x}^t, \mathbf{r}, \mathbf{y}^t)$ with the probability $\frac{\mathbf{w}^t}{\sum_{t} \mathbf{w}^t}$. We denote the resulting data distribution as $p_{\mathbf{w}}$. \reffig{quali} shows a few qualitative results demonstrating the improvement by using data rebalancing. Our evaluation in \refsec{experiments} also shows the effectiveness of data rebalancing. \myparagraph{Incorporating temporal cues} We find that our initial results look quite realistic, but the predicted output sequences and input sequences are often out of sync (\reffig{motion_scale}). To address this temporal mismatch issue, we use multiple nearby frames of the input signal in addition to its current frame. In practice, we sample $5$ consecutive frames every $2$ frames: $\bar{\mathbf{x}}^{t} = \{\mathbf{x}^{t-4}, \mathbf{x}^{t-2}, \mathbf{x}^{t}, \mathbf{x}^{t+2}, \mathbf{x}^{t+4}\}$ at a particular moment $t$. To reduce data redundancy, we only use grayscale images and leave the reference image as RGB. \myparagraph{Our full model} \reffig{arch} shows an overview of our final cross-modal prediction model. The generator $G\xspace$ takes both input data $\bar{\mathbf{x}}^{t} = \{\mathbf{x}^{t-4}, \mathbf{x}^{t-2}, \mathbf{x}^{t}, \mathbf{x}^{t+2}, \mathbf{x}^{t+4}\}$ as well as reference vision and tactile images $\mathbf{r} = (\mathbf{x}^{\text{ref}}, \mathbf{y}^{\text{ref}})$ and produce a output image $\hat{\mathbf{y}}^t = G\xspace(\bar{\mathbf{x}}^t, \mathbf{r})$ at moment $t$ in the target domain. We extend the minimax objective (\refeq{minimax}) $\mathcal{L}_{\text{GAN}}(G\xspace, D\xspace) + \lambda \mathcal{L}_1(G\xspace)$, where $\mathcal{L}_{\text{GAN}}(G\xspace, D\xspace)$ is as follows: \begin{equation} \mathbb{E}\xspace_{(\bar{\mathbf{x}}^t,\mathbf{r}, \mathbf{y}^t)\sim p_{\mathbf{w}} }[\log D\xspace(\bar{\mathbf{x}}^t, \mathbf{r},\mathbf{y}^t)]+ \mathbb{E}\xspace_{(\bar{\mathbf{x}}^t,\mathbf{r})\sim p_{\mathbf{w}} }[\log (1- D\xspace(\bar{\mathbf{x}}^t, \mathbf{r}, \hat{\mathbf{y}}^t)], \lbleq{gan2} \end{equation} where $G\xspace$ and $D\xspace$ both takes both temporal data $\bar{\mathbf{x}}^t$ and reference images $\mathbf{r}$ as inputs. Similarly, the regression loss $ \mathcal{L}_1(G\xspace)$ can be calculated as: \begin{equation} \mathcal{L}_1(G\xspace) = \mathbb{E}\xspace_{(\bar{\mathbf{x}}^t,\mathbf{r},\mathbf{y}^t) \sim p_{\mathbf{w}}} ||\mathbf{y}^t - \hat{\mathbf{y}}^t||_1 \lbleq{l1_2} \end{equation} \reffig{arch} shows a sample input-output combination where the network takes a sequence of visual images and the corresponding references as inputs, synthesizing a tactile prediction as output. The same framework can be applied to the touch $\rightarrow$ vision direction as well. \input{figText/quali.tex} \subsection{Implementation details} \lblsec{method:details} \vspace{10pt} \myparagraph{Network architectures} \lblsec{arch} We use an encoder-decoder architecture for our generator. For the encoder, we use two ResNet-18 models~\cite{he2016deep} for encoding input images $\mathbf{x}$ and reference tactile and visual images $\mathbf{r}$ into $512$ dimensional latent vectors respectively. We concatenate two vectors from both encoders into one $1024$ dimensional vector and feed it to the decoder that contains $5$ standard strided-convolution layers. As the output result looks close to one of the reference images, we add several skip connections between the reference branch in the encoder and the decoder. For the discriminator, we use a standard ConvNet. Please find more details about our architectures in our supplement. \myparagraph{Training} \lblsec{train} We train the models with the Adam solver~\cite{kingma2014adam} with a learning rate of $0.0002$. We set $\lambda = 10$ for $\mathcal{L}_1$ loss. We use LSGANs loss~\cite{mao2017least} rather than standard GANs~\cite{goodfellow2014generative} for more stable training, as shown in prior work~\cite{zhu2017unpaired,wang2017high}. We apply standard data augmentation techniques~\cite{krizhevsky2012imagenet} including random cropping and slightly perturbing the brightness, contrast, saturation, and hue of input images. \section{Related Work} \lblsec{related} \vspace{10pt} \myparagraph{Cross-modal learning and prediction} People understand our visual world through many different modalities. Inspired by this, many researchers proposed to learn shared embeddings from multiple domains such as words and images~\cite{frome2013devise}, audio and videos~\cite{ngiam2011multimodal,aytar2016soundnet,owens2016ambient}, and texts and visual data~\cite{norouzi2013zero,otani2016learning,aytar2017cross}. Our work is mostly related to cross-modal prediction, which aims to predict data in one domain from another. Recent work has tackle different prediction tasks such as using vision to predict sound~\cite{owens2016visually} and generating captions for images~\cite{kulkarni2013babytalk,karpathy2015deep,xu2015show,donahue2015long}, thanks to large-scale paired cross-domain datasets, which are not currently available for vision and touch. We circumvent this difficulty by automating the data collection process with robots. \myparagraph{Vision and touch} To give intelligent robots the same tactile sensing ability, different types of force, haptic, and tactile sensors~\cite{lederman1987hand,lederman2009haptic,cutkosky2008force,kappassov2015tactile,SSundaram:2019:STAG} have been developed over the decades. Among them, GelSight~\cite{johnson2009retrographic,johnson2011microgeometry,yuan2017gelsight} is considered among the best high-resolution tactile sensors. Recently, researchers have used GelSight and other types of force and tactile sensors for many vision and robotic applications~\cite{yuan2016estimating,yuan2017shape, yuan2015measurement,li2013sensing,li2014localization,lee2018making}. Yuan et al.~\cite{yuan2017connecting} studied physical and material properties of fabrics by fusing visual, depth, and tactile sensors. Calandra et al.~\cite{calandra2017feeling} proposed a visual-tactile model for predicting grasp outcomes. Different from prior work that used vision and touch to improve individual tasks, in this work we focus on several cross-modal prediction tasks, investigating whether we can predict one signal from the other. \myparagraph{Image-to-image translation} Our model is built upon recent work on image-to-image translation~\cite{isola2017image,liu2016unsupervised,zhu2017unpaired}, which aims to translate an input image from one domain to a photorealistic output in the target domain. The key to its success relies on adversarial training~\cite{goodfellow2014generative,mirza2014conditional}, where a discriminator is trained to distinguish between the generated results and real images from the target domain. This method enables many applications such as synthesizing photos from user sketches~\cite{isola2017image,sangkloy2016scribbler}, changing night to day~\cite{isola2017image,zhu2017multimodal}, and turning semantic layouts into natural scenes~\cite{isola2017image,wang2017high}. Prior work often assumes that input and output images are geometrically aligned, which does not hold in our tasks due to the dramatic scale difference between two modalities. Therefore, we design objective functions and architectures to sidestep this scale mismatch. In \refsec{experiments}, we show that we can obtain more visually appealing results compared to recent methods~\cite{isola2017image}.
{'timestamp': '2019-06-17T02:18:27', 'yymm': '1906', 'arxiv_id': '1906.06322', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06322'}
arxiv
\section{Introduction} Resource optimization problems arise in critical environments, such as healthcare, air traffic control, and manufacturing operations. Many of these problems are characterized as NP-Hard \cite{CHAPMAN1987333} and computationally intractable to solve due to the large number of jobs to be performed and the complex interplay of temporal and resource-based constraints. Human domain experts readily achieve high-quality solutions to these problems by drawing on years of experience working with similar problems, during which they develop assistive strategies, heuristics, and guidelines. However, manually soliciting and encoding this knowledge in a computational framework is prone to error, not scalable, and leaves much to be desired \cite{Cheng:2006:FSM:1152999.1153056,Raghavan:2006:ALF:1248547.1248608}. In this paper, we aim to develop an apprenticeship learning framework that is able to infer these strategies implicitly from observation to scale the power of a standard homogeneous apprenticeship learning model. The challenge for apprenticeship learning in this context lies in learning from the different strategies domain experts develop from their unique experiences (i.e., learning from \emph{heterogeneous} demonstration). There has been significant progress in the ability to capture domain-expert knowledge from demonstration \citep{Abbeel04apprenticeshiplearning,DBLP:conf/ijcai/GombolayJSSS16, Konidaris11d, Zheng2015, Odom:2016:AAS:2936924.2936998,Ziebart:2008:MEI:1620270.1620297, inferring_beliefs}, predominantly using inverse reinforcement learning (IRL), to learn the reward function followed by domain experts (demonstrators), as well as a policy to optimize that reward function. However, applying IRL to planning domains is difficult due to the need for a model and the computational tractability as the state space grows. Heterogeneous decision-makers would appear to have different reward functions due to their innate preferences, and the IRL algorithm would fail to learn the true representation of the reward function. Furthermore, IRL requires the form of a reward function, and hypothesis in the case of max-entropy IRL, beforehand; Markov decision processes (MDPs) are ill-suited to many scheduling problems with non-Markovian constraints, and state-space enumeration and exploration is intractable for large-scale planning domains. \begin{figure}[btp] \begin{center} \centerline{\includegraphics[width = .9\textwidth]{images/data_efficiency_new.png}} \caption{Depiction of approaches to heterogeneity: (Left) Assume homogeneity~\cite{DBLP:conf/icml/SammutHKM92}, (Center) Partition data to semi-homogeneous clusters~\cite{Nikolaidis:2015:EML:2696454.2696455}, and (Right) Bayesian embeddings (our approach).} \label{fig:power_of_BNN} \end{center} \end{figure} Another complementary approach to capture domain-expert knowledge is to learn a function that directly maps states to actions \citep{chernova2007confidence,Terrell:2012:RAM:2392800.2392849, Huang:2014:LMM:2559636.2559668}. While this method scales better, such policy learning approaches do not yet handle heterogeneity well. The typical approach is to assume homogeneity over demonstrators, reasoning about the average human, as shown in the left-most diagram in Figure \ref{fig:power_of_BNN}. However, seminal work attempting to learn auto-pilots from commercial aviators found that pilots executing the same flight plan created such heterogeneous data as to make it more practical to learn from a single trajectory and disregard the remaining data~\cite{DBLP:conf/icml/SammutHKM92} . A more recent approach by \cite{Nikolaidis:2015:EML:2696454.2696455} sought to divide demonstrators into relatively-homogeneous clusters and learn a separate model of human decision-making from each cluster. As depicted in the center diagram in Figure \ref{fig:power_of_BNN}, this approach means that each model only has $\sfrac{1}{k}^{th}$ of the data to learn from, missing out on the possible homogeneity existing among the clusters. With high-dimensional data, expensive data collection, and residual, within-cluster heterogeneity, such an approach is ultimately unsatisfying. In this paper, we seek to overcome these key gaps in prior work by providing an integrated learning framework that allows for learning planning policies from heterogeneous decision-makers. We propose using personalized embeddings, learned through backpropogation, which enable the apprenticeship learner to automatically adapt to a person's unique characteristics while simultaneously leveraging any homogeneity that exists within the data (i.e., uniform adherence to hard constraints). We then present a human-interpretable version of our apprenticeship learning model that allows for direct analysis of a given demonstrator's behavior. We evaluate our approach on three problems: a synthetic low-dimensional environment, a synthetic job scheduling environment consisting of mock experts' scheduling heuristics, and a real-world dataset with human gameplay in StarCraft II. To our knowledge, this is the first paper to apply a personalized apprenticeship learning framework to learn from heterogeneous decision-makers in a cohesive framework that learns one integrated model to capture the similarity and differences of demonstrators through personalized embeddings. We also utilize counterfactual reasoning by pairwise comparisons to improve the model’s performance and display inference of the required action-specific features in domains in which they are not readily available. Finally, we introduce a methodology to learn and transfer our apprenticeship learning framework into a human-interpretable model for analysis or examination by a given expert for education and training. \section{Learning from Heterogeneous Decision Makers} \label{HLfD} Personalized Neural Networks (PNNs) are an extension of a standard neural network, or any differentiable model, that allow for capturing the homo- and heterogeneity among human domain experts presenting varied trajectories. Here, we present the framework for automatically inferring personalized embeddings to learn from heterogeneous decision-makers. Figure \ref{fig:my_pnn} depicts a PNN, which learns a model, $\pi_\theta : S \times \Omega \to [0,1]^{|A|}$, of the human demonstrator's decision-making policy, where $\omega\in\mathbb{R}^d$ is the demonstrator-specific personalized embedding of length $d$, which is a tune-able hyperparameter. As this personalized embedding is a continuous parameter, the outcome of choosing a length $d$ that is too high or low in comparison to the optimum is not nearly as detrimental as choosing the non-optimal number of clusters in the approach of \citet{Nikolaidis:2015:EML:2696454.2696455}. These latent features, $\omega$, provide the pattern of the current decision-maker, which accounts for a component not represented within the state features and that is needed for accurate prediction. The training procedure of a PNN consists of taking as input an example of a state, $s_t^p$ at time $t$, for person, $p$, as well as the person's embedding, $\omega_p^{(i)}$ at training iteration $i$, and predict the person's action in that state, $y_t^p$. The loss is computed as the R\'{e}nyi divergence~\cite{zyczkowski2003renyi} between the predicted action, $\hat{y}_t^p$, and the true action, $y_t^p$. This loss is then backpropagated through the network to update model parameters $\theta$ and the personalized embedding $\omega$ via stochastic gradient descent. \begin{wrapfigure}{r}{0.5\textwidth} \begin{center} \includegraphics[width=0.48\textwidth]{images/BNN_Diagram} \end{center} \caption{Personalized Neural Network Diagram.} \label{fig:my_pnn} \end{wrapfigure} When applying the algorithm during runtime (i.e., testing) for a new human demonstrator, $p'$, one updates the embedding, $\omega_{p'}$; however, the network's parameters, $\theta$, remain static. The personalized embedding, $\omega_{p'}$, for a new human demonstrator is initialized to the mean personalized embedding. This means during runtime, we start by assuming a new expert is performing the planning task in the predicted manner; over time, we infer how she is acting differently and update our personalized embedding accordingly. This hybrid approach enables one to balance the bias-variance tradeoff, grounding the model in parameters common to all demonstrators via $\theta$ while tailoring a subset of the parameters, $\omega$, to tune the model for an individual. We note that researchers have explored the use of a latent embedding in other contexts. For example, \citet{DBLP:conf/aaai/KillianKD17} applied a Bayesian Neural Network to model transition dynamics. \citet{tani_parametric_bias} utilized a similar personalized embedding in a recurrent neural network but learns through imitative interaction in a domain with fewer degrees of freedom primarily concerned with mimicking motion rather than decision-making for planning and scheduling. Recent work by \citet{Angelov2019} uses causal analysis to learn specifications from task demonstrations, but assumptions are made regarding the number of demonstrator types and the work requires prior labeling of a demonstrator set. Our approach is novel in that it utilizes a latent embedding as a personalized embedding for apprenticeship learning in domains with a high degree of freedom while also automatically inferring behavior, eliminating the need for tedious and biased annotation of person types. \paragraph{Counterfactual Reasoning} To increase the utility of our learning framework, we draw inspiration from the domain of web page ranking \cite{Pageetal98}, where the goal is to predict the most relevant web page given a search query. Web page ranking must learn how pages relate to one another and capture these complex dependencies. These dependencies are also apparent in many complex planning problems, such as in the scheduling domain where there are tasks related to precedence, wait, and deadline constraints. The pairwise approach to web page ranking determines a ranking based on pairwise comparisons between individual pages \cite{Jin:2008:RRA:1367497.1367552, rank_pahikala}. Utilizing this methodology, we can apply counterfactual reasoning between the factual (action taken) and the counterfactual (action not taken) to learn a ranking formulation to predict which action the expert would ultimately take at each moment. \citet{Gombolay:2016a} presented evidence that learning a pairwise preference model by comparing pairs of actions can outperform a multi-class classification model. However, this paper is the first to our knowledge to apply counterfactual reasoning in personalized apprenticeship learning. \par\nobreak{\parskip0pt\noindent \begin{align} z_{a,a'}^{t,p} \coloneqq{}& [\omega_p,\bar{x}^t,x_a^t- x_{a'}^t], y_{a,a'}^t = 1 \label{eq: pairwise1}\\ z_{a',a}^{t,p} \coloneqq{}& [\omega_p,\bar{x}^t,x_{a'}^t- x_{a}^t], y_{a',a}^t = 0 \label{eq: pairwise2} \end{align}}The framework for generating counterfactuals through pairwise comparisons is shown in Equations \ref{eq: pairwise1}-\ref{eq: pairwise2}. At each timestep, we observe the decision, $a$, person $p$ made at time $t$. From each observation, we then extract 1) the feature vector describing that action, $x_a^t$, from state $s_t$, 2) the corresponding feature, $x_{a'}^t$ for an alternative action, $a' \in A | a' \neq a$, 3) a contextual feature vector capturing features common to all actions (e.g., how many workers are available to be assigned jobs), $\bar{x}^t$, and 4) the person's embedding, $\omega_p$. We note that each demonstrator has their own embedding which is updated through backpropagation during training. The comparison of the action the decision-maker took, $a$, versus the action not taken, $a' \neq a$, is considered a positive example for a classifier. Likewise, the reverse comparison is a negative example. This process generates $2(|A|-1)$ examples for each time step and is repeated for all users and all trajectory demonstrations. Given this data set, the apprentice is trained to output a psuedo-probability, $f(a,a',p)$ of action $a$ being taken over action $a'$ at time $t$ by the human decision-maker described by embedding $\omega_p$, using features $z_{a,a'}^{t,p}$. To predict the probability of taking action $a$ at time t, we marginalize over all other actions, as shown in Equation \ref{eq:marg}. Finally, the action prediction is the argmax this probability. \par\nobreak{\parskip0pt\noindent \begin{align} \hat{P}(a|t,p) &= \frac{\sum_{a'\in A} f(a,a',p)}{\sum_{a' \in A}\sum_{a''\in A} f(a',a'',p)} \label{eq:marg} \end{align}}\paragraph{Generating Action-Specific Features}In many cases, the action-specific features may not be readily available. In this case, we can choose to learn these features using a variation of this framework, where instead of an embedding personalized to the current demonstrator, the embedding is personalized to a particular action. In this way we can learn a mapping $\pi_\psi: S_t \times \Omega_A \to S_{t+1}$. This represents the transition model for the environment, and we can learn an action representation $\omega_a$ for each action. These action embeddings can then be used in the pairwise approach discussed above. We apply this method for the StarCraft II environment with great success. \subsection{Personalized Differentiable Decision Tree} \label{sub:PDDT_Approach} While a PNN provides us with high-performance models of demonstrator preferences, standard deep network models lack straightforward interpretability. Interpretability is an important area of exploration in machine learning, and an interpretable model of resource allocation or planning tasks would be useful for a variety of reasons, from decision explanations to training purposes. Therefore, we present a personalized differentiable decision tree (PDDT) model that is able to approximate PNN performance, while also giving us interpretability. Differentiable decision trees (DDTs) \cite{suarez1999globally} have provided researchers in various fields with simple and powerful models for constructing fuzzy decision trees \cite{yuan1995induction} through differentiation. Our approach begins with a balanced DDT and a demonstrator embedding, as in the PNN. The demonstrator embedding is concatenated with input data $\vec{x} \in X$ and routed directly to each decision node, rather than being transformed between nodes as in a traditional deep network architecture. While this hinders the representation learning capacity of our model, it is important to learn a model directly over input features to preserve interpretability. Each decision node in the PDDT is conditioned on three parameters: a vector of weights $\vec{w} \in W$, a vector of comparison values $\vec{c} \in C$, and a vector of selective importances $\vec{s} \in S$. When input data $\vec{x}$ is passed to a decision node $D_i$, the data is weighted by $\vec{w_i}$ and compared against $\vec{c_i}$. By using a vector for comparison values, we can perform element-wise comparison for each input feature, allowing the model to learn easily translatable rules for how to consider each individual element of $\vec{x}$. After comparison against $\vec{c_i}$, the model then uses its selective importance vector $\vec{s_i}$ to decide which feature matters the most for $D_i$. The maximum value in $\vec{s_i}$ is set to 1, while all other elements of $\vec{s_i}$ are set to 0, and the transformed input data is then element-wise multiplied by $\vec{s_i}$. This procedure ensures that each decision node only considers a single feature during each forward pass but still allows the model to learn over all features during backpropagation. The single transformed feature is then weighted by a learned feature $\alpha$ and passed through a sigmoid activation function. The sigmoid function ensures that each decision node $D_i$ outputs a value between 1 and 0, where 1 means the $D_i$ evaluates to "true", and 0 means that $D_i$ evaluates to "false." The learned feature $\alpha$ enables the PDDT tree to control the steepness of the sigmoid function. Each decision node $D_i$ evaluates the the sigmoidal approximation of a decision boundary, $D_i = \sigma [\alpha(\vec{s_i} \cdot ((\vec{w_i} \cdot \vec{x}) - \vec{c_i}))]$. Leaf nodes $L_i$ in the PDDT maintain a set of weights over each output class and have exactly one path from root to leaf $L_i$. Decision nodes along the path output probabilities, which are all multiplied to produce the final probability of reaching $L_i$ given input $\vec{x}$ and the current demonstrator embedding. The set of weights in $L_i$ is then weighted by this probability, and the weighted output of all leaves is summed to produce the final network output. \begin{wrapfigure}{r}{0.5\textwidth} \begin{center} \includegraphics[width=0.5\textwidth]{images/fuzzy_to_crispy.png} \end{center} \caption{A two-leaf PDDT to an interpretable decision tree.} \label{fig:pddt_fuzzy_to_crisp} \end{wrapfigure} To achieve interpretability, we translate a PDDT to a decision tree through using the selective importance parameters $\vec{s}$. Every decision node $D_i$ in the PDDT outputs a decision based on a single feature, chosen by $\vec{s_i}$; therefore, we can use $\vec{s_i}$ to choose which feature, weight, and comparison should be used to instantiate a new decision node for the interpretable decision tree. We can also remove the probabilistic weighting of leaves by pushing $\alpha$ towards infinity, restricting every decision’s output to 1 or 0. Finally, the class output within each leaf is chosen as the maximum value of the leaf's weights. The new model is then a decision tree where every node considers one feature and outputs 1 or 0, only one leaf is selected for each forward pass, and each leaf outputs a single class. \section{Environments} We use three environments to evaluate the utility of our personalized apprenticeship learning framework. In the synthetic low-dimensional environment, we perform tests to show the advantage of our framework and a case study displaying the need for PDDTs. In the synthetic scheduling environment, we test the capability of our apprenticeship learning framework to learn heterogeneous scheduling policies. Finally, in StarCraft II, we test the apprentice models on a real-world gameplay dataset and present a result showing the utility of interpretability. Our approaches and implementations are available at https://github.com/ghost12331/Personalized-Apprenticeship-Learning-from-Heterogeneous-Decision-Makers. Hyper-parameter settings are provided in the supplementary material. \subsection{Synthetic Low-Dimensional Environment} The synthetic low-dimensional environment represents a simple domain where an expert will choose an action based on the state and one of two hidden heuristics. This domain captures the idea that we have homogeneity in conforming to constraints (z) and strategies or preferences (heterogeneity) in the form of $\lambda$. The idea is that decision-making exists on a manifold for each "mode" or "strategy" an operator shows, and we need to infer the identity of these manifolds through the embedding. Demonstration trajectories are given in sets of 20 (which we denote a schedule), where each observation consists of $x^t \in {0,1} $ and $z^t \in \mathcal{N}(0,1) $ and the output is $y^t$. Exact specifications for the computation of the label given by the observation of $y = x*\mathds{1}_{(z >= 0 \land \lambda = 1) \lor (z < 0 \land \lambda = 2)}$, where $\mathds{1}$ is the indicator function. Assuming a near-even class distribution, randomly guessing and overfitting to one class results in about 50\% accuracy. Only by inferring the type of demonstrator, given by $\lambda_p \in \{1,2\}$, will the apprentice be able to achieve an accurate model of decision-making. \subsection{Synthetic Scheduling Environment} The next environment we use to explore our personalized learning framework is a synthetic environment that we can control, manipulate, and interpret to empirically validate the efficacy of our proposed method. For our investigation, we leverage a jobshop scheduling environment built upon the XD[ST-SR-TA] scheduling domain defined by \citet{Korsah-2011-7217}, representing one of the hardest scheduling problems. In this environment, two agents must complete a set of twenty tasks which have upper- and lower-bound temporal constraints (i.e., deadlines and wait constraints), proximity constraints (i.e., no two agents can be in the same place at the same time), and travel-time constraints. For the purposes of apprenticeship learning, an action is defined as the assignment of an agent to complete a task presently. The decision-maker must decide the optimal sequence of actions according to the decision-maker's own criteria. For this environment, we construct a set of heterogeneous, mock decision-makers that select scheduling actions according to Equation \ref{eq:blending}. \par\nobreak{\parskip0pt\noindent} \begin{align} \tau_i^* =& \argmax_{\tau_{j} \subset \boldsymbol{{\tau_S}}} \left(\beta_1 *H_{EDF}(\tau_j) +\beta_2 * H_{distance}(\tau_j) +H_{Index}(\tau_j,\beta_3)\right) \label{eq:blending} \end{align} In this equation, our decision-maker selects a task, $\tau_i^*$ from the set of tasks, $\boldsymbol{\tau_S}$. The task-prioritization scheme is based upon three criteria: $H_{EDF}$ prioritizes tasks according to their deadline (i.e., ``earliest-deadline first"), $H_{distance}$ prioritizes the closest task, and $H_{Index}$ prioritizes tasks according to a user-specified highest/lowest index or value based upon $\beta_3$ (i.e., $\beta_3 (j) + (1-\beta_3)(-j)$). The heterogeneity in decision-making comes from the latent weighting vector $\vec{\beta}$. Specifically, $\beta_1\in \mathbb{R}$ and $\beta_2\in \mathbb{R}$ weight the importance of $H_{EDF}$ and $H_{distance}$, respectively. Furthermore, $\beta_3 \in \{0,1\}$ is a mode selector in which the highest/lowest task index is prioritized. By drawing $\vec{\beta}$ from a multivariate random distribution, we can create an infinite number of unique demonstrator types. \subsection{StarCraft II} In our third environment, we leverage a real-world dataset with gameplay from StarCraft II. This data is provided alongside the StarCraft II API PySC2 \citep{vinyals2017starcraft}. The dataset contains a large number of 1-vs.-1 replays that affords access to game state-action information at every frame, information regarding the outcome of the game, and the ranking of the players. The state of the game at any timestep within the gameplay trajectory (i.e., demonstration) consists of several images pertaining to where units and buildings are located alongside information about visibility regions and vectorized state information regarding the amount of resources, buildings, and units in the game. The action taken in every frame can be one of hundreds, and thus as a simplification, we produce 40 actions that are a representative super-class of refined actions. \section{Results and Discussion} We evaluate the performance of our apprenticeship learning framework against related approaches and assess the power of counterfactual reasoning against two baselines: 1) \emph{Pointwise} -- each action is considered independently with a positive example assigned to an action taken and a negative example assigned to an action not taken, which is another type of model from web-page ranking~\cite{page1999pagerank} and 2) \emph{Standard} -- the model must select from $A$ which action is taken (i.e., a multi-class classification problem), which is the ubiquitous approach in policy-learning~\cite{silver2016mastering}. Finally, we explore queries related to interpretability that support the significance of our approach. \subsection{Synthetic Low-Dimensional Environment} A set of 50 schedules are given as input to the apprenticeship learning framework specified above. Several approaches are used in a thorough comparison between our personalized approach and those previous. We test a standard decision tree (DT), a standard neural network (NN), a differentiable decision tree (DDT), a neural network trained on homogeneous clusters generated through k-means clustering \cite{Nikolaidis:2015:EML:2696454.2696455} (k-means to NN), a neural network trained on soft clusters generated through a Gaussian Mixture Model (GMM to NN), a Personalized Differentiable Decision Tree (PDDT), and a Personalized Neural Network (PNN). \begin{figure*} \centering \begin{subfigure}[t]{0.5\textwidth} \centering \includegraphics[width = 0.9\textwidth,height=2in]{images/toy_env_results_acc.png} \caption{} \label{fig:toy_env_results} \end{subfigure}% \begin{subfigure}[t]{0.5\textwidth} \centering \includegraphics[width = 0.9\textwidth,height=2in]{images/scheduling_acc.png} \caption{} \label{fig:sched_results} \end{subfigure} \caption{Performance in the low-dimension (left) and the scheduling (right) environments.} \end{figure*} We also consider training a decision tree in which we infer embeddings using a Monte Carlo sampling so that a decision tree is given a univariate embedding sampled from a bimodal distribution, which is iteratively updated based on the tree's performance as the distribution changes. This expectation maximization procedure allows us to compare the capability of another personalized embedding-based approach. However, this approach requires the number of modes (types) of domain experts within the domain to be known in advance (in this case, 2), which is a limiting condition to the utility of this approach. We first initialize the probability that a domain expert is of type 1 and type 2 to random. Then, for a training schedule, it appends the embedding (which is a one-hot encoding of the type i.e., [1,0] or [0,1]) to the input and trains a decision tree classifier upon this. Then, this classifier is used to predict the outcome on the rest of the samples in that schedule and is penalized by its incorrectness. Repeating this process allows for the embeddings to converge to their proper values. Figure \ref{fig:toy_env_results} shows the personalized apprenticeship learning frameworks--specifically, the PDDT and PNN--outperform conventional approaches to apprenticeship learning. It should be noted that we expected a DT with bimodal embedding to perform as well as the personalized apprenticeship framework, as the MCMC sampling-based update allows for the embedding of the expert to be inferred. We hypothesize that the reason that the performance is not comparable to that of the PDDT or PNN is due to the invariability in the outputs of a decision tree. \subsection{Synthetic Scheduling environment} A set of 150 schedules generated by heterogeneous domain experts are given as input to the apprenticeship learning framework specified above. This consists of 3000 individual timesteps that the framework must be able to learn from. While we have the capability to generate a larger number of schedules, it is more significant to show that our apprenticeship learning framework works well on smaller training datasets as in many cases these demonstrations can be expensive or sparse. The efficacy of each approach is shown in Figure \ref{fig:sched_results}. It can be seen that the personalized apprenticeship learning frameworks that utilize counterfactual reasoning outperforms all other approaches, achieving near perfect accuracy in predicting what task a domain expert will schedule. These results show that the personalized apprenticeship learning framework can learn from observations in a high-dimensional and complex environment with heterogeneous demonstrators. \begin{wrapfigure}{r}{0.45\textwidth} \begin{center} \includegraphics[width = .45\textwidth]{images/sc_loss.png} \end{center} \caption{Performance in StarCraft II.} \label{fig:sc_loss} \end{wrapfigure} \subsection{StarCraft II} A set of real-world gameplay data from StarCraft II is used to further verify our claim. This environment has higher dimensionality and is a multi-label classification task \cite{Tsoumakas07multi-labelclassification:}: multiple actions can be taken in a single time step, increasing the challenge of inferring a high-quality policy. Based on the relative performance of the various methods tested on the synthetic domains -- with PNN and PDDTs outperforming the baselines -- we evaluate a neural network learning for multi-class classification of actions as well as neural network, a PNN, and PDDT using counterfactual reasoning via pairwise comparisons. We find that the PDDT and PNNs again outperform our baselines, as shown in Figure \ref{fig:sc_loss}, on a data set of human decision-making on a complex planning problem. \subsection{Interpretability} The results of our empirical evaluations support the hypothesis that personalized embeddings allow for learning a powerful representation of heterogeneous domain experts. However, we want not just an accurate model, but also one that lends insight into the demonstrator's decision-making process. In section \ref{sub:PDDT_Approach}, we proposed a differentiable decision tree architecture that would provide the novel ability for apprenticeship learning with personalized embeddings for heterogeneous demonstrators in a tree-like architecture. With the ability to readily translate a PDDT to a classical decision tree with interpretable decision boundaries, this model offers much promise so long as we do not empirically lose a substantial amount of accuracy through the conversion process. To assess the efficacy of learning interpretable decision trees with personalized embeddings through the PDDT, we conduct the following experiment for the synthetic, low-dimensional environment. First, we train a PNN over a set of training data; next, we extract the learned embeddings and train a traditional DT with the training data and paired embeddings. Third, we run the PNN on the test set to infer the ``correct'' embeddings and provide these inferred embeddings to the DT along with the test demonstration examples for the sake of classification. In addition to this PNN-DT hybrid approach, we report the accuracy of the PNN provided with these PNN-extracted embeddings. Table \ref{table:interpretability_toy} shows the advantage of using a PDDT. While an uninterpretable PNN can achieve higher accuracy, the DT constructed from PNN embeddings performs much worse than any other approach. Positively, the conversion from continuous PDDT to discrete PDDT incurs a low penalty and the resulting model is much better than the DT given PNN embeddings. This result is intuitive in that jointly learning the hard constraints of the problem with the demonstrator embedding leads to performance gains versus simply learning the embeddings separately and then attempting to build an independent interpretable model. In a real-world dataset of StarCraft II, generating a discrete PDDT from a continuous PDDT incurs a relatively small penalty, confirming that we able to generate interpretable models in complex domains without sacrificing performance. We note that it is possible to achieve perfect accuracy for the synthetic environments as we do not introduce artificial noise. Figure \ref{fig:interpretable_model} shows an interpretable model that can be generated from the PDDT, for the low-dimensional environment. Given a set of observations from decision-makers, our personalized framework can generate an interpretable model that will display the behavior of each decision-maker, allowing us to inspect each individual demonstrator's style. If a decision node is conditioned on the demonstrator embedding and leads to a set of actions of type A when the decision evaluates to true and of type B otherwise, we can say that demonstrators with embeddings that satisfy the decision node stylistically prefer actions of type A (causal reasoning). \begin{figure} \centering \includegraphics[width=.6\textwidth, height = 1.2in]{images/pddt_discrete.png} \caption{This figure depicts the learned PDDT model after translation to an interpretable form for the low-dimensional environment, achieving $89.15\%$ accuracy.} \label{fig:interpretable_model} \vspace{-0.4cm} \end{figure} \begin{table}[t] \centering \caption{This table reports the results of our intepretability investigation. A asterisk denotes the interpretable models, and the performance of the best of the interpretable models is bolded.} \begin{tabular}{lccc} \toprule Model & Low-Dimensional & Scheduling & StarCraft II (Average Loss) \\ \midrule *Discrete PDDT & \textbf{89.15\%} & \textbf{100.00 \%} & \textbf{0.0985} \\ *DT (PNN Embeddings) & 77.70\% & 17.65 \% & --------\\ \hline Continuous PDDT & 94.79\% & 100.00 \% & 0.0960 \\ PNN & 95.65 \% & 99.80 \% & 0.0866 \\ \bottomrule \end{tabular} \label{table:interpretability_toy} \vspace{-0.3cm} \end{table} \vspace{-0.3cm} \section{Conclusion} \vspace{-0.2cm} We present a new apprenticeship learning framework for learning from heterogeneous demonstrators, leveraging PNNs and PDDTs to learn task models from large datasets, while still being able to predict individual demonstrator preferences. We demonstrate that our approach is superior to standard NN and DDT models, which fail to capture individual demonstrator styles, and that our counterfactual reasoning approach to actions is superior to a standard action prediction approach, allowing us to achieve near-perfect accuracy in predicting demonstration trajectories of domain experts in a scheduling problem. Finally, we introduce two methods to extract an interpretable model for demonstrator preferences and task constraints, show that conversion from a differentiable PDDT into a discrete, interpretable PDDT offers performance gains over attempting to construct an interpretable model with an independent set of demonstrator embeddings and task examples, and underline ways that this interpretability can highlight differences in demonstrator styles. \small \bibliographystyle{named}
{'timestamp': '2019-06-18T02:02:40', 'yymm': '1906', 'arxiv_id': '1906.06397', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06397'}
arxiv
\section{Introduction} The goal of {\bf automatic post-editing}~\citep[APE;][]{simard2007rule} is to automatically correct the mistakes produced by a black-box machine translation (MT) system. APE is particularly appealing for rapidly customizing MT, avoiding to train new systems from scratch. Interfaces where human translators can post-edit and improve the quality of MT sentences~\citep{Alabau2014,Federico2014,Denkowski2015,Hokamp2018} are a common data source for APE models, since they provide {\bf triplets} of {\it source} sentences ({\tt src}), {\it machine translation} outputs ({\tt mt}), and {\it human post-edits} ({\tt pe}). Unfortunately, human post-edits are typically scarce. Existing APE systems circumvent this by generating {\bf artificial triplets}~\citep{junczys2016log, negri2018escape}. However, this requires access to a high quality MT system, similar to (or better than) the one used in the black-box MT itself. This spoils the motivation of APE as an alternative to large-scale MT training in the first place: the time to train MT systems in order to extract these artificial triplets, combined with the time to train an APE system on the resulting large dataset, may well exceed the time to train a MT system from scratch. Meanwhile, there have been many successes of {\bf transfer learning} for NLP: models such as CoVe~\citep{mccann2017learned}, ELMo~\citep{peters2018deep}, OpenAI GPT~\citep{radford2018improving}, ULMFiT~\citep{howard2018universal}, and BERT~\citep{devlin2018bert} obtain powerful representations by training large-scale language models and use them to improve performance in many sentence-level and word-level tasks. However, a language generation task such as APE presents additional challenges. In this paper, we build upon the successes above and show that {\bf transfer learning is an effective and time-efficient strategy for APE}, using a pre-trained BERT model. This is an appealing strategy in practice: while large language models like BERT are expensive to train, this step is only done once and covers many languages, reducing engineering efforts substantially. This is in contrast with the computational and time resources that creating artificial triplets for APE needs---these triplets need to be created separately for every language pair that one wishes to train an APE system for. Current APE systems struggle to overcome the MT baseline without additional data. This baseline corresponds to leaving the MT uncorrected (``do-nothing'' baseline).\footnote{If an APE system has worse performance than this baseline, it is pointless to use it.} With only the small shared task dataset (23K triplets), our proposed strategy outperforms this baseline by $-$4.9 TER and $+$7.4 BLEU in the English-German WMT 2018 APE shared task, with 3 hours of training on a single GPU. Adding the artificial eSCAPE dataset~\citep{negri2018escape} leads to a performance of 17.15 TER, a new state of the art. Our main contributions are the following: \begin{itemizesquish} \item We combine the ability of BERT to handle {\bf sentence pair inputs} together with its pre-trained multilingual model, to use both the {\tt src} and {\tt mt} in a {\bf cross-lingual encoder}, that takes a multilingual sentence pair as input. \item We show how pre-trained BERT models can also be used and fine-tuned as the {\bf decoder} in a language generation task. \item We make a thorough empirical evaluation of different ways of coupling BERT models in an APE system, comparing different options of parameter sharing, initialization, and fine-tuning. \end{itemizesquish} \section{Automatic Post-Editing with BERT}\label{sec:ape_bert} \subsection{Automatic Post-Editing} APE~\citep{simard2007rule} is inspired by human post-editing, in which a translator corrects mistakes made by an MT system. APE systems are trained from triplets ({\tt src}, {\tt mt}, {\tt pe}), containing respectively the source sentence, the machine-translated sentence, and its post-edited version. \paragraph{Artificial triplets.} Since there is little data available (e.g WMT 2018 APE shared task has 23K triplets), most research has focused on creating artificial triplets to achieve the scale that is needed for powerful sequence-to-sequence models to outperform the MT baseline, either from ``round-trip'' translations~\citep{junczys2016log} or starting from parallel data, as in the eSCAPE corpus of \newcite{negri2018escape}, which contains 8M synthetic triplets. \paragraph{Dual-Source Transformer.} The current state of the art in APE uses a Transformer~\citep{vaswani2017attention} with {\bf two encoders}, for the {\tt src} and {\tt mt}, and {\bf one decoder}, for {\tt pe}~\citep{junczys2018ms, tebbifakhr2018multi}. When concatenating human post-edited data and artificial triplets, these systems greatly improve the MT baseline. However, little successes are known using the shared task training data only. By contrast, with transfer learning, our work outperforms this baseline considerably, even without any auxiliary synthetic dataset; and, as shown in \S\ref{sec:experiments}, it achieves state-of-the-art results by combining it with the aforementioned artificial datasets. \begin{figure}[htbp] \centering \includegraphics[width=\columnwidth]{diagram_8-dashed.pdf} \caption{\textbf{Dual-Source BERT.} Dashed lines show shared parameters in our best configuration.} \label{fig:transformer_diagram} \end{figure} \subsection{BERT as a Cross-Lingual Encoder} Our transfer learning approach is based on the Bidirectional Encoder Representations from Transformers~\citep[BERT;][]{devlin2018bert}. This model obtains deep bidirectional representations by training a Transformer~\citep{vaswani2017attention} with a large-scale dataset in a masked language modeling task where the objective is to predict missing words in a sentence. We use the BERT\textsubscript{BASE} model, which is composed of $L=12$ self-attention layers, hidden size $H=768$, $A=12$ attention heads, and feed-forward inner layer size $F=3072$. In addition to the word and learned position embeddings, BERT also has {\bf segment embeddings} to differentiate between a segment A and a segment B---this is useful for tasks such as natural language inference, which involve two sentences. In the case of APE, there is also a pair of input sentences ({\tt src}, {\tt mt}) which are in different languages. Since one of the released BERT models was jointly pre-trained on 104 languages,\footnote{ \url{https://github.com/google-research/bert/blob/master/multilingual.md}} we use this multilingual BERT pre-trained model to encode the bilingual input pair of APE. Therefore, the whole encoder of our APE model is the multilingual BERT: we encode both {\tt src} and {\tt mt} in the same encoder and use the segment embeddings to differentiate between languages (Figure~\ref{fig:transformer_diagram}). We reset positional embeddings when the {\tt mt} starts, since it is not a continuation of {\tt src}. \subsection{BERT as a Decoder}\label{sec:ape_bert_decoder} Prior work has incorporated pre-trained models in {\it encoders}, but not as {\bf decoders} of sequence-to-sequence models. Doing so requires a strategy for generating fluently from the pre-trained model. Note that the bidirectionality of BERT is lost, since the model cannot look at words that have not been generated yet, and it is an open question how to learn decoder-specific blocks (e.g. context attention), which are absent in the pre-trained model. One of our key contributions is to use BERT in the decoder by experimenting different strategies for initializing and sharing the self and context attention layers and the positionwise feed-forward layers. We tie together the encoder and decoder embeddings weights (word, position, and segment) along with the decoder output layer (transpose of the word embedding layer). We use the same segment embedding for the target sentence ({\tt pe}) and the second sentence in the encoder ({\tt mt}) since they are in the same language. The full architecture is shown in Figure~\ref{fig:transformer_diagram}. We experiment with the following strategies for coupling BERT pre-trained models in the decoder: \begin{itemizesquish} \item \textbf{Transformer.} A Transformer decoder as described in \newcite{vaswani2017attention} without any shared parameters, with the BERT\textsubscript{BASE} dimensions and randomly initialized weights. \item \textbf{Pre-trained BERT.} This initializes the decoder with the pre-trained BERT model. The only component initialized randomly is the context attention (CA) layer, which is absent in BERT. Unlike in the original BERT model---which only encodes sentences---a mask in the self-attention is required to prevent the model from looking to subsequent tokens in the target sentence. \item \textbf{ BERT initialized context attention.} Instead of a random initialization, we initialize the context attention layers with the weights of the corresponding BERT self-attention layers. \item \textbf{Shared self-attention}. Instead of just having the same initialization, the self-attentions (SA) in the encoder and decoder are tied during training. \item \textbf{Context attention shared with self-attention.} We take a step further and \emph{tie} the context attention and self attention weights---making all the attention transformation matrices (self and context) in the encoder and decoder tied. \item \textbf{Shared feed-forward.} We tie the feed-forward weights (FF) between the encoder and decoder. \end{itemizesquish} \section{Experiments} \label{sec:experiments} We now describe our experimental results. Our models were implemented on a fork of OpenNMT-py~\citep{klein2017opennmt} using a Pytorch~\citep{paszke2017automatic} re-implementation of BERT.\footnote{\url{https://github.com/huggingface/pytorch-pretrained-BERT}} Our model's implementation is publicly available.\footnote{\url{https://github.com/deep-spin/OpenNMT-APE}} \paragraph{Datasets.} We use the data from the WMT 2018 APE shared task~\citep{Chatterjee2018} (English-German SMT), which consists of 23,000 triplets for training, 1,000 for validation, and 2,000 for testing. In some of our experiments, we also use the eSCAPE corpus~\citep{negri2018escape}, which comprises about 8M sentences; when doing so, we oversample 35x the shared task data to cover $10\%$ of the final training data. We segment words with WordPiece~\citep{wu2016google}, with the same vocabulary used in the Multilingual BERT. At training time, we discard triplets with 200+ tokens in the combination of {\tt src} and {\tt mt} or 100+ tokens in {\tt pe}. For evaluation, we use TER~\cite{snover2006study} and tokenized BLEU~\cite{papineni2002bleu}. \begin{table}[htbp] \small \centering \begin{tabular}{lcc} \toprule & TER$\downarrow$ & BLEU$\uparrow$ \\ \midrule Transformer decoder & 20.33 & 69.31 \\ Pre-trained BERT & 20.83 & 69.11 \\ \hspace{1ex}\textcolor{gray}{\textit{with}} CA $\leftarrow$ SA & 18.91 & 71.81 \\ \textover[r] {\hspace{1ex}\textcolor{gray}{\textit{and}}}{\hspace{1ex}\textit{with}} \textover[r] {SA $\leftrightarrow$} {CA $\leftarrow$} Encoder SA & \textbf{18.44} & \textbf{72.25} \\ \textover[r] {\hspace{1ex}\textcolor{gray}{\textit{and}}}{\hspace{1ex}\textit{with}} \textover[r] {CA $\leftrightarrow$}{CA $\leftarrow$} SA & 18.75 & 71.83 \\ \textover[r] {\hspace{1ex}\textcolor{gray}{\textit{and}}}{\hspace{1ex}\textit{with}} \textover[r] {FF $\leftrightarrow$}{CA $\leftarrow$} Encoder FF & 19.04 & 71.53 \\ \bottomrule \end{tabular} \caption{ Ablation study of decoder configurations, by gradually having more shared parameters between the encoder and decoder (trained without synthetic data). $\leftrightarrow$ denotes parameter tying and $\leftarrow$ an initialization. } \label{tab:ablation_smt} \end{table} \begin{table*}[htbp!] \small \centering \begin{tabular}{lccccccc} \toprule & & \multicolumn{2}{c}{test 2016} & \multicolumn{2}{c}{test 2017} & \multicolumn{2}{c}{test 2018} \\ \cmidrule{3-4} \cmidrule{5-6} \cmidrule{7-8} Model & Train Size & TER$\downarrow$ & BLEU$\uparrow$ & TER$\downarrow$ & BLEU$\uparrow$ & TER$\downarrow$ & BLEU$\uparrow$ \\ \midrule MT baseline (Uncorrected) & & 24.76 & 62.11 & 24.48 & 62.49 & 24.24 & 62.99 \\ \midrule \newcite{berard2017lig} & \multicolumn{1}{c}{23K} & 22.89 & --- & 23.08 & 65.57 & --- & --- \\ \midrule \newcite{junczys2018ms} & \multicolumn{1}{c}{\multirow{2}{*}{5M}} & 18.92 & 70.86 & 19.49 & 69.72 & --- & --- \\ \newcite{junczys2018ms}$\times 4$ & \multicolumn{1}{c}{} & 18.86 & 71.04 & 19.03 & 70.46 & --- & --- \\ \midrule \newcite{tebbifakhr2018multi} & \multicolumn{1}{c}{\multirow{3}{*}{8M}} & --- & --- & --- & --- & 18.62 & 71.04 \\ \newcite{junczys2018ms} & \multicolumn{1}{c}{} & 17.81 & 72.79 & 18.10 & 71.72 & --- & --- \\ \newcite{junczys2018ms}$\times 4$ & \multicolumn{1}{c}{} & 17.34 & 73.43 & 17.47 & 72.84 & 18.00 & 72.52 \\ \midrule \midrule Dual-Source Transformer$^\dagger & \multicolumn{1}{c}{\multirow{4}{*}{23K}} & 27.80 & 60.76 & 27.73 & 59.78 & 28.00 & 59.98 \\ BERT Enc.\,+\,Transformer Dec. (\emph{Ours}) & \multicolumn{1}{c}{} & 20.23 & 68.98 & 21.02 & 67.47 & 20.93 & 67.60 \\ BERT Enc.\,+\,BERT Dec. (\emph{Ours}) & \multicolumn{1}{c}{} & 18.88 & 71.61 & 19.03 & 70.66 & 19.34 & 70.41 \\ BERT Enc.\,+\,BERT Dec. $\times 4$ (\emph{Ours}) & \multicolumn{1}{c}{} & \textbf{18.05} & \textbf{72.39} & \textbf{18.07} & \textbf{71.90} & \textbf{18.91} & \textbf{70.94} \\ \midrule BERT Enc.\,+\,BERT Dec. (\emph{Ours}) & \multicolumn{1}{c}{\multirow{2}{*}{8M}} & 16.91 & 74.29 & 17.26 & 73.42 & 17.71 & 72.74 \\ BERT Enc.\,+\,BERT Dec. $\times 4$ (\emph{Ours}) & \multicolumn{1}{c}{} & \textbf{16.49} & \textbf{74.98} & \textbf{16.83} & \textbf{73.94} & \textbf{17.15} & \textbf{73.60} \\ \bottomrule \end{tabular} \caption{Results on the WMT 2016--18 APE shared task datasets. Our single models trained on the 23K dataset took only 3h20m to converge on a single Nvidia GeForce GTX 1080 GPU, while results for models trained on 8M triplets take approximately 2 days on the same GPU. Models marked with ``$\times 4$'' are ensembles of 4 models. Dual-Source Transformer$^\dagger$ is a comparable re-implementation of \newcite{junczys2018ms}.} \label{tab:results_smt} \end{table*} \paragraph{Training Details.} We use Adam~\citep{kingma2014adam} with a triangular learning rate schedule that increases linearly during the first 5,000 steps until $5\times 10^{-5}$ and has a linear decay afterwards. When using BERT components, we use a $\ell_2$ weight decay of $0.01$. We apply dropout~\cite{srivastava2014dropout} with $p_{drop}=0.1$ to all layers and use label smoothing with $\epsilon=0.1$~\citep{pereyra2017regularizing}. For the small data experiments, we use a batch size of 1024 tokens and save checkpoints every 1,000 steps; when using the eSCAPE corpus, we increase this to 2048 tokens and 10,000 steps. The checkpoints are created with the exponential moving average strategy of \newcite{junczys2018marian} with a decay of $10^{-4}$. At test time, we select the model with best TER on the development set, and apply beam search with a beam size of 8 and average length penalty. \paragraph{Initialization and Parameter Sharing.} Table~\ref{tab:ablation_smt} compares the different decoder strategies described in \S\ref{sec:ape_bert_decoder} on the WMT 2018 validation set. The best results were achieved by sharing the self-attention between encoder and decoder, and by initializing (but not sharing) the context attention with the same weights as the self-attention. Regarding the self-attention sharing, we hypothesize that its benefits are due to both encoder and decoder sharing a common language in their input (in the {\tt mt} and {\tt pe} sentence, respectively). Future work will investigate if this is still beneficial when the source and target languages are less similar. On the other hand, the initialization of the context attention with BERT's self-attention weights is essential to reap the benefits of BERT representations in the decoder---without it, using BERT decreases performance when compared to a regular transformer decoder. This might be due to the fact that context attention and self-attention share the same neural block architecture (multi-head attention) and thus the context attention benefits from the pre-trained BERT's better weight initialization. No benefit was observed from sharing the feed-forward weights. \paragraph{Final Results.} Finally, Table~\ref{tab:results_smt} shows our results on the WMT 2016--18 test sets. The model named \emph{BERT Enc.\,+\,BERT Dec.} corresponds to the best setting found in Table~\ref{tab:ablation_smt}, while \emph{BERT Enc.\,+\,Transformer Dec.} only uses BERT in the encoder. We show results for single models and ensembles of 4 independent models. Using the small shared task dataset only (23K triplets), our single \emph{BERT Enc.\,+\,BERT Dec.} model surpasses the MT baseline by a large margin ($-$4.90 TER in test 2018). The only system we are aware to beat the MT baseline with only the shared task data is \citet{berard2017lig}, which we also outperform ($-$4.05 TER in test 2017). With only about 3 GPU-hours and on a much smaller dataset, our model reaches a performance that is comparable to an ensemble of the best WMT 2018 system with an artificial dataset of 5M triplets ($+$0.02 TER in test 2016), which is much more expensive to train. With 4$\times$ ensembling, we get competitive results with systems trained on 8M triplets. When adding the eSCAPE corpus (8M triplets), performance surpasses the state of the art in all test sets. By ensembling, we improve even further, achieving a final 17.15 TER score in test 2018 ($-$0.85 TER than the previous state of the art). \section{Related Work}\label{sec:related} In their Dual-Source Transformer model, \newcite{junczys2018ms} also found gains by tying together encoder parameters, and the embeddings of both encoders and decoder. Our work confirms this but shows further gains by using segment embeddings and more careful sharing and initialization strategies. \newcite{sachan2018parameter} explore parameter sharing between Transformer layers. However, they focus on sharing decoder parameters in a \emph{one-to-many} multilingual MT system. In our work, we share parameters between the encoder and the decoder. As stated in \S\ref{sec:experiments}, \citet{berard2017lig} also showed improved results over the MT baseline, using exclusively the shared task data. Their system outputs edit operations that decide whether to insert, keep or delete tokens from the machine translated sentence. Instead of relying on edit operations, our approach mitigates the small amount of data with transfer learning through BERT. Our work makes use of the recent advances in transfer learning for NLP~\citep{peters2018deep, howard2018universal, radford2018improving, devlin2018bert}. Pre-training these large language models has largely improved the state of the art of the GLUE benchmark~\citep{wang2018glue}. Particularly, our work uses the BERT pre-trained model and makes use of the representations obtained not only in the encoder but also on the decoder in a language generation task. More closely related to our work, \newcite{lample2019cross} pre-trained a BERT-like language model using parallel data, which they used to initialize the encoder and decoder for supervised and unsupervised MT systems. They also used segment embeddings (along with word and position embeddings) to differentiate between a pair of sentences in different languages. However, this is only used in one of the pre-training phases of the language model (translation language modelling) and not in the downstream task. In our work, we use segment embeddings during the downstream task itself, which is a perfect fit to the APE task. \newcite{lopes2019unbabels} used our model on the harder English-German NMT subtask to obtain better TER performance than previous state of the art. To obtain this result, the transfer learning capabilities of BERT were not enough and further engineering effort was required. Particularly, a conservativeness factor was added during beam decoding to constrain the changes the APE system can make to the {\tt mt} output. Furthermore, the authors used a data weighting method to augment the importance of data samples that have lower TER. By doing this, data samples that required less post-editing effort are assigned higher weights during the training loop. Since the NMT system does very few errors on this domain this data weighting is important for the APE model to learn to do fewer corrections to the {\tt mt} output. However, their approach required the creation of an artificial dataset to obtain a performance that improved the MT baseline. We leave it for future work to investigate better methods to obtain results that improve the baseline using only real post-edited data in these smaller APE datasets. \section{Conclusion and Future Work} We proposed a transfer learning approach to APE using BERT pre-trained models and careful parameter sharing. We explored various ways for coupling BERT in the decoder for language generation. We found it beneficial to initialize the context attention of the decoder with BERT's self-attention and to tie together the parameters of the self-attention layers between the encoder and decoder. Using a small dataset, our results are competitive with systems trained on a large amount of artificial data, with much faster training. By adding artificial data, we obtain a new state of the art in APE. In future work, we would like to do an extensive analysis on the capabilities of BERT and transfer learning in general for different domains and language pairs in APE. \section*{Acknowledgments} This work was supported by the European Research Council (ERC StG DeepSPIN 758969), and by the Funda\c{c}\~ao para a Ci\^encia e Tecnologia through contracts UID/EEA/50008/2019 and CMUPERI/TIC/0046/2014 (GoLocal). We thank the anonymous reviewers for their feedback.
{'timestamp': '2019-06-17T02:16:13', 'yymm': '1906', 'arxiv_id': '1906.06253', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06253'}
arxiv
\section{Introduction} \label{sec:intro} Instance segmentation is the task of classifying every object pixel into a category and discriminating between individual object instances. It has a wide variety of applications such as autonomous driving~\cite{cordts2016cityscapes}, scene understanding~\cite{lin2014microsoft, everingham2010pascal}, and medical imaging~\cite{pohle2001segmentation}. \begin{figure} \label{fig:overview} \begin{center} \includegraphics[width=\linewidth]{figures/inference.png} \end{center} \caption{{\bf WISE network.} Our method, WISE, is trained using point-level annotations only. At test time, WISE first uses L-Net to locate the objects in the image, and then uses E-Net to predict the masks of the located objects. Finally, the predicted masks are refined with the help of an object proposal method.} \end{figure} Most instance segmentation methods, such as Mask-RCNN~\cite{he2017mask} and MaskLab~\cite{chen2017masklab}, rely on per-pixel labels which requires huge human effort. For instance, obtaining labels for PASCAL VOC~\cite{everingham2010pascal} requires an average time of $239.7$ seconds per image~\cite{bearman2016s}. Other datasets with more objects to annotate such as CityScapes~\cite{cordts2016cityscapes} can take up to $1.5$ hours per image. Indeed, having a method that can train with weaker supervision can vastly reduce the required annotation cost. According to Bearman~\emph{et al.}~\cite{bearman2016s}, manually collecting image-level and point-level labels for the PASCAL VOC dataset took only $20.0$ and $22.1$ seconds per image, respectively. These annotation methods are an order of magnitude faster than acquiring full segmentation labels (see Figure~\ref{fig:annotation} for a comparison between the point-level and per-pixel annotation methods). For semantic segmentation, other forms of weaker labels were explored such as bounding boxes~\cite{khoreva2017simple}, scribbles~\cite{lin2016scribblesup}, and image-level annotation~\cite{Zhou2018PRM}. For instance segmentation, few works exist that use weak supervision~\cite{Zhou2018PRM, cholakkal2019object}. In this paper, we propose a Weakly-supervised Instance SEgmentation (WISE) network, the first to address this task with point-level annotations. WISE has two branches: (1) a localization network (L-Net) that predicts the location of each object; and (2) an embedding network (E-Net) that learns an embedding space where pixels of the same object are closer. L-Net is trained using a loss function that forces the network to output a single point per object instance. E-Net is trained using a similarity-based objective function to force the pixel embeddings to be similar within the same object mask. Since we do not have access to the ground-truth object masks, we instead use pseudo-masks generated by an object proposal method. These pseudo-masks belong to arbitrary objects and have no class labels and therefore cannot be directly applied for instance segmentation. At test time, L-Net first predicts the object locations. Second, E-Net outputs the embedding value for each pixel. Then the pixels with the most similar embeddings to an object's predicted pixel location become part of that object's mask (Figure~\ref{fig:overview}). \begin{figure}[t] \begin{center} \includegraphics[width=\linewidth]{figures/Figure2.png} \end{center} \caption{\textbf{Image annotation.} Point-level (top) and per-pixel (bottom) labels for COCO and the CityScapes datasets.} \label{fig:annotation} \end{figure} We summarize our contributions as follows: (1) we provide a first strong baseline for instance segmentation with point-level supervision; (2) we evaluate our method on a wide variety of datasets, including, PASCAL VOC~\cite{everingham2010pascal}, COCO~\cite{lin2014microsoft}, CityScapes~\cite{cordts2016cityscapes}, and KITTI~\cite{Geiger2012CVPR} datasets; (3) we obtain competitive results compared to fully-supervised methods; and (4) our method outperforms fully- and weakly- supervised methods when the annotation budget is limited. \section{Related Work} \label{sec:relatedwork} Our approach lies at the intersection of object localization, metric learning, object proposal methods, and instance segmentation. These topics have been studied extensively and we review the literature below. The novelty of our method is the combination of these techniques into a new setup, namely, instance segmentation with point-level supervision. \paragraph{Instance segmentation.} Instance segmentation is an important computer vision task that can be applied in many real-life applications~\cite{ren2017end, romera2016recurrent}. This task consists of classifying every object pixel into categories and distinguishing between object instances. Most methods follow a two step procedure~\cite{he2017mask, chen2017masklab, fu2019retinamask}, where they first detect objects and then segment them. For instance, Mask-RCNN~\cite{he2017mask} uses Faster-RCNN~\cite{ren2015faster} for detection and an FCN network~\cite{long2015fully} for segmentation. However, these methods require dense labels which leads to a high annotation time for new applications. \paragraph{Embedding-based instance segmentation.} Another class of instance segmentation methods obtain the object masks by grouping pixels based on a similarity measure. Notable works in this category include methods based on watershed~\cite{bai2017deep}, template matching~\cite{uhrig2016pixel} and associative embedding~\cite{newell2017associative}. Fathi~\emph{et al.}~\cite{fathi2017semantic} propose a grouping-based method that first learns the object locations and then learns the pixel embeddings in order to distinguish between object instances. These methods also require per-pixel labels which are costly to acquire for new applications. However, our method follows a similar procedure for obtaining the segmentation masks while requiring weaker supervision. \paragraph{Weakly supervised instance segmentation.} Per-pixel labels used by fully supervised instance segmentation methods require high annotation cost~\cite{everingham2010pascal, cordts2016cityscapes}. Therefore many weakly supervised methods have been explored for object detection~\cite{Tang2018ECCV, Bilen2016CVPR}, semantic segmentation~\cite{pinheiro2015image, kolesnikov2016seed, ahn2018learning, selvaraju2017grad} and instance segmentation~\cite{khoreva2017simple, Zhou2018PRM, cholakkal2019object}. Point-level annotation is one of the fastest ways to annotate object instances, albeit one of the least informative forms of weak supervision. However, they were shown to be effective for semantic segmentation~\cite{bearman2016s}. Inspired by their cost-effectiveness, we explore the novel problem setup of instance segmentation with point-supervision in this work. \paragraph{Object localization with point supervision.} An important step in instance segmentation is to locate objects of interest before segmenting them. One way to perform object localization is to use object detection methods~\cite{ren2015faster, yolov3}. However, these methods require bounding-box labels. In contrast, several methods exist that use weaker supervision to identify object locations~\cite{song2014learning, song2014weakly, lempitsky2010learning, li2018csrnet}. Close to our work is LCFCN~\cite{laradji2018blobs} which uses point-level annotations in order to obtain the locations and counts of the objects of interest. While this method gives accurate counts and identifies a partial mask for each instance, it does not produce accurate segmentation of the instances. We extend this method by using an embedding network that groups pixels that are most similar to the predicted object locations in order to obtain their masks. \begin{figure*}[t] \begin{center} \includegraphics[width=\linewidth]{figures/simple.png} \end{center} \caption{{\bf Training WISE.} Our method consists of a localization branch (L-Net) and an embedding branch (E-Net). During training, L-Net optimizes Eq.~\ref{eq:loss_lcfcn} in order to output a single point per object instance. E-Net optimizes Eq.~\ref{eq:loss_enet} in order to group pixels that belong to the same object instance.} \label{fig:WISE} \end{figure*} \paragraph{Object proposals.} Weakly supervised methods often rely on object proposals~\cite{hosang2016makes} to ease the task of detection~\cite{Tang2018ECCV, Bilen2016CVPR}, and segmentation~\cite{pinheiro2015image, bearman2016s, Zhou2018PRM, kolesnikov2016seed}. Object proposals are class-agnostic methods that can output thousands of object candidates per image and have received great progress over the last decade~\cite{uijlings2013selective, zitnick2014edge, arbelaez2014multiscale, maninis2016convolutional, pinheiro2015learning, pinheiro2016learning}. SharpMask~\cite{pinheiro2016learning} is a popular deep-learning based object proposal method that has been successfully applied to many weakly supervised computer vision problems. However, their output object masks cannot be directly used for instance segmentation as they belong to arbitrary objects and have no class labels. Our framework uses pseudo-masks generated by SharpMask. \section{Proposed Method} \label{sec:method} We address the problem of weakly-supervised instance segmentation, where each labeled object has a single point annotation. Our method, WISE network, has two output branches that share a common feature extraction backbone (Figure~\ref{fig:WISE}): (1) a localization branch (L-Net) that is trained for locating objects in the image, and (2) an embedding branch (E-Net) that outputs an embedding vector for each pixel. L-Net is trained using point-level annotations in order to output a single pixel for each object to represent its location and category in the image. On the other hand, E-Net is trained using pseudo-masks obtained by a pretrained proposal method. This allows E-Net to output an embedding vector for each pixel such that similar ones belong to the same object's pseudo-mask. Note that proposal methods have been widely used for different weakly-supervised problem setups~\cite{Zhou2018PRM, cholakkal2019object, Bilen2016CVPR, pinheiro2015image, bearman2016s} WISE obtains the mask of an object as follows. First, L-Net outputs a pixel label per object to identify its location, category, and instance. Then, the embedding of every pixel in the image is compared to the embedding of the pixels predicted by L-Net to identify which object instance they belong to. Finally, the pixels are grouped to form the object masks in the image. \subsection{Localization Branch (L-Net)} \label{ssec:lnet} The goal of L-Net is to obtain the locations and categories of the objects in the image. L-Net is based on LC-FCN~\cite{laradji2018blobs} which trains with point level annotations to produce a single blob per object. While this was originally designed for counting, it is able to locate objects effectively. LC-FCN is based on a semantic segmentation architecture that is similar to FCN~\cite{long2015fully}. Indeed, semantic segmentation methods are not suitable for instance segmentation as they often predict large blobs that merge several object instances together. LC-FCN addresses this issue by optimizing a loss function that ensures that only a single small blob is predicted around the center of each object. The location loss term $\mathcal{L}_L$ is described as: \begin{equation} \begin{split} \mathcal{L}_L &= \underbrace{\mathcal{L}_I(S,T)}_{\text{Image-level loss}} + \underbrace{\mathcal{L}_P(S,T)}_{\text{Point-level loss}}\\ &+ \underbrace{\mathcal{L}_S(S,T)}_{\text{Split-level loss}} + \underbrace{\mathcal{L}_F(S,T)}_{\text{False positive loss}}\;, \label{eq:loss_lcfcn} \end{split} \end{equation} where $T$ represent the point annotation ground-truth, and $S$ is LC-FCN's output mask. $\mathcal{L}_L$ consists of four terms: an image-level loss ($\mathcal{L}_I$) that trains the model to predict whether there is an object in the image; a point-level loss ($\mathcal{L}_P$) that encourages the model to predict a pixel for each object instance; a split-level ($\mathcal{L}_S$) and a false-positive ($\mathcal{L}_F$) loss that enforce the model to predict a single blob per instance (see~\cite{laradji2018blobs} for details for each of the loss components). Since LC-FCN's predicted blobs are too small to be considered as useful segmentation masks, we instead leverage the location of each blob by identifying the pixel with the highest probability of being foreground (Figure~\ref{fig:localization}). \begin{figure}[] \begin{center} \includegraphics[width=\linewidth]{figures/figure6.png} \end{center} \caption{{\bf Localization branch (L-Net).} L-Net's raw output is a small blob per predicted object (top). L-Net's final output is the set of pixels with the largest activation within their respective blobs (bottom). These pixels are used as input to E-Net at test time.} \label{fig:localization} \end{figure} \subsection{Embedding Branch (E-Net)} \label{sec:enet} The goal of E-Net is to produce object masks by grouping pixels with similar embeddings together. E-Net's architecture is based on FCN8~\cite{long2015fully}, which can output an embedding vector per image pixel. Using a similarity loss, E-Net learns to output similar embeddings for pixels that belong to the same object and dissimilar otherwise. This loss requires several points per object (including the background) in order to distinguish between different objects. While we do not have access to the ground-truth masks, we instead use pseudo-masks generated by an object proposal method to assign a mask for each object. E-Net learns a mapping from an input image to a set of embedding vectors of size $d$ for each pixel. Let $E_i$ and $E_j$ be the embeddings for pixel $i$ and pixel $j$, respectively. We measure the similarity between a pair of pixels using a squared exponential kernel function, similar to that of Fathi \emph{et al.}~\cite{fathi2017semantic}: \begin{equation} S(i, j) = \exp\Bigg({-\frac{||E_i-E_j||_2^2}{2d}}\Bigg)\;, \label{eq:similarity} \end{equation} where $S(E_i, E_j)$ tends to $1$ as $E_i$ and $E_j$ get closer, and tends to $0$ as they get farther in the embedding space. Note that our method can use other similarity functions as in~\cite{newell2017associative, fathi2017semantic, kong2018grouppixels}. Our goal is to train E-Net such that embeddings of pixel pairs belonging to the same object instance (\ie $y_i = y_j$) have the same embedding (\ie $S(i, j) = 1$) and to different object instances (\ie $y_i \neq y_j$) have different embeddings (\ie $S(i, j) = 0$). Therefore, E-Net minimizes the following loss function\footnote{Note that the $\log$ and $\exp$ cancel out in the first term of the equation but not the second term.}: \begin{align} \begin{split} \mathcal{L}_E = -\sum_{(i,j) \in P} \Big[&\mathbbm{1}_{\{y_i=y_j\}} \log{S(E_i, E_j)} \;\;+ \\& \mathbbm{1}_{\{y_i\neq y_j\}} \log{(1 - S(E_i, E_j))}\Big]\;, \label{eq:loss_enet} \end{split} \end{align} where $P$ is a set of pixel pairs. Since we require more than one point label per object to optimize Equation~\ref{eq:loss_enet}, we use extra points from pseudo-masks generated by an object proposal method (see Figure~\ref{fig:gt}). At each training iteration, the pseudo-mask of an object is randomly selected from the set of proposals (obtained by the proposal method) that intersect with the object's point annotation. Further, we define the background as the region that does not contain any proposal mask. We obtain the set of pixel pairs $P$ for Eq.~\ref{eq:loss_enet} as follows. We pair each pixel represented by the point-level annotation with $k$ random pixels\footnote{We chose $k$ as the number of objects in the image.} from each object's pseudo-mask including the background region. This randomness allows the model to learn the important pixels that correspond to the objects of interest. The final objective function of WISE is defined as: \begin{equation} \mathcal{L}_W = \lambda\cdot \mathcal{L}_L + (1-\lambda)\cdot \mathcal{L}_E\;, \label{eq:loss_wisenet} \end{equation} where $\lambda$ is the weight that balances between L-Net's and E-Net's loss terms. \begin{figure}[t] \begin{center} \includegraphics[width=\linewidth]{figures/proposals.png} \end{center} \caption{\textbf{Pseudo-mask labels}. (Left) ground-truth point-level annotations; (Center) a set of generated object proposals that intersect with the point annotations; (Right) proposals with best ``objectness".} \label{fig:gt} \end{figure} \subsection{Prediction at Test Time} \label{sec:prediction} WISE predicts masks of objects using the following steps. First, L-Net outputs a pixel coordinate for each object representing its location and category. Second, E-Net outputs the embedding vectors for all pixels in the image. Third, we compute the similarity (Equation~\ref{eq:similarity}) between each pixel in the image and two sets of pixels: (1) L-Net's predicted pixel coordinates, and (2) several selected background pixels. Next, we assign each pixel to the most similar object, resulting in a mask for each object including the background region. Finally, the object masks are refined by replacing them with the pseudo-mask (generated from a proposal method) with the largest Jaccard similarity (see Figure~\ref{fig:overview}). For selecting the background pixels deterministically, we first define the background regions as the pixels that do not correspond to any of the generated proposal masks. We use the $k$-means algorithm for clustering the pixels embeddings into $k$ groups. Then, for each cluster we select the closest pixel to the mean of that cluster, giving us $k$ representative pixels from the background. \section{Experiments} \label{sec:experiments} We evaluate the WISE network on a wide variety of datasets: PASCAL VOC~\cite{everingham2010pascal}, COCO~\cite{lin2014microsoft}, CityScapes~\cite{cordts2016cityscapes}, and KITTI~\cite{Geiger2012CVPR} datasets. We compare our results against fully-supervised, and weakly-supervised methods. We compare WISE against several baselines to showcase the efficacy of each of its components. We also fix the annotation budget for acquiring per-pixel, point-level, and image-level labels and compare several models based on the type of label they require. Unless otherwise specified, the performance is measured using average precision (AP) as in~\cite{he2016deep}, computed with Intersection-over-Union (IoU) thresholds of 0.25, 0.5, and 0.75. \subsection{Methods and Baselines} We include the following methods in our benchmarks: \noindent {\bf L-Net + Blobs:} use the raw output of L-Net (see Figure~\ref{fig:localization}) (which is a predicted blob per object in the scene) as mask prediction. \noindent {\bf L-Net + Best proposal:} replace each object location predicted by L-Net with the SharpMask's proposal that has the highest ``objectness'' score. \noindent {\bf L-Net + Oracle proposal:} replace each object location predicted by L-Net with the SharpMask's proposal that achieves the highest evaluation score (\eg mAP). \noindent {\bf L-Net + GT-Mask:} replace each object location predicted by L-Net with the ground-truth mask. \noindent {\bf PRM + E-Net:} use the object locations predicted by PRM (as described in~\cite{Zhou2018PRM}) as input to E-Net to obtain the object masks. Note that PRM only requires image-level labels. \noindent {\bf GT-points + E-Net:} use the ground-truth object locations (point-level annotations) as input to E-Net to obtain the object masks. \noindent {\bf WISE (L-Net + E-Net):} use L-Net's predicted object locations as input to E-Net to obtain the object masks. \begin{table}[t] \centering \begin{tabular}{l|x{22}x{22}x{22}} \textbf{Method} &\textbf{AP$_{25}$} &\textbf{AP$_{50}$} &\textbf{AP$_{75}$}\\ \shline L-Net + Blobs & 08.4 & 01.2 & 00.1\\ L-Net + Best proposal & 42.9 & 33.4 & 19.1\\ L-Net + Oracle proposal & 57.3 & 45.1 & 37.2\\ L-Net + GT-Mask & 61.2 & 61.2 & 61.2\\ \hline PRM + E-Net & 43.0 & 32.0 & 19.0\\ GT-points + E-Net & 63.1 & 47.0 & 26.3\\ \hline WISE (L-Net + E-Net) & 53.5 & 43.0 & 25.9\\ \end{tabular} \vspace{3mm} \caption{\textbf{Ablation Studies}. A benchmark illustrating the contribution of each WISE's component on PASCAL VOC 2012.} \label{tab:pascal_baselines} \end{table} \subsection{Implementation Details} L-Net and E-Net share the same backbone, a ResNet-50~\cite{he2016deep} pretrained on ImageNet~\cite{deng2009imagenet}. They also have independent upsampling paths with similar architecture as FCN8~\cite{long2015fully}. The number of output channels for L-Net is the number of classes, and for E-Net is $d=64$, the size of a pixel's embedding vector. We observed minor differences in the results between different embedding dimensions. For each image, we use $1000$ pretrained SharpMask~\cite{pinheiro2016learning} proposals (note that we do not finetune the proposal on any dataset). During training, for each point-annotation we sample a proposal non-uniformly based on its ``objectness'' score to represent its pseudo-mask. We set $k$ as the number of predicted objects (by L-Net) for selecting the background pixels at test time. The model is trained using Adam~\cite{kingma2014adam} optimizer with a learning rate of $10^{-5}$ and a weight decay of $0.0005$ for $200k$ iterations with a batch size of $1$. We choose $\lambda=0.1$ in Equation~\ref{eq:loss_wisenet} in order to make the scale between its two loss terms similar. \begin{table}[t] \centering \resizebox{\linewidth}{!}{% \begin{tabular}{l|x{47}x{16}x{16}x{16}} \textbf{Method} & \textbf{Annotation} &\textbf{AP$_{25}$} &\textbf{AP$_{50}$} &\textbf{AP$_{75}$}\\ \shline Mask R-CNN~\cite{zhu2017soft} & per-pixel & 17.1 & 11.2 & 03.4\\ SPN~\cite{zhu2017soft} & image-level & 26.0 & 13.0 & 04.0\\ PRM~\cite{Zhou2018PRM} & image-level & 44.0 & 27.0 & 09.0\\ Cholakkal~\emph{et al.}~\cite{cholakkal2019object}& image-level & \textbf{48.5} & 30.2 & 14.4\\ \hline PRM + E-Net (Ours) & image-level & 43.0 & 32.0 & 19.0\\ WISE (Ours) & point-level & 47.5 & \textbf{38.1} & \textbf{23.5}\\ \end{tabular} } \vspace{3mm} \caption{\textbf{PASCAL VOC 2012 with a fixed annotation budget.} Comparison across methods with the same annotation budget.} \label{tab:pascal_budget} \end{table} \subsection{Experiments on PASCAL VOC 2012} PASCAL VOC 2012~\cite{everingham2010pascal} contains $1,464$ and $1,449$ images for training and validation respectively, where objects come from $20$ categories. We use the point-level annotations provided by Bearman~\emph{et al.}~\cite{bearman2016s} as ground-truth for training our methods. We report the AP across several thresholds on the validation set, as described in the dataset's instance segmentation setup~\cite{everingham2010pascal}. \begin{table*}[t] \centering \tablestyle{4pt}{1.05} \resizebox{\textwidth}{!}{% \begin{tabular}{l|x{12}x{12}x{12}x{12}x{12}x{12}x{12}x{12}x{12}x{12}x{12}x{12}x{12}x{12}x{12}x{12}x{12}x{12}x{12}x{12}|x{12}x{12}} \multicolumn{1}{l|}{\textbf{Method}} & \multicolumn{1}{l|}{\textbf{\rotatebox[origin=c]{90}{plane}}} & \multicolumn{1}{l|}{\textbf{\rotatebox[origin=c]{90}{bike}}} & \multicolumn{1}{l|}{\textbf{\rotatebox[origin=c]{90}{bird}}} & \multicolumn{1}{l|}{\textbf{\rotatebox[origin=c]{90}{boat}}} & \multicolumn{1}{l|}{\textbf{\rotatebox[origin=c]{90}{bottle}}} & \multicolumn{1}{l|}{\textbf{\rotatebox[origin=c]{90}{bus}}} & \multicolumn{1}{l|}{\textbf{\rotatebox[origin=c]{90}{car}}} & \multicolumn{1}{l|}{\textbf{\rotatebox[origin=c]{90}{cat}}} & \multicolumn{1}{l|}{\textbf{\rotatebox[origin=c]{90}{chair}}} & \multicolumn{1}{l|}{\textbf{\rotatebox[origin=c]{90}{cow}}} & \multicolumn{1}{l|}{\textbf{\rotatebox[origin=c]{90}{table}}} & \multicolumn{1}{l|}{\textbf{\rotatebox[origin=c]{90}{dog}}} & \multicolumn{1}{l|}{\textbf{\rotatebox[origin=c]{90}{horse}}} & \multicolumn{1}{l|}{\textbf{\rotatebox[origin=c]{90}{motor}}} & \multicolumn{1}{l|}{\textbf{\rotatebox[origin=c]{90}{person}}} & \multicolumn{1}{l|}{\textbf{\rotatebox[origin=c]{90}{plant}}} & \multicolumn{1}{l|}{\textbf{\rotatebox[origin=c]{90}{sheep}}} & \multicolumn{1}{l|}{\textbf{\rotatebox[origin=c]{90}{sofa}}} & \multicolumn{1}{l|}{\textbf{\rotatebox[origin=c]{90}{train}}} & \textbf{\rotatebox[origin=c]{90}{tv}} & \textbf{\rotatebox[origin=c]{90}{Avg.}} \\\shline \scriptsize SDS~\cite{hariharan2014simultaneous} & 58.8 & 0.5 & 60.1 & 34.4 & 29.5 & 60.6 & 40.0 & 73.6 & 6.5 & 52.4 & 31.7 & 62.0 & 49.1 & 45.6 & 47.9 & 22.6 & 43.5 & 26.9 & 66.2 & 66.1 & 43.8 \\ \scriptsize Chen \emph{et al.}~\cite{chen2015multi} & 63.6 & 0.3 & 61.5 & 43.9 & 33.8 & 67.3 & 46.9 & 74.4 & 8.6 & 52.3 & 31.3 & 63.5 & 48.8 & 47.9 & 48.3 & 26.3 & 40.1 & 33.5 & 66.7 & 67.8 & 46.3 \\ \scriptsize PFN~\cite{liang2015proposal} & 76.4 & 15.6& 74.2 & 54.1 & 26.3 & 73.8 & 31.4 & 92.1 & 17.4& 73.7 & 48.1 & 82.2 & 81.7 & 72.0 & 48.4 & 23.7 & 57.7 & 64.4 & 88.9 & 72.3 & 58.7 \\ \scriptsize R2-IOS~\cite{liang2016reversible} & 87.0 & 6.1 & 90.3 & 67.9 & 48.4 & 86.2 & 68.3 & 90.3 & 24.5 & 84.2 & 29.6 & 91.0 & 71.2 & 79.9& 60.4 & 42.4 & 67.4 & 61.7 & 94.3 & 82.1 & 66.7 \\ \scriptsize Fathi \emph{et al.}~\cite{fathi2017semantic}& 69.7 & 1.2 & 78.2 & 53.8 & 42.2 & 80.1 & 57.4 & 88.8 & 16.0 & 73.2 & 57.9 & 88.4 & 78.9 & 80.0 & 68.0 & 28.0 & 61.5 & 61.3 & 87.5 & 70.4 & 62.1 \\ \hline \scriptsize WISE (Ours) & 59.0 & 5.6 & 63.6 & 41.4 &21.9 & 40.6 & 34.1 & 73.8 & 8.5 & 38.7 & 29.1& 64.6 &58.1 & 60.4 & 33.3 & 25.1 &43.8 & 32.7 & 64.7 & 60.7 & 43.0 \\ \end{tabular}} \vspace{3mm} \caption{\textbf{Comparison to fully supervised methods.} Per-class comparison against the AP$_{50}$ metric on PASCAL VOC 2012.} \label{tab:pascal_full} \end{table*} \begin{table*}[t] \centering \tablestyle{4pt}{1.05} \begin{tabular}{l|x{22}x{22}x{22}|x{22}x{22}x{22}|x{22}x{22}x{22}} \multirow{2}{*}{{\textbf{Model}}} & \multicolumn{3}{c|}{\textbf{COCO 2014}} &\multicolumn{3}{c|}{\textbf{KITTI}} & \multicolumn{3}{c}{\textbf{CityScapes}}\\ &\textbf{AP$_{25}$} & \textbf{AP$_{50}$}&\textbf{AP$_{75}$} &\textbf{AP$_{25}$} &\textbf{AP$_{50}$} &\textbf{AP$_{75}$} &\textbf{AP$_{25}$} &\textbf{AP$_{50}$} &\textbf{AP$_{75}$} \\ \shline L-Net Best proposal & 18.3 & 13.6 & 7.3 & 46.4 & 38.1 & 22.2 & 27.2 & 15.5 & 6.7\\ WISE (Ours) & 25.8 & 17.6 & 7.8 & 63.4 & 49.8 & 30.9 & 28.7 & 18.2 & 8.8\\ \end{tabular} \vspace{3mm} \caption{\textbf{Baseline comparisons.} Results across different average precision IoU thresholds.} \label{tab:other_baseline} \end{table*} \subsubsection{Comparison to methods and baselines.}\label{sec:baselines} In this section, we discuss the results shown in Table~\ref{tab:pascal_baselines}. A straightforward method to obtain object masks is to use L-Net's raw output (which we refer to as ``L-Net + Blobs''). However, it performs poorly as the predicted blobs are often small around the center of the object. A natural extension is to replace L-Net's predicted blobs by a segment proposal obtained from an object proposal method. Therefore, we discovered a reasonable strategy which is to replace each of L-Net's predicted blobs by the proposal of highest ``objectness'' score (``L-Net + Best-proposal''). However, ``L-Net + Oracle'' shows that a perfect proposal selection strategy can vastly improve on the segmentation results. Accordingly, we propose WISE which improves on ``L-Net + Best-proposal'' by having E-Net that learns rough segmentation of the objects. This allows to select better proposals by choosing those with the highest IoU. Note that other object proposal selection strategies have been used in other weakly supervised instance segmentation setups~\cite{Zhou2018PRM, cholakkal2019object}. To assess how much improvement we can make over L-Net, we report the results of ``GT-points + E-Net'' which uses the ground-truth points instead of L-Net's predictions. We see that L-Net's performance is close to its upper-bound. Further, we provide the results of ``PRM + E-Net'' which is an extension to WISE that can train using image-level annotations only. Similarly, we observe that the results are not widely different. However, image-level labels might not be suitable for datasets when the number of objects in an image is dense and when the same object class exist in almost every image as the \emph{car} category in CityScapes. \subsubsection{Comparison to Similar Annotation Time}\label{sec:budget} We compare the performance between state-of-the-art methods in Table~\ref{tab:pascal_budget} when the annotation time is fixed. Therefore, we limit the annotation budget to around $8.13$ hours which is calculated as $20.0 \times 1,464$ seconds. Bearman~\emph{et al.}~\cite{bearman2016s} has shown that it takes $20.0$, $22.1$, and $239.7$ seconds per image for collecting image-level, point-level, and per-pixel labels, respectively. As a result, for the same annotation time budget, we acquire $1,464$ images with image-level labels, $1,325$ images with point-level labels, and $122$ images with per-pixel labels. We selected these images uniformly without replacement from the training set. We also reported the result of Mask R-CNN~\cite{massa2018mrcnn} trained on the images with the per-pixel labels. The table shows that our method significantly outperforms other approaches, suggesting that using point-level annotations is a cost-effective labeling method for instance segmentation. Further, Figure~\ref{fig:qualitative} illustrates that WISE can capture high quality masks for PASCAL VOC objects, although it can fail in merging two masks of the same object such as in the horse image. \subsubsection{Comparison to Weakly and Fully Supervised Methods} \label{sec:full} Acquiring point-level labels is almost as cheap as image-level labels, yet they vastly improve results, as shown in Table~\ref{tab:pascal_budget}. For a fair evaluation, we compare ``PRM + E-Net'' which uses image-level labels against current state-of-the-art image-level instance segmentation methods. The concurrent work of~\cite{cholakkal2019object} performs better with respect to AP$_{25}$, which is expected as their counting results is better than LCFCN which is what L-Net is based on. Further, we report WISE results against fully supervised methods in Table~\ref{tab:pascal_full} for each category with respect to AP$_{50}$. While WISE achieves competitive results, there is room for improvement between weakly- and strong- supervised methods. \begin{table}[h] \centering \begin{tabular}{l|x{18}x{18}} \textbf{Model} & \textbf{AP$_{50}$} & \textbf{AP$_{75}$}\\\shline Base-DA~\cite{dvornik2018importance}& 46.0 & 28.1\\ Mask-RCNN~\cite{he2017mask} & 55.2 & 35.3\\\hline WISE (Ours) & 17.4 & 07.7\\ \end{tabular} \vspace{3mm} \caption{\textbf{COCO 2014.} Comparison to fully supervised methods.} \label{tab:coco} \end{table} \subsection{Experiments on COCO 2014} For COCO 2014~\cite{lin2014microsoft}, we train on the union of the $80$k train images and the $35$k subset of validation images, and report the results on {\it minival} consisting of $5$k images, following the experimental setup of He~\emph{et al.}~\cite{he2017mask}. It consists of $80$ categories belonging to a wide variety of everyday objects. We obtain ground-truth points by taking the pixel with the largest distance transform for each instance segmentation mask. We use the standard COCO metrics including AP (averaged over IoU thresholds), AP$_{50}$, and AP$_{75}$. Table~\ref{tab:other_baseline} shows that WISE outperforms our baseline ``L-Net + Best Proposal'', which suggests that E-Net generates better proposal masks. The qualitative results in Figure~\ref{fig:qualitative} show that WISE can successfully capture the mask of diverse objects. Table~\ref{tab:coco} shows that while our results are poor compared to fully supervised methods, they establish a first strong baseline for instance segmentation with point-level supervision. \subsection{Experiments on KITTI} KITTI~\cite{Geiger2012CVPR} is a meaningful benchmark for autonomous driving. Using the setup described in \cite{zhang2016instance}, we train our models on the $3,712$ training images where the ground-truth points are the provided bounding box centers. We reported results on the $120$ validation images using the {\it MUCov} and {\it MWCov} metrics, as described in Silberman~\emph{et al.}~\cite{silberman2014instance}. Table~\ref{tab:other_baseline} shows that WISE significantly outperforms the baseline ``L-Net + Best Proposal'', suggesting that relying on the best ``objectness'' score for picking the proposal is not the optimal approach. Furthermore, Table~\ref{tab:kitti} shows that WISE achieves competitive results compared to methods that use full supervision. Figure~\ref{fig:qualitative} shows quality masks being generated for the cars and persons objects on KITTI images by WISE. \begin{table}[h] \centering \begin{tabular}{l|x{30}x{30}} \textbf{Model} & \textbf{MWCov} & \textbf{MUCov} \\\shline DepthOrder~\cite{zhang2015monocular} & 70.9 & 52.2\\ DenseCRF~\cite{zhang2016instance} & 74.1 & 55.2\\ AngleFCN+Depth~\cite{uhrig2016pixel} & 79.7 & 75.8\\ Recurrent+attention~\cite{ren2017end} & 80.0 & 66.9\\\hline WISE (Ours) & 74.2 & 58.9\\ \end{tabular} \vspace{3mm} \caption{\textbf{KITTI.} Comparison to fully supervised methods.} \label{tab:kitti} \end{table} \subsection{Experiments on CityScapes} CityScapes~\cite{cordts2016cityscapes} is a popular autonomous driving benchmark for instance segmentation. It contains $2,975$ high-resolution training images, and $500$ validation images that represent street scenes acquired from an on-board camera. The pixels are labeled into 19 classes, but only 8 classes belong to countable objects (used for instance segmentation): person, rider, car, truck, bus, train, motorcycle, and bicycle. The ground-truth point for each object is the pixel with the largest distance transform within its corresponding ground-truth segmentation mask. Table~\ref{tab:other_baseline} shows that WISE sets a new strong baseline for the weakly supervised setting, while achieving better results than the comparable baseline ``L-Net + Best proposal''. Further, Figure~\ref{fig:qualitative} illustrates that our method can obtain good masks for various objects of interest. However, fully supervised methods shown in Table~\ref{tab:cityscapes_full} outperform our weakly supervised method with a large margin, inspiring future research on this problem setup. In Table~\ref{tab:cityscapes_bbox}, we compare ``GT-points + E-Net'' against the methods proposed by Remez~\emph{et al.}~\cite{remez2018learning} which use bounding box ground-truth labels at test time. Using their evaluation setup, we report the results in Table~\ref{tab:cityscapes_bbox} which shows better results across four categories. This is despite E-Net using weaker labels than Cut \& Paste. According to Bearman~\emph{et al.}~\cite{bearman2016s}, it takes an average of 10.2 seconds to acquire a bounding box, but only 2.4 seconds to get an annotation for a single object instance. \begin{table}[h] \centering \begin{tabular}{l|x{15}} \textbf{Method} & \textbf{AP}\\\shline InstanceCut~\cite{kirillov2017instancecut} & 15.8\\ DWT~\cite{bai2017deep} & 19.8\\ SGN~\cite{liu2017sgn} & 29.2\\ Mask-RCNN~\cite{he2017mask} & 31.5\\\hline WISE (Ours) & 07.8\\ \end{tabular} \vspace{3mm} \caption{\textbf{CityScapes.} Comparison to fully supervised methods.} \label{tab:cityscapes_full} \end{table} \begin{table}[h] \centering \resizebox{\linewidth}{!}{% \begin{tabular}{l|x{22}x{22}x{32}x{32}} \textbf{Method} & \textbf{Car} & \textbf{Person} & \textbf{T. light} & \textbf{T. sign}\\\shline Box~\cite{remez2018learning} & 62.0 & 49.0 & 76.0 & 76.9\\ Simple Does it~\cite{khoreva2017simple} & 68.0 & 53.0 & 60.0 & 51.0\\ GrabCut~\cite{rother2004grabcut} & 62.0 & 50.0 & 64.0 & 65.0\\ Cut \& Paste~\cite{remez2018learning} & 67.0 & 54.0 & 77.0 & 79.0\\\hline Fully Supervised~\cite{remez2018learning}& 80.0 & 61.0 & 79.0 & 81.0\\\hline GT-points + E-Net (Ours) & 77.6 & 55.4 & 77.8 & 80.1\\ \end{tabular} } \vspace{3mm} \caption{\textbf{CityScapes.} Methods with bounding boxes at test time.} \label{tab:cityscapes_bbox} \end{table} \section{Conclusion} \label{sec:conclusion} In this paper, we have introduced a weakly supervised instance segmentation network (WISE). It can train by using point-level annotations and by leveraging pseudo-masks from object proposal methods. WISE uses L-Net to first detect the object locations which are then given as input to E-Net in order to obtain the segmentation masks. E-Net is based on an embedding network that groups pixels in the image-based on their similarity which are then used to select the best matching proposal mask. We have validated our method across a wide variety of datasets. The results show that WISE obtains competitive results against fully supervised methods and outperform weakly-supervised methods with a fixed annotation cost. The results also provide a strong first baseline for instance segmentation with point-level supervision. Although a pretrained proposal method was used in this problem setup, it was not finetuned on any of our datasets. However, an interesting future direction is to address this task with a more challenging setup that requires proposal-free methods. \clearpage \begin{figure*}[ht] \begin{center} \includegraphics[width=0.8\textwidth]{figures/figure5_qualitative.png} \end{center} \caption{\textbf{Qualitative results.} Qualitative results of WISE on the four datasets evaluated.} \label{fig:qualitative} \end{figure*} \clearpage {\small \bibliographystyle{ieee}
{'timestamp': '2019-06-18T02:02:28', 'yymm': '1906', 'arxiv_id': '1906.06392', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06392'}
arxiv
\section{Introduction} Credit default risk modelling is critical to the loss management of credit portfolios for financial institutions. Effective credit risk estimation prevents and manages losses that arise when borrowers cannot make the necessary credit repayments on agreed terms. Accurate estimation of an individual's credit risk is of benefit both to the lending institution and the borrower in any credit agreement \cite{hand_henly}. The lending institution benefits from increased profits or reduced loss while the borrower benefits through only being involved in transactions which are within their ability of fulfilment. Subjective expert judgement has historically been used to determine the credit risk presented by a borrower\cite{Wang:2011:CAE:1860128.1860220}. This clearly presents challenges of introducing cognitive biases and does not allow for streamlined operational efficiency in large financial institutions\cite{Wang:2011:CAE:1860128.1860220}. In recent times, increased demand for credit and the development of efficient computing systems has given prominence to sophisticated machine learning techniques in the credit risk determination process\cite{hand_henly}. Literature in machine learning approaches to credit risk modelling is dominated by tree based models and artificial neural networks(ANNs) \cite{baesens,yeh2009comparisons}. \citet{XIA2017225} proposed an Xtreme Gradient boosting (XGboost) tree model for credit scorecard creation. Their results show that XGboost after Bayesian parameter tuning outperforms random forests(RF) and support vector machines(SVMs) based on accuracy and the Area Under the Curve(AUC) measures on five benchmark credit datasets. \citet{twala2010multiple} shows that ensemble tree based classifiers demonstrate superior predictive performance when noise is introduced to credit scoring attributes. \citet{sun2018} compare deep neural networks(DNNs) and simple ANNs in predicting credit default on a Brazilian Banking Dataset. Their results show that simple ANNs and DNNs outperform logistic regression and tree based methods on the AUC performance measure. The work of \citet{ANGELINI2008733} similarly finds that low classification errors can be obtained when using ANNs to predict credit default for Italian Small businesses. \citet{yeh2009comparisons} use ANNs to predict credit card default for Taiwanese credit cardholders and their results show that ANNs produced the lowest errors when predicting the probability of default as compared to K-nearest neighbours, logistic regression and decision trees. The work of \citet{hamori2018ensemble} shows that the performance of ANNs in credit default modelling is significantly affected by the choice of activation function and the dropout mechanism employed. While ANN methods are well covered in the literature, there has been no attempt to address some of their short comings when it comes to their applications to credit risk modelling. These shortcomings include the fact that traditional ANNs do not give an indication of which attributes are relevant for the prediction of credit risk and this does not aid in the transparency of the credit granting process which might be required by regulations such as General Data Protection Regulation(GDPR)'s 'right to explanation' in the European Union \cite{goodman2016eu} . The second drawback which applies to both ANNs and tree based models is that they give the probability of default but do not address the level of uncertainty behind such a probability - this does not aid in the reliability analysis and risk appetite assessment of the lending institution. In this work, we develop probabilistic formulations of ANNs through the Gaussian approximation \cite{8191129,lagazio2006} and Hybrid Monte Carlo \cite{neal2012bayesian} that will address the two shortcomings identified above. The Bayesian formulation of ANNs using a Gaussian approximation to the posterior was first proposed by \citet{Mackay1991APB}. This method has shown superior performance in numerous applications of ANNs including in conflict analysis \cite{lagazio2006}, energy consumption modelling\cite{MacKay95probablenetworks} and wind power forecasting \citep{8191129}. Hybrid Monte Carlo (HMC) was first applied as a technique for sampling from Bayesian Neural Network models (BNNs) in the seminal work of \citet{neal1993bayesian}. Since then, HMC has proved to be the most effective way to obtain such samples from the exact posterior distribution of BNNs, outperforming other approximate inference methods such as Gaussian approximation of \citet{MacKay95probablenetworks} and variational inference of \citet{hinton1993keeping} (\cite{wang2013adaptive},\cite{betancourt2017conceptual}). BNNs have numerous advantages over traditional ANNs that are useful for decision makers in credit risk modelling. These include the ability to produce a predictive distribution rather than a point estimate of the probability to default. The ability to perform Automatic Relevance Determination(ARD) in BNNs also allows decision makers to infer the relative influences of different attributes on the network outputs - this aids in addressing the notion that Neural ANNs are "black-box" models that offer no interpretation. Finally, network regularisation arises naturally in BNNs through the prior distribution which creates a bias towards simpler regularised networks and increases network generalisation in accordance with Occam's Razor\cite{MacKay95probablenetworks}. The ideas on BNNs described above have thus far not been developed and applied in credit risk modelling. This work aims to develop and compare BNNs trained using Gaussian approximation and HMC when applied to credit default modelling. The rest of the paper is arranged as follows: section \ref{Mlp} describes the basic Multilayer Perceptron(MLP) neural network. Section \ref{bnn} describes the Bayesian formulation of the MLP with sections \ref{Gauss} and \ref{hmc} describing how to perform inference in BNNs using the Gaussian approximation and HMC. Section \ref{expr} sets out our experiments. Section \ref{resultss} provides and discusses the results of the experiments. Section \ref{conc} concludes and gives possible future work. \section{The Multilayer Perceptron (MLP)} \label{Mlp} Neural networks (NNs) are learning machines that infer input output relationships of functions with arbitrary complexity \cite{DBLP:journals/corr/EricsonM17}. Feed-forward multilayer perceptron (MLP) are a type of NNs that propagate inputs through 'hidden' layers of non-linear activation functions to generate outputs. The output of the MLP with a single hidden layer and a single output is defined by the following composite function \cite{8191129}: \begin{align} h_j(x) &= \Psi\bigg(Z_j + \sum_{i}w_{ij} x_i\bigg) \\ o_k(x) &= b_k + \sum_{j}v_{jk} h_j(x) \end{align} Where $w_{ij}$ is the weight connection for the $i^{th}$ input to the $j^{th}$ hidden unit and $v_{jk}$ is the weight connection between the $j^{th}$ hidden unit to the $k^{th}$ output. $\Psi$ is a non-linear activation function. Locally Optimal weight parameters of the MLP are found by back-propagation of errors between network outputs and the ground truth realisations of the system being modelled \cite{rumelhart1986learning}. This results in maximum likelihood estimates (MLE) and Maximum A Posteriori (MAP) estimates where regularisation is included. \section{Probabilistic Multilayer Perceptron}\label{bnn} MLP networks can be formulated within the Bayesian Probabilistic framework such that the error function of the network can be viewed as the kernel of the posterior distribution of network parameters \cite{8191129}. In the Bayesian sense the posterior distribution of the network weight parameters given the observed data and prior distribution of weights can be derived using Bayes formula as \cite{MacKay:1992:PBF:148147.148165}: \begin{equation} P(\mathbf{w}|D,\mathcal{H}) = \frac{P(D|\mathbf{w},\mathcal{H})P(\mathbf{w}|\mathcal{H})}{P(D|\mathcal{H})} \label{bayes} \end{equation} where $P(\mathbf{w}|D,\mathcal{H})$ is the posterior probability of the weights given the data and model architecture $\mathcal{H}$. $P(D|w,H)$ is the likelihood of the data given the model. $P(w|H)$ is the prior probability of the weights. $P(D|H)$ is a marginalisation across all parameters known as the evidence. The posterior distribution for the MLP weights in equation \ref{bayes} becomes \cite{neal1993bayesian}: \begin{align} P(\mathbf{w}|\alpha,\beta,\mathcal{H})& = \frac{1}{Z(\alpha,\beta)}\exp\big(-\alpha\big( E_W + \beta E_D\big)\big)\\ & = \frac{1}{Z_M(\alpha,\beta)} \exp\big(-M(\mathbf{w})\big) \label{eq:pos} \end{align} Where $\alpha E_W$ is the kernel of the prior distribution on the weights and $\beta E_D$ is the kernel of the data likelihood. The distribution functions above are not computationally tractable in closed form and thus we rely on approximate inference techniques such as Gaussian approximation \cite{MacKay95probablenetworks} and Hybrid Monte Carlo\cite{neal2011mcmc}. \section{Gaussian Approximation}\label{Gauss} \citet{Mackay1991APB} proposed a Gaussian Approximation to the posterior distribution in equation \ref{eq:pos} based on a second order Taylor expansion of the posterior around $\mathbf{w_{MP}}$ as follows \cite{MacKay95probablenetworks}: \begin{equation} P(\mathbf{w}|\alpha,\beta,H,D) \approx \frac{1}{Z'_M(\alpha,\beta)} \exp\bigg(-M(\mathbf{w_{MP}})-\frac{1}{2}(\mathbf{w} -\mathbf{w_{MP}})^T\mathbf{A}(\mathbf{w} -\mathbf{w_{MP}})\bigg) \label{eq:post} \end{equation} The matrix $\mathbf{A}$ contains the second derivatives of the negative log posterior. Assuming the Gaussian approximation holds the values of the hyper-parameters $\alpha$ and $\beta$ can be approximated by alternating between gradient decent for the weights and maximising the evidence $P(D|H)$ in equation \ref{eq:pos} which becomes tractable through the Gaussian approximation. Under these simplifying assumptions the posterior weight distribution becomes \cite{MacKay95probablenetworks}: \begin{equation} P(\mathbf{w}|D,\alpha,\beta) \approx \mathcal{N}(\mathbf{w_{MP}},\mathbf{A}^{-1}) \end{equation} Due to the central limit theorem the Gaussian Approximation is expected to be a close approximation to the true posterior as the sample size becomes large \cite{lagazio2006} \section{Hybrid Monte Carlo}\label{hmc} HMC is a Markov Chain Monte Carlo technique that generates samples from the exact posterior distribution by simulating a Markov Chain with a stationary distribution, which is the the target posterior distribution of the NN. Traditional MCMC algorithms such as Metropolis Hastings (MH) suffer from excessive random walk behaviour - where the next state of the Markov Chain is randomly proposed from a proposal distribution. This results in inefficient sampling with low acceptance rates and low effective sample sizes. \citet{neal1993bayesian} proposed HMC which suppresses random walk behaviour by augmenting the parameter space with auxiliary momentum variables. HMC uses the gradient information of the neural network to create a vector field around the current state giving it a trajectory towards a high probability next state. The dynamical system formed by the model parameters $w$ and the auxiliary momentum variables $p$ is represented by the Hamiltonian $H(w,q)$ written as follows \cite{neal1993bayesian}: \begin{equation} H(w,q)=M(w)+K(p) \end{equation} Where $M(w)$ is the negative log likelihood of the posterior distribution in equation \ref{eq:pos}, also referred to as the potential energy. $K(p)$ is the kinetic energy defined by the kernel of a Gaussian with a co-variance matrix $M$ \cite{neal2012bayesian}: \begin{equation} K(p) =\frac{p^TM^{-1}p}{2} \end{equation}. The trajectory vector field is defined by considering the parameter space as a physical system that follows Hamiltonian Dynamics. The dynamical equations governing the trajectory of the chain are then defined by the Hamilton's equations at a fictitious time $t$ as follows \cite{neal1993bayesian}: \begin{equation} \frac{\partial w_i}{\partial t} = \frac{\partial H}{\partial p_i} \end{equation} \begin{equation} \frac{\partial p_i}{\partial t} = -\frac{\partial H}{\partial w_i} \end{equation} In practical terms the dynamical trajectory is discretised using the leapfrog integrator. In the leapfrog integrator to reach the next point in the trajectory we take half a step in the momentum direction, followed by a full step in the direction of the network parameters - then ending with another other half step in the momentum direction. Finally due to the discretising errors that arise from the leapfrog integrator a Metropolis acceptance step is performed in order to accept or reject the new sample proposed by the trajectory\cite{neal2011mcmc}. In the Metropolis step the parameters proposed by the HMC trajectory $w*$ are accepted with the probability \cite{neal1993bayesian}: \begin{equation} P(accept) = min\bigg(1,\frac{P(w^{*}|D,\alpha,\beta,H)}{P(w|D,\alpha,\beta,H)}\bigg) \end{equation} Algorithm \ref{alg:BNN} shows the pseudo-code for the HMC where $\epsilon$ is a discretisation step-size. The leapfrog steps is repeated until the maximum trajectory length $L$. In HMC the hyperparameters $\alpha$ and $\beta$ can be sampled by alternating between HMC samples of weights and re-sampling the regularisation parameters from an assumed distribution given a fixed sample of weights. \begin{algorithm} \SetAlgoLined \DontPrintSemicolon \KwData{Training dataset \{$\mathbf{X}^{(i)},\mathbf{t}^{(i)}\}$} \KwResult{$N$ Samples of MLP Weights $\mathbf{w}_{MP}$} \For{$n\leftarrow 1$ \KwTo $N$}{ $w_0\leftarrow w_{\text{init}}$\; \emph{sample the auxiliary momentum variables $p$}\; p$\sim\mathcal{N}(0,\mathbf{M})$\; Use leapfrog steps to generate proposals for $w$\; \For{$t\leftarrow 1$ \KwTo $L$}{ $p(t+\epsilon/2) \leftarrow p(t) + (\epsilon/2)\frac{\partial H}{\partial w}\bigg(w(t)\bigg)$\; $w(t+\epsilon) \leftarrow w(t) + \epsilon\frac{p(t+\epsilon/2)}{M}$\; $ p(t+\epsilon) \leftarrow p(t)+\epsilon/2) + (\epsilon/2)\frac{\partial H}{\partial w}\bigg(w(t+\epsilon)\bigg)$\; } \emph{Metropolis Update step:}\; $(p,w)_n\leftarrow(p(L),w(L))$ with probability:\; $min\bigg(1,\frac{P(w^{*}|D,\alpha,\beta,H)}{P(w|D,\alpha,\beta,H)}\bigg)$\; } \caption{ Hamiltonian Monte Carlo Algorithm} \label{alg:BNN} \end{algorithm} \section{Automatic Relevance Determination(ARD)}\label{ARD} The MLP formulations presented above can be parameterised such that different groups of weights can come from unique prior distributions and thus have unique regularisation parameters $\alpha_c$ for each class. An Automatic Relevance Determination (ARD) MLP is one where weights associated with each network input belong to a distinct class. The loss function in ARD is a follows\cite{MacKay95probablenetworks}: \begin{equation} P(w|D,\alpha,\beta,H)=\frac{1}{Z(\mathbf{\alpha},\beta)}\exp\bigg(\beta E_D+\sum_{c}{\alpha_c} E_{W_C}\bigg) \end{equation} The regularisation hyperparameters for each class of weights can be estimated online during the inference stage of each method as discussed in sections \ref{Gauss} and \ref{hmc} . The resulting regularisation parameter $\alpha_c$ for each input can be inferred as denoting the relevance of each input. Irrelevant inputs will have high values of the regularisation parameter meaning that their weights will be forced to decay to values close to zero. ARD thus embodies the principle of Occam's Razor by placing preference on simpler models that regularise noisy irrelevant inputs \cite{MacKay95probablenetworks}. \section{Experiment Setup}\label{expr} We use the Taiwan Credit Card Dataset of \citet{yeh2009comparisons} to illustrate the utility of the various Bayesian inference methods described above. A single hidden layer MLP with 5 hidden neurons based on an initial hidden unit grid search. The following MLP inference methods are compared: A Bayesian MLP trained by HMC, a Bayesian MLP with ARD trained by HMC and a Bayesian MLP with ARD trained by Gaussian Approximation. \subsection{Dataset} The dataset consists of 30000 records with 23 features relating to the demographic profile of credit cardholders as well as their historical payment behaviour. The target variable is a binary indicator of whether the client has had a default payment. The dataset consisted of the following features: \begin{table} \centering \caption{Attributes in the Taiwanese Credit Card Dataset} \begin{tabular}{|c |c|} \hline \textbf{Attribute } & \textbf{Attribute Name} \\ \hline X1 & Amount of the given credit\\ X2 & Gender \\ X3 & Education \\ X4 & Marital status\\ X5 & Age (years)\\ X6 - X11 & History of past payment - each of the last six months \\ X12 - X17 & Amount of bill statement - each of the last six months\\ X18 - X23 & Amount of previous payment - each of the last six months \\ \hline \end{tabular} \label{table:ft1} \end{table} Normalisation of attributes has been shown to improve the performance of MLP models\cite{hamori2018ensemble}. Thus, each of the attributes above is pre-processed by projecting it onto the range $[0,1]$ using min-max normalisation. A random split 70:30 training and testing partition of the data is used for all the models. \subsection{Performance Evaluation} The Area Under the Receiver Operating Characteristic Curve (AUC) and a confusion matrix are used to evaluate predictive performance. The AUC can be interpreted as the probability of the model correctly assigning higher probability of default to defaulters relative to non-defaulters. The AUC has been shown to be a more robust metric in unbalanced classification problems where datasets are often biased towards non-defaulters \cite{ANGELINI2008733}. . \section{Results}\label{resultss} \subsection{Predictive Performance} We now discuss the performance results on the testing set of the models specified in section \ref{expr}. Figure \ref{fig:roc_curve} shows the receiver operating characteristic(ROC) curves of each of the classifiers. The ROC curve shows that the performance of the HMC-ARD with an AUC of 0.7783 and Gaussian approximation-ARD with an AUC of 0.7753 both outperform the HMC-MLP with an AUC of 0.7079. This result implies that adding the ARD to the BNN results in a more accurate model. This effect could be attributed to the fact that the ARD regularises noisy inputs thus leaving the network with greater generalisation ability. It is important to note that while the AUC gives equal weight to miss-classifications of defaulters and non-defaulters, this is not necessarily the case in credit risk modelling where the cost of miss-classifying a default (false negative) is much higher than that of miss-classifying a non-default. \begin{figure}[h] \centering \includegraphics[width=1\textwidth]{roc_curve.png} \caption{Receiver Operating Characteristics Curves of the various models on the Taiwan Credit Card Dataset} \label{fig:roc_curve} \end{figure} Table \ref{table:Results1} gives some insight into the miss-classification rates of the different models. As can be seen from the table the HMC-ARD model seems to marginally have a lower number of false negatives than the Gaussian approximation ARD model. This would save the lending institution from advancing credit to a borrower who is unlikely to repay the loan. While the differences in predictive performance is marginal, it is important to highlight that the HMC-ARD is more theoretically robust than the Gaussian approximation as it samples the exact posterior distribution. \begin{table}[!h] \centering \caption{Table showing performance results on the testing set for Taiwan Credit Card Dataset} \begin{tabular}{|c |c |c|c|c|} \hline Model & True Default & False Non-Defaults & True Non-Defaults & False Defaults \\ \hline HMC-MLP & 934 & 614 & 6407 & 1045 \\ Gaussian Approximation-ARD & 772 & 355 & 6666 & 1207 \\ HMC-ARD & 754 & 331 & 6690 & 1225 \\ \hline \end{tabular} \label{table:Results1} \end{table} \subsection{ARD Output and Model Interpretation} We now explore the output of the ARD to draw inferences on the relative influences of different features on the output. This feature of BNNs is critical to credit risk modelling as it allows lending institutions to understand the drivers of credit risk and, therefore, puts them in a position that affords their clients the 'right to explanation'. Figure \ref{fig:ard_compare} shows a comparison of the ARD output of HMC-ARD and the Gaussian approximation. Since the HMC-ARD model gives samples of the posterior variances we use the mean posterior variances for the comparisons, the heap-map of the exact samples from the posterior can be seen in figure \ref{fig:heat}. Both models identify the payment status six months ago (PAY 0) as the most important factor. The models also seem to agree on other features that are identified as important such as payment status 3 months ago (PAY 3), amount of credit given(LIMIT BAL) and the amount of previous payment 4 months ago (PAY AMT 2). The HMC-ARD model also highlights the education level as a relevant predictor. \begin{figure} \centering \includegraphics[width=0.98\textwidth]{ARD_compare.png} \caption{Left, mean posterior variances from the HMC-ARD model which indicate the relevance of each attribute. Right, posterior variances from the Gaussian Approximation-ARD model which indicate the relevance of each attribute} \label{fig:ard_compare} \end{figure} \begin{figure} \centering \includegraphics[width=0.98\textwidth]{ARD_Coefficients_samples.png} \caption{A heat-map showing the exact samples of posterior variances from the HMC-ARD model} \label{fig:heat} \end{figure} \section{Conclusion}\label{conc} We developed and compared two approaches for Bayesian inference in neural networks. The results show that the Gaussian approximation-ARD and the HMC-ARD models display similar predictive performance with clear out-performance over the basic HMC-MLP. The more theoretically grounded HMC-ARD does show a marginally superior ability to manage false negatives which is ideal for credit data. Both models crucially also allow for interpretation of the relative feature influences on the probability of default. The ARD results of both models show significant overlap which indicates some robustness in the relevance determination ability of the Bayesian frameworks \cite{lagazio2006}. Future improvements to this work could include exploring alternative variants of the HMC sampling such as the Riemannian Manifold Hamiltonian Monte Carlo of \citet{girolami2011riemann}. Deeper neural networks could also be explored. \bibliographystyle{plainnat}
{'timestamp': '2019-06-18T02:02:09', 'yymm': '1906', 'arxiv_id': '1906.06382', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06382'}
arxiv
\section{Depth Correction} \label{sec:depth_correction} Our \method{SDN}\xspace significantly improves depth estimation and more precisely renders the object contours. However, there is a fundamental limitation in stereo because of the discrete nature of pixels: the disparity, being the difference in the horizontal coordinate between corresponding pixels, has to be \emph{quantized} at the level of individual pixels while the depth is \emph{continuous}. Although the quantization error can be alleviated with higher resolution images, the computational depth prediction cost scales \emph{cubic} with pixel width and height --- pushing the limits of GPUs in autonomous vehicles. We therefore explore a hybrid approach by leveraging a cheap LiDAR with extremely sparse (\eg, 4 beams) but accurate depth measurements to \emph{correct} this bias. We note that such sensors are too \emph{sparse} to capture object shapes and cannot be used alone for detection. However, by projecting the LiDAR points into the image plane we obtain exact depths on a small portion of ``landmark'' pixels. We present a graph-based depth correction (\method{GDC}\xspace{}) algorithm that effectively combines the \emph{dense} stereo depth that has rendered object shapes and the \emph{sparse} accurate LiDAR measurements. Conceptually, we expect the corrected depth map to have the following properties: globally, landmark pixels associated with LiDAR points should possess the exact depths; locally, object shapes captured by neighboring 3D points, back-projected from the input depth map (cf. \autoref{eq_3D}), should be preserved. \autoref{fig:PL++} (bottom) illustrates the algorithm. \noindent\textbf{Input Matching.} We take as input the two point clouds from LiDAR and Pseudo-LiDAR (PL) by stereo depth estimation. Latter is obtained by converting pixels $(u,v)$ with depth $z$ to 3D points $(x_u,y_v,z)$. First, we characterize the local shapes by the directed K-nearest-neighbor (KNN) graph in the PL point cloud that connects each point to its KNN neighbors with appropriate weights (using accelerated KD-Trees~\cite{shevtsov2007highly}). Similarly, we can project the 3D LiDAR points onto pixel locations $(u,v)$ and match them to corresponding 3D stereo points. W.l.o.g. assume that we are given ``ground truth'' LiDAR depth for the first $n$ points and no ground truth for the remaining $m$ points. We refer to the 3D stereo depth estimates as $Z\in\R^{n+m}$ and the LiDAR depths as $G\in\R^n$. \noindent\textbf{Edge weights.} To construct the KNN graph in 3D we ignore the LiDAR information on the first $n$ points and only use their predicted stereo depth in $Z$. Let $\mathcal{N}_i$ denote the set of neighbors of the $i^{th}$ point. Further, let $W\in{\R}^{(n+m)\times(n+m)}$ denote the weight matrix, where $W_{ij}$ denotes the edge-weight between points $i$ and $j$. Inspired by prior work in manifold learning~\cite{roweis2000nonlinear,WeinbergerPS05} we choose the weights to be the coefficients that reconstructs the depth of any point from the depths of its neighbors in $\mathcal{N}_i$. We can solve for these weights with the following constrained quadratic optimization problem: \begin{align} & W=\argmin_{W} \|Z-WZ\|_2^2, \nonumber \\ & \text{s.t.\ } W\mathbf{1}=\mathbf{1} \textrm{ \ and \ } W_{ij}=0 \textrm{ if } j\notin {\mathcal N}_{i}.\label{eq:qp1} \end{align} Here $\mathbf{1}\in \R^{n+m}$ denotes the all-ones vector. As long as we pick $k>3$ and the points are in general positions there are infinitely many solutions that satisfy $Z=WZ$, and we pick the minimum $L_2$ norm solution (obtained with slight $L_2$ regularization) for robustness reasons. \noindent\textbf{Depth Correction.} Let us denote the corrected depth values as $Z'\in \R^{n+m}$, with $Z'=[Z'_{L};Z'_{PL}]$ and $Z'_L\in \R^n$ and $Z'_{PL}\in\R^m$. For the $n$ points with LiDAR measurements we update the depth to the (ground truth) values $Z'_L=G$. We then solve for $Z'_{PL}$ given $G$ and the weighted KNN graph encoded in $W$. Concretely, we update the remaining depths $Z'_{PL}$ such that the depth of any point $i$ can still be be reconstructed with high fidelity as a weighted sum of its KNN neighbors' depths using the learned weights $W$; \ie if point $i:1\leq i\leq n$ is moved to its new depth $G_i$, then its neighbors in $\mathcal{N}_i$ must also be corrected such that $G_i\approx\sum_{j\in{\mathcal{N}}_i} W_{ij}Z'_j.$ Further, the neighbors' neighbors must be corrected and the depth of the few $n$ points propagates across the entire graph. We can solve for the final $Z'$ directly with another quadratic optimization, \begin{align} Z'=\argmin_{Z'} \|Z'W-Z'\|^2, \label{eq:qp2} \text{\ s.t.\ } Z'_{1:n}=G. \end{align} To illustrate the correction process, imagine the simplest case where the depth of only a single point ($n=1$) is updated to $G_1=Z_1+\delta$. A new optimal depth for~\autoref{eq:qp2} is to move all the remaining points similarly, i.e. $Z'=Z+\mathbf{1}\delta$: as $Z=WZ$ and $W\mathbf{1}=\mathbf{1}$ we must have $W(Z+\mathbf{1}\delta)=Z+\mathbf{1}\delta$. In the setting with $n>1$, the least-squares loss ensures a soft diffusion between the different LiDAR depth estimates. Both optimization problems in \autoref{eq:qp1} and \autoref{eq:qp2} can be solved exactly and efficiently with sparse matrix solvers. We summarize the procedure as an algorithm in the supplemental material. From the view of graph-based manifold learning, our GDC algorithm is reminiscent of the locally linear embedding~\cite{roweis2000nonlinear} with landmarks to guide the final solution \cite{WeinbergerPS05}. \autoref{fig:redpurpleblue} illustrates beautifully how the initial 3D point cloud from \method{SDN}\xspace{} (purple) of a car in the KITTI data set is corrected with a few sparse LiDAR measurements (yellow). The resulting points (blue) are right inside the ground-truth box and clearly show the contour of the car. \autoref{fig:depth_comp} shows the additional improvement from the \method{GDC}\xspace{} (blue) over the pure \method{SDN}\xspace{} depth estimates. The error is corrected over the entire image where many regions have no LiDAR measurements. For objects such as cars the improvements through \method{GDC}\xspace{} are far more pronounced, as these typically are touched by the four LiDAR beams and can be corrected effectively. \section{Stereo Depth Network (SDN)} \label{sec:approach} \begin{figure} \centering \includegraphics[width=.8\linewidth]{figures/depth_disp} \caption{\textbf{The disparity-to-depth transform.} We set $f_U=721$ (in pixels) and $b=0.54$ (in meters) in \autoref{eq_disp_depth}, which are the typical values used in the KITTI object detection benchmark.} \label{fig:depth_disparity} \end{figure} A stereo network designed and learned to minimize the disparity error (cf. \autoref{eq_disp_loss}) may over-emphasize nearby objects with smaller depths and therefore perform poorly in estimating depths for far away objects. To see this, note that \autoref{eq_disp_depth} implies that for a given error in disparity $\delta D$, the error in depth, $\delta Z$, increases \emph{quadratically} with depth: \begin{equation} Z \propto \frac{1}{D} \Rightarrow \delta Z \propto \frac{1}{D^2} \delta D \Rightarrow \delta Z \propto Z^2 \delta D, \end{equation} and the middle term is obtained by differentiating $Z(D)$ w.r.t. $D$. In particular, using the settings on the KITTI dataset, a single pixel error in disparity implies only a 0.1m error in depth at a depth of 5 meters, but a 5.8m error at a depth of 50 meters. See~\autoref{fig:depth_disparity} for a mapping from disparity to depth. \noindent\textbf{Depth Loss.} We propose two essential changes to adapt a stereo network for direct depth estimation. First, we learn the stereo network to directly optimize the depth loss \begin{align} \sum_{(u,v)\in \mathcal{A}} \ell(Z(u,v) - Z^\star(u,v)). \label{eq_depth_loss} \end{align} $Z$ and $Z^\star$ can be obtained from $D$ and $D^\star$ respectively using \autoref{eq_disp_depth}. The change from the disparity to the depth loss corrects the disproportionally strong emphasis on tiny depth errors of nearby objects --- a necessary but still insufficient change to overcome the problems of disparity estimation. \begin{figure} \centering \begin{subfigure}[b]{0.23\textwidth} \includegraphics[width=\linewidth]{figures/dl_example3} \label{fig:disp_cost} \end{subfigure} \hfill \begin{subfigure}[b]{0.23\textwidth} \includegraphics[width=\linewidth]{figures/dcv_exmaple3} \label{fig:depth_cost} \end{subfigure} \caption{\textbf{Disparity cost volume (left) vs. depth cost volume (right).} The figure shows the 3D points obtained from LiDAR (yellow) and stereo (pruple) corresponding to a car in the KITTI dataset, seen from the bird's-eye view (BEV). Points from the disparity cost volume are stretched out and noisy; while points from the depth cost volume capture the car contour faithfully.} \label{fig:cost} \end{figure} \noindent\textbf{Depth Cost Volume.} To facilitate accurate depth learning (rather than disparity) we need to address the internals of the depth estimation pipeline. A crucial source of error are the 3D convolutions within the 4D disparity cost volume, where the same convolutional kernels are applied for the entire cost volume. This is highly problematic as it implicitly assumes that the effect of a convolution is homogeneous throughout --- which is clearly violated by the reciprocal depth to disparity relation (\autoref{fig:depth_disparity}). For example, it may be completely appropriate to locally smooth two neighboring pixels with disparity 85.7 and 86.3 (changing the depth by a few cm to smooth out a surface), whereas applying the same kernel for two pixels with disparity 3.7 and 4.3 could easily move the 3D points by 10m or more. \begin{figure} \centering \includegraphics[width=0.95\linewidth]{figures/val_median_three} \caption{\textbf{Depth estimation errors.} We compare depth estimation error on 3,769 validation images of the KITTI data set, taking LiDAR depths as ground truths. We separate pixels according to their truth depths (z).} \label{fig:depth_comp} \end{figure} Taking this insight and the central assumption of convolutions --- all neighborhoods can be operated upon in an identical manner --- into account, we propose to instead construct the depth cost volume $C_\text{depth}$, in which $C_\text{depth}(u, v, z, :)$ will encode features describing how likely the depth $Z(u,v)$ of pixel $(u,v)$ is $z$. The subsequent 3D convolutions will then operate on the grid of depth, rather than disparity, affecting neighboring depths identically, independent of their location. The resulting 3D tensor $S_\text{depth}$ is then used to predict the pixel depth similar to \autoref{eq_disp_pred} \begin{equation} Z(u, v) = \sum_z \softmax(S_\text{depth}(u,v,z))\times z. \nonumber \end{equation} We construct the new depth volume, $C_\text{depth}$, based on the intuition that $C_\text{depth}(u,v,z,:)$ and $C_\text{disp}\left(u,v,\cfrac{f_U\times b}{z},:\right)$ should lead to equivalent ``cost''. To this end, we apply a bilinear interpolation to construct $C_\text{depth}$ from $C_\text{disp}$ using the depth-to-disparity transform in \autoref{eq_disp_depth}. Specifically, we consider disparity in the range of $[0, 191]$ following PSMNet~\cite{chang2018pyramid}, and consider depth in the range of $[1\text{m}, 80\text{m}]$ and set the gird of depth in $C_\text{depth}$ to be 1m. \autoref{fig:PL++} (top) depicts our stereo depth network (\method{SDN}\xspace) pipeline. Crucially, all convolution operations are operated on $C_\text{depth}$ exclusively. \autoref{fig:depth_comp} compares the median values of absolute depth estimation errors using the disparity cost volume (disparity net: \ie, PSMNet) and the depth cost volume (\method{SDN}\xspace{}). As expected, for far away depth, \method{SDN}\xspace{} leads to drastically smaller errors with only marginal increases in the very near range (which disparity based methods over-optimize). \begin{figure*}[t] \centering \includegraphics[width=\linewidth]{figures/whole_model} \caption{\textbf{The whole pipeline of improved stereo depth estimation:} (top) the stereo depth network (\method{SDN}\xspace) constructs a depth cost volume from left-right images and is optimized for direct depth estimation; (bottom) the graph-based depth correction algorithm (\method{GDC}\xspace) refines the depth map by leveraging sparser LiDAR signal. The gray arrows indicates the observer's view point. We superimpose the (green) ground-truth 3D box of a car, the same one in \autoref{fig:redpurpleblue}. The corrected points (blue; bottom right) are perfectly located inside the ground truth box.} \label{fig:PL++} \end{figure*} \section{Background} \label{sec:background} \noindent\textbf{3D object detection.} Most work on 3D object detection operates on 3D point clouds from LiDAR as input~\cite{li20173d,li2016vehicle,meyer2019lasernet,yang2018hdnet,du2018general,shi2019pointrcnn,engelcke2017vote3deep,yan2018second,lang2019pointpillars}. Frustum PointNet~\cite{qi2018frustum} applies PointNet~\cite{qi2017pointnet,qi2017pointnet++} to the points directly, while Voxelnet~\cite{zhou2018voxelnet} quantizes them into 3D grids. For street scenes, several work finds that processing points from the bird's-eye view can already capture object contours and locations~\cite{chen2017multi,yang2018pixor,ku2018joint}. Images have also been used, but mainly to supplement LiDAR~\cite{meyer2019sensor,xu2018pointfusion,liang2018deep,chen2017multi,ku2018joint}. Early work based solely on images --- mostly built on the 2D frontal-view detection pipeline~\cite{ren2015faster,he2017mask,lin2017feature} --- fell far behind in localizing objects in 3D~\cite{li2019gs3d,xiang2015data,xiang2017subcategory,chabot2017deep,mousavian20173d,chen20153d,xu2018multi,chen2016monocular,pham2017robust,chen20183d}. \noindent\textbf{Pseudo-LiDAR.} This gap has been reduced significantly recently with the introduction of the pseudo-LiDAR framework proposed in~\cite{pseudoLiDAR}. This framework applies a drastically different approach from previous image-based 3D object detectors. Instead of directly detecting the 3D bounding boxes from the frontal view of a scene, pseudo-LiDAR begins with image-based depth estimation, predicting the depth $Z(u,v)$ of each image pixel $(u,v)$. The resulting depth map $Z$ is then back-projected into a 3D point cloud: a pixel $(u, v)$ will be transformed to $(x,y,z)$ in 3D by \begin{align} & \text{depth: } z = Z(u, v), \nonumber \\ & \text{width: } x = \frac{(u - c_U)\times z}{f_U}, \label{eq_3D} \\ & \text{height: } y = \frac{(v - c_V)\times z}{f_V}, \nonumber \end{align} where $(c_U, c_V)$ is the camera center and $f_U$ and $f_V$ are the horizontal and vertical focal length. The 3D point cloud is then treated exactly as LiDAR signal --- any LiDAR-based 3D detector can be applied seamlessly. By taking the state-of-the-art algorithms from both ends~\cite{chang2018pyramid, ku2018joint, qi2018frustum}, pseudo-LiDAR obtains the highest image-based performance on the KITTI object detection benchmark~\cite{geiger2012we,geiger2013vision}. Our work builds upon this framework. \noindent\textbf{Stereo disparity estimation.} Pseudo-LiDAR relies heavily on the quality of depth estimation. Essentially, if the estimated pixel depths match those provided by LiDAR, pseudo-LiDAR with any LiDAR-based detector should be able to achieve the same performance as that obtained by applying the same detector to the LiDAR signal. According to~\cite{pseudoLiDAR}, depth estimation from stereo pairs of images~\cite{mayer2016large,yamaguchi2014efficient,chang2018pyramid} are more accurate than that from monocular (\ie, single) images~\cite{fu2018deep,godard2017unsupervised} for 3D object detection. We therefore focus on stereo depth estimation, which is routinely obtained from estimating disparity between images. A disparity estimation algorithm takes a pair of left-right images $I_l$ and $I_r$ as input, captured from a pair of cameras with a horizontal offset (i.e., baseline) $b$. Without loss of generality, we assume that the algorithm treats the left image, $I_l$, as reference and outputs a disparity map $D$ recording the horizontal disparity to $I_r$ for each pixel $(u, v)$. Ideally, $I_l(u, v)$ and $I_r(u, v + D(u, v))$ will picture the same 3D location. We can therefore derive the depth map $Z$ via the following transform ($f_U$: horizontal focal length), \begin{align} Z(u, v) = \frac{f_U \times b}{D(u, v)}. \label{eq_disp_depth} \end{align} A common pipeline of disparity estimation is to first construct a 4D disparity cost volume $C_\text{disp}$, in which $C_\text{disp}(u,v,d,:)$ is a feature vector that captures the pixel difference between $I_l(u,v)$ and $I_r(u,v + d)$. It then estimates the disparity $D(u, v)$ for each pixel $(u, v)$ according to the cost volume $C_\text{disp}$. One basic algorithm is to build a 3D cost volume with $C_\text{disp}(u,v,d) = \|I_l(u,v) - I_r(u,v + d)\|_2$ and determine $D(u,v)$ by $\argmin_d C_\text{disp}(u,v,d)$. Advanced algorithms exploit more robust features in constructing $C_\text{disp}$ and perform structured prediction for $D$. In what follows, we give a concise introduction on PSMNet~\cite{chang2018pyramid}, a state-of-the-art algorithm used in~\cite{pseudoLiDAR}. PSMNet begins with extracting deep feature maps $h_l$ and $h_r$ from $I_l$ and $I_r$, respectively. It then constructs $C_\text{disp}(u,v,d,:)$ by concatenating features of $h_l(u,v)$ and $h_r(u,v+d)$, followed by layers of 3D convolutions. The resulting 3D tensor $S_\text{disp}$, with the feature channel size ending up being one, is then used to derive the pixel disparity via the following weighted combination, \begin{align} D(u, v) = \sum_d \softmax(S_\text{disp}(u,v,d))\times d, \label{eq_disp_pred} \end{align} where $\softmax$ is performed along the 3\textsuperscript{rd} dimension of $S_\text{disp}$. PSMNet can be learned end-to-end, including the image feature extractor and 3D convolution kernels, to minimize the disparity error \begin{align} \sum_{(u,v)\in \mathcal{A}} \ell(D(u,v) - D^\star(u,v)), \label{eq_disp_loss} \end{align} where $\ell$ is the smooth L1 loss, $D^\star$ is the ground truth map, and $\mathcal{A}$ contains pixels with ground truth. \section{Conclusion} \label{sec:disc} In this paper we made two contributions to improve the 3D object detection in autonomous vehicles without expensive LiDAR. First, we identify the disparity estimation as a main source of error for stereo based systems and propose a novel approach to learn depth directly end-to-end instead of through disparity estimates. Second, we advocate that one should not use expensive LiDAR sensors to learn the local structure and depth of objects. Instead one can use commodity stereo cameras for the former and a cheap sparse LiDAR to correct the systematic bias in the resulting depth-estimates. We provide a novel graph propagation algorithm that integrates the two data modalities and propagates the initial depth estimates with two sparse matrix solvers. The resulting system, Pseudo-LiDAR++, performs almost on par with 64-beams LiDAR systems for \$75,000 but only requires 4 beams and two commodity cameras, which could be obtained with a total cost of less than \$800. \subsection{Experimental results} \label{sec:exp_result} \begin{table*}[t] \centering \caption{\textbf{3D object detection results on KITTI validation.} We report AP$_\text{BEV}$\xspace ~/ AP$_\text{3D}$\xspace (in \%) of the \textbf{car} category, corresponding to average precision of the bird's-eye view and 3D object detection. We arrange methods according to the input signals: M for monocular images, S for stereo images, L for 64-beam LiDAR, and L\# for \emph{sparse 4-beam} LiDAR. PL stands for \method{pseudo-LiDAR}\xspace. \emph{Our \method{pseudo-LiDAR}\xspace++ (PL++) with enhanced depth estimation --- \method{SDN}\xspace and \method{GDC}\xspace --- are in {\color{blue} blue}.} Methods with 64-beam LiDAR are in {\color{gray} gray}. Best viewed in color.} \label{tbMain} \begin{tabular}{=l|+c|+c|+c|+c|+c|+c|+c} & & \multicolumn{3}{c|}{IoU = 0.5} & \multicolumn{3}{c}{IoU = 0.7} \\ \cline{3-8} \multicolumn{1}{c|}{Detection algorithm} & Input & Easy & Moderate & Hard & Easy & Moderate & Hard \\ \hline \method{3DOP}\xspace~\cite{chen20153d} & S & 55.0 / 46.0 & 41.3 / 34.6 & 34.6 / 30.1 & 12.6 / 6.6 \hspace{3pt} & 9.5 / 5.1 & 7.6 / 4.1 \\ \method{MLF-stereo}\xspace~\cite{xu2018multi} & S & - & 53.7 / 47.4 & - & - & 19.5 / 9.8 \hspace{3pt} & - \\ \method{S-RCNN}\xspace~\cite{li2019stereo} & S & 87.1 / 85.8 & 74.1 / 66.3 & 58.9 / 57.2 & 68.5 / 54.1 & 48.3 / 36.7 & 41.5 / 31.1 \\ PL: \method{AVOD}\xspace~\cite{pseudoLiDAR} & S & 89.0 / 88.5 & 77.5 / 76.4 & 68.7 / 61.2& 74.9 / 61.9 & 56.8 / 45.3 & 49.0 / 39.0 \\ PL: \method{PIXOR$^\star$}\xspace & S & 89.0 / - \hspace{12pt} & 75.2 / - \hspace{12pt} & 67.3 / - \hspace{12pt} & 73.9 / - \hspace{12pt} & 54.0 / - \hspace{12pt} & 46.9 / - \hspace{12pt} \\ PL: \method{P-RCNN}\xspace & S & 88.4 / 88.0 & 76.6 / 73.7 & 69.0 / 67.8 & 73.4 / 62.3 & 56.0 / 44.9 & 52.7 / 41.6 \\ \hline \rowstyle{\color{blue}} \hspace{-2.8pt}PL++: \method{AVOD}\xspace & S & 89.4 / 89.0 & 79.0 / 77.8 & 70.1 / 69.1 & 77.0 / 63.2 & 63.7 / 46.8 & 56.0 / 39.8 \\ \rowstyle{\color{blue}} \hspace{-2.8pt}PL++: \method{PIXOR$^\star$}\xspace & S & 89.9 / - \hspace{12pt} & 78.4 / - \hspace{12pt} & 74.7 / - \hspace{12pt} & 79.7 / - \hspace{12pt} & 61.1 / - \hspace{12pt} & 54.5 / - \hspace{12pt} \\ \rowstyle{\color{blue}} \hspace{-2.8pt}PL++: \method{P-RCNN}\xspace & S & 89.8 / 89.7 & 83.8 / 78.6 & 77.5 / 75.1 & 82.0 / 67.9 & 64.0 / 50.1 & 57.3 / 45.3 \\\hline \rowstyle{\color{blue}} \hspace{-2.8pt}PL++: \method{AVOD}\xspace & L\# + S & 90.2 / 90.1 & 87.7 / 86.9 & 79.8 / 79.2 & 86.8 / 70.7 & 76.6 / 56.2 & 68.7 / 53.4 \\ \rowstyle{\color{blue}} \hspace{-2.8pt}PL++: \method{PIXOR$^\star$}\xspace & L\# + S & 95.1 / - \hspace{12pt} & 85.1 / - \hspace{12pt} & 78.3 / - \hspace{12pt} & 84.0 / - \hspace{12pt} & 71.0 / - \hspace{12pt} & 65.2 / - \hspace{12pt} \\ \rowstyle{\color{blue}} \hspace{-2.8pt}PL++: \method{P-RCNN}\xspace & L\# + S & 90.3 / 90.3 & 87.7 / 86.9 & 84.6 / 84.2 & 88.2 / 75.1 & 76.9 / 63.8 & 73.4 / 57.4 \\ \hline \rowstyle{\color{gray}} \hspace{-2.8pt}\method{AVOD}\xspace~\cite{ku2018joint} & L + M & 90.5 / 90.5 & 89.4 / 89.2 & 88.5 / 88.2 & 89.4 / 82.8 & 86.5 / 73.5 & 79.3 / 67.1 \\ \rowstyle{\color{gray}} \hspace{-2.8pt}\method{PIXOR$^\star$}\xspace~\cite{yang2018pixor, liang2018deep} & L + M & 94.2 / - \hspace{12pt} & 86.7 / - \hspace{12pt} & 86.1 / - \hspace{12pt} & 85.2 / - \hspace{12pt} & 81.2 / - \hspace{12pt} & 76.1 / - \hspace{12pt} \\ \rowstyle{\color{gray}} \hspace{-2.8pt}\method{P-RCNN}\xspace~\cite{shi2019pointrcnn} & L & 96.3 / 96.1 & 88.6 / 88.5 & 88.6 / 88.5 & 87.8 / 81.7 & 86.0 / 74.4 & 85.8 / 74.5 \\ \hline \end{tabular} \end{table*} We summarize the main results on KITTI object detection in \autoref{tbMain}. Several important trends can be observed: \textbf{1)} Our PL++ with enhanced depth estimations by \method{SDN}\xspace and \method{GDC}\xspace yields consistent improvement over PL across all settings; \textbf{2)} PL++ with \method{GDC}\xspace refinement of 4 laser beams (INPUT: L\# + S) performs significantly better than PL++ with only stereo inputs (INPUT: S); \textbf{3)} PL experiences a substantial drop in accuracy from IoU 0.5 to 0.7 for \emph{hard} objects. This indicates that PL does indeed manage to detect objects that are far away, but systematically places them at the wrong depth. Once an overlap of 0.7 is required (IoU = 0.7), the object is too far out of place and is no longer registered as detect. Interestingly, here is where we experience the largest gain --- from PL: \method{P-RCNN}\xspace (AP$_\text{BEV}$\xspace$=52.7$) to PL++: \method{P-RCNN}\xspace (AP$_\text{BEV}$\xspace$=73.4$) with input as L\# + S. Note that the majority of the gain originates from \method{GDC}\xspace{}, as PL++ with solely stereo input only improves the score to $57.3$ AP$_\text{BEV}$\xspace. \textbf{4)} Compared to LiDAR, PL++ is only outperformed by at most $13\%$ AP$_\text{BEV}$\xspace, even at the hard case under IoU at 0.7. \textbf{5)} For IoU at 0.5, with the aid of only 4 LiDAR beams, PL++ is boosted to a level comparable to models with 64-beam LiDAR signals. \begin{table} \centering \tabcolsep 3pt \caption{3D object detection results on the \textbf{car} category on the \emph{test} set. We compare our methods (in {\color{blue}blue}) and 64-beam LiDAR (in {\color{gray} gray}), using \method{P-RCNN}\xspace as the object detector. We report AP$_\text{BEV}$\xspace~/ AP$_\text{3D}$\xspace at IoU = 0.7. $\dagger$: Results from the KITTI leaderboard.} \label{tbTest} \begin{tabular}{=l|+c|+c|+c} Input signal & Easy & Moderate & Hard \\ \hline \rowstyle{\color{blue}} PL++ (\method{SDN}\xspace) & 75.5 / 60.4 & 57.2 / 44.6 & 53.4 / 38.5 \\ \rowstyle{\color{blue}} PL++ (\method{SDN}\xspace+\method{GDC}\xspace) & 83.8 / 68.5 & 73.5 / 54.7 & 66.5 / 51.2\\ \rowstyle{\color{gray}} $\dagger$LiDAR & 89.5 / 85.9 & 85.7 / 75.8 & 79.1 / 68.3\\ \hline \end{tabular} \end{table} \noindent\textbf{Results on the secret KITTI test set.} \autoref{tbTest} summarizes our test results for the car category on the KITTI test set server. We see a similar gap between our methods and LiDAR as on the validation set, suggesting that our approach does not simply over-fit to the validation data. There is no category for 4-beam LiDAR, but at the time of submission, our approach without LiDAR refinement (pure \method{SDN}\xspace{}) is placed at the top position among all the image-based algorithms on the KITTI leaderboard. In the following sections, we conduct a series of experiments to analyze the performance gain by our approaches and discuss several key observations. \emph{We will mainly experiment with \method{P-RCNN}\xspace: we find that the results with \method{AVOD}\xspace and \method{PIXOR$^\star$}\xspace follow similar trends and include them in the supplemental material.} \begin{table} \centering \caption{\textbf{Ablation study on stereo depth estimation.} We report AP$_\text{BEV}$\xspace ~/ AP$_\text{3D}$\xspace (in \%) of the \textbf{car} category at IoU$=0.7$ on KITTI validation. DL: depth loss. The best result of each column is in bold font. \label{tbl:ablation_sdn}} \tabcolsep 3pt \begin{tabular}{l|c|c|c} \multicolumn{1}{c|}{\multirow{2}{*}{Stereo depth}} & \multicolumn{3}{c}{\method{P-RCNN}\xspace} \\ \cline{2-4} \multicolumn{1}{c|}{} & Easy & Moderate & Hard \\ \hline \method{PSMNet}\xspace & 73.3 / 62.3 & 55.9 / 44.8 & 52.6 / 41.4 \\ \method{PSMNet}\xspace + DL & 80.1 / 65.5 & 61.9 / 46.8 & 56.0 / 43.0 \\ \method{SDN}\xspace & \textbf{82.0} / \textbf{67.9} & \textbf{64.0} / \textbf{50.1} & \textbf{57.3} / \textbf{45.3} \\ \hline \end{tabular} \end{table} \noindent\textbf{Depth loss and depth cost volume.} To turn a disparity network (\eg, \method{PSMNet}\xspace) into \method{SDN}\xspace, there are two subsequent changes: \textbf{1)} change the disparity loss into the depth loss; \textbf{2)} change the disparity cost volume into the depth cost volume. In \autoref{tbl:ablation_sdn}, we uncover the effect of these two changes separately. Regarding AP$_\text{BEV}$\xspace/AP$_\text{3D}$\xspace (moderate), the metric used in the KITTI leaderboard, the depth loss gains us $6\% / 2\%$ improvement, while the depth cost volume brings another $2\%/3\%$. Essentially, we demonstrate that the two components are complementary to improve depth estimation. \begin{table} \centering \tabcolsep 3pt \caption{\textbf{Ablation study on leveraging sparse LiDAR.} We report AP$_\text{BEV}$\xspace ~/ AP$_\text{3D}$\xspace (in \%) of the \textbf{car} category at IoU$=0.7$ on KITTI validation. L\#: 4-beam LiDAR signal alone. \method{SDN}\xspace + L\#: pseudo-LiDAR with corresponding parts replaced by 4-beam LiDAR. The best result of each column is in bold font. See text for details. \label{tbl:ablation_lidar}} \begin{tabular}{l|c|c|c} \multicolumn{1}{c|}{\multirow{2}{*}{Stereo depth}} & \multicolumn{3}{c}{\method{P-RCNN}\xspace} \\ \cline{2-4} \multicolumn{1}{c|}{} & Easy & Moderate & Hard \\ \hline \method{SDN}\xspace & 82.0 / 67.9 & 64.0 / 50.1 & 57.3 / 45.3 \\ L\# & 73.2 / 56.1 & 71.3 / 53.1 & 70.5 / 51.5 \\ \method{SDN}\xspace + L\# & 86.3 / 72.0 & 73.0 / 56.1 & 67.4 / 54.1 \\ \method{SDN}\xspace + \method{GDC}\xspace & \textbf{88.2} / \textbf{75.1} & \textbf{76.9} / \textbf{63.8} & \textbf{73.4} / \textbf{57.4} \\ \hline \end{tabular} \end{table} \noindent\textbf{Impact of sparse LiDAR beams.} In \method{pseudo-LiDAR}\xspace++, we leverage 4-beam LiDAR by \method{GDC}\xspace to correct stereo depth. We then ask the following question: is it possible that the gain solely comes from adding 4-beam LiDAR points? In \autoref{tbl:ablation_lidar}, we study this question by comparing the detection result against that of models using \textbf{1)} sole 4-beam LiDAR point clouds and \textbf{2)} pseudo-LiDAR point clouds with corresponding parts replaced by 4-beam LiDAR. It can be seen that 4-beam LiDAR itself performs fairly well on locating far away objects but cannot capture close objects precisely, while simply replacing pseudo-LiDAR with LiDAR prevents the model from detecting far away object accurately. In contrast, our proposed \method{GDC}\xspace method effectively combines the merits of the two signals, achieving superior performance than using them alone. \subsection{Setup} \label{sec:exp_setup} We refer to our combined method (\method{SDN}\xspace{} and \method{GDC}\xspace{}) for 3D object detection as \method{pseudo-LiDAR}\xspace{}++ (PL++ in short). To analyze the contribution of each component, we evaluate \method{SDN}\xspace{} and \method{GDC}\xspace{} independently and jointly across several settings. For \method{GDC}\xspace we set $k=10$ and consider adding signal from a (simulated) 4-beam LiDAR, unless stated otherwise. \noindent\textbf{Dataset, Metrics, and Baselines.} We evaluate on the KITTI dataset~\cite{geiger2013vision,geiger2012we}, which contains 7,481 and 7,518 images for training and testing. We follow~\cite{chen20153d} to separate the 7,481 images into 3,712 for training and 3,769 validation. For each (left) image, KITTI provides the corresponding right image, the 64-beam Velodyne LiDAR point cloud, and the camera calibration matrices. We focus on 3D object detection and bird's-eye-view (BEV) localization and report results on the \emph{validation set}. Specifically, we focus on the ``car'' category, following~\cite{chen2017multi, xu2018pointfusion}. We report average precision (AP) with IoU (Intersection over Union) thresholds at 0.5 and 0.7. We denote AP for the 3D and BEV tasks by AP$_\text{3D}$\xspace and AP$_\text{BEV}$\xspace. KITTI divides each category into easy, moderate, and hard cases, according to the 2D box height and occlusion/truncation level. We compare to four stereo-based detectors: \method{pseudo-LiDAR}\xspace~(PL in short)~\cite{pseudoLiDAR}, \method{3DOP}\xspace~\cite{chen20153d}, \method{S-RCNN}\xspace\cite{li2019stereo}, and \method{MLF-stereo}\xspace~\cite{xu2018multi}. \noindent\textbf{Stereo depth network (\method{SDN}\xspace).} We use \method{PSMNet}\xspace~\cite{chang2018pyramid} as the backbone for our stereo depth estimation network (\method{SDN}\xspace). We follow~\cite{pseudoLiDAR} to pre-train \method{SDN}\xspace{} on the synthetic Scene Flow dataset~\cite{mayer2016large} and fine-tune it on the 3,712 training images of KITTI. We obtain depth ground truth of these images by projecting the corresponding LiDAR points onto images. We also train a \method{PSMNet}\xspace in the same way for comparison, which minimizes disparity error. \noindent\textbf{3D object detection.} We apply three algorithms for 3D object detection: \method{AVOD}\xspace~\cite{ku2018joint}, \method{PIXOR}\xspace~\cite{yang2018pixor}, and \method{P-RCNN}\xspace~\cite{shi2019pointrcnn}. All can utilize information from LiDAR and/or monocular images. We use the released implementations of \method{AVOD}\xspace (more specifically, \method{AVOD}\xspace-FPN) and \method{P-RCNN}\xspace. We implement \method{PIXOR}\xspace ourselves with a slight modification to include visual information (denoted as \method{PIXOR$^\star$}\xspace). We train all models on the 3,712 training data from scratch by replacing the LiDAR points with pseudo-LiDAR data generated from stereo depth estimation (see the supplemental material for details.) \noindent\textbf{Sparser LiDAR.} We simulate sparser LiDAR signal with fewer beams by first projecting the 64-beam LiDAR points onto a 2D plane of horizontal and vertical angles. We quantize the vertical angles into 64 levels with an interval of $0.4^{\circ}$, which is close to the SPEC of the 64-beam LiDAR. We keep points fallen into a subset of beams to mimic the sparser signal (see the supplemental material for details.) \section{Experiments} \label{sec:exp} \input{exp_setup} \input{exp_result} \section{Introduction} \label{sec:intro} Safe driving in autonomous cars requires the detection and accurate 3D localization of cars, pedestrians and other objects. This in turn requires accurate depth information, which can be obtained from LiDAR (Light Detection And Ranging) sensors. Although highly precise and reliable, LiDAR sensors are notoriously expensive: a 64-beam model can cost around \$75,000 (USD).\footnote{The information is obtained from the automotive LiDAR market report:~\url{http://www.woodsidecap.com/wp-content/uploads/2018/04/Yole_WCP-LiDAR-Report_April-2018-FINAL.pdf}} The alternative is to obtain depth information through inexpensive commodity cameras. However, in spite of recent dramatic progress in stereo-based 3D object detection brought by pseudo-LiDAR~\cite{pseudoLiDAR}, a significant performance gap remains especially for far away objects (which we want to detect early to allow time for reaction). The trade-off between affordability and safety creates an ethical dilemma. \begin{figure} \includegraphics[width=\linewidth]{figures/teaser_light.png} \caption{\textbf{An illustration of our proposed depth estimation and correction method.} The green box is the ground truth location of the car in the KITTI data set. The red points are obtained with a stereo disparity network. Purple points, obtained with our stereo depth network (SDN), are much closer to the truth. After depth propagation (blue points) with a few (yellow) LiDAR measurements the car is squarely inside the green box. (One floor square is 1m$\times$1m.) \label{fig:redpurpleblue}} \end{figure} In this paper we propose a possible solution to this remaining challenge that combines insights from both perspectives. We observe that the higher 3D object localization error of stereo-based systems stems entirely from the higher error in depth estimation (after the 3D point cloud is obtained the two approaches are identical~\cite{pseudoLiDAR}). Importantly, this error is not random but \emph{systematic}: we observe that stereo methods do indeed \emph{detect} objects with high reliability, yet they estimate the depth of the \emph{entire} object as either too far or too close. See \autoref{fig:redpurpleblue} for an illustration: the red stereo points capture the car but are shifted by about 2m completely outside the ground-truth location (green box). If we can de-bias these depth estimates it should be possible to obtain accurate 3D localization even for distant objects without exorbitant costs. We start by revisiting the depth estimation routine embedded at the heart of state-of-the-art stereo-based 3D detection approaches~\cite{pseudoLiDAR}. A major contributor to the systematic depth bias comes from the fact that depth is typically not computed directly. Instead, one first estimates the \emph{disparity} --- the horizontal shift of a pixel between the left and right images --- and then \emph{inverts} it to obtain pixel-wise depth. While the use of deep neural networks has largely improved disparity estimation~\cite{chang2018pyramid,cheng2018depth,mayer2016large,wang2018anytime}, designing and learning the networks to optimize the accuracy of \emph{disparity estimation} simply over-emphasizes nearby objects due to the reciprocal transformation. For instance, a unit disparity error (in pixels) for a 5-meter-away object means a 10cm error in depth: the length of a side mirror. The same disparity error for a 50-meter-away object, however, becomes a 5.8m error in depth: the length of an entire car. Penalizing both errors equally means that the network spends more time correcting subtle errors on nearby objects than gross errors on far away objects, resulting in degraded depth estimates and ultimately poor detection and localization for far away objects. We thus propose to adapt the stereo network architecture and loss function for direct depth estimation. Concretely, the cost volume that fuses the left-right images and the subsequent 3D convolutions are the key components in stereo networks. Taking the central assumption of convolutions --- all neighborhood can be operated in an identical manner --- we propose to construct the cost volume on the grid of depth rather than disparity, enabling 3D convolutions and the loss function to perform exactly on the right scale for depth estimation. We refer to our network as stereo depth network (\method{SDN}\xspace). See~\autoref{fig:redpurpleblue} for a comparison of 3D points obtained with SDN (purple) and disparity estimation (red). Although our \method{SDN}\xspace{} improves the depth estimates significantly, stereo images are still inherently 2D and it is unclear if they can ever match the accuracy and reliability of a true 3D LiDAR sensor. Although LiDAR sensors with 32 or 64 beams are expensive, LiDAR sensors with only 4 beams are two orders of magnitude cheaper\footnote{The Ibeo Wide Angle Scanning (ScaLa) sensor with 4 beams cost \$600 (USD). In this paper we simulate the 4-beam LiDAR response on KITTI benchmark~\cite{geiger2012we,geiger2013vision} by sparsifying the original 64-beam signal.} and thus easily affordable. The 4 laser beams are very sparse and ill-suited to capture 3D object shapes by themselves, but if paired with stereo images they become the ideal tool to de-bias our dense stereo depth estimates: a single high-precision laser beam may inform us how to correct the depth of an entire car or pedestrian in its path. To this end, we present a novel depth-propagation algorithm, inspired by graph-based manifold learning~\cite{WeinbergerPS05,roweis2000nonlinear,xiaojin2002learning}. In a nutshell, we connect our estimated 3D stereo point cloud locally by a nearest neighbor graph, such that points corresponding to the same object will share many local paths with each other. We match the few but exact LiDAR measurements first with pixels (independent of depth) and then with their corresponding 3D points to obtain accurate depth estimates for several nodes in the graph. Finally, we propagate this exact depth information along the graph using a label diffusion mechanism --- resulting in a \emph{dense and accurate depth map} at \emph{negligible cost}. In \autoref{fig:redpurpleblue} we see that the few (yellow) LiDAR measurements are sufficient to position almost all final (blue) points of the entire car within the green ground truth box. We conduct extensive empirical studies of our approaches on the KITTI object detection benchmark~\cite{geiger2012we,geiger2013vision} and achieve remarkable results. With solely stereo images, we outperform the previous sate-of-the-art~\cite{pseudoLiDAR} by $10\%$. Further adding a cheap 4-beam LiDAR brings another $27\%$ relative improvement --- on some metrics, our approach is nearly on par with those based on a 64-beam LiDAR but can potentially save $95\%$ in cost. \section*{Acknowledgments} This research is supported by grants from the National Science Foundation NSF (III-1618134, III-1526012, IIS-1149882, IIS-1724282, and TRIPODS-1740822), the Office of Naval Research DOD (N00014-17-1-2175), the Bill and Melinda Gates Foundation, and the Cornell Center for Materials Research with funding from the NSF MRSEC program (DMR-1719875). We are thankful for generous support by Zillow and SAP America Inc. We thank Gao Huang for helpful discussion. {\small \bibliographystyle{ieee} \section{Graph-based Depth Correction (\method{GDC}\xspace) Algorithm} \label{sec:sup_gdc} Here we present the \method{GDC}\xspace algorithm in detail (see \autoref{alg::GDC}). The two steps described in the main paper can be easily turned into two (sparse) linear systems and then solved by using Lagrange multipliers. For the first step, we solve a problem that is slightly modified from that described in the main paper (for more accurate reconstruction). For the second step, we use the \emph{Generalized Minimal Residual Method} (GMRES) to iteratively solve the sparse linear system. \begin{algorithm*} \caption{Graph-based depth correction (\method{GDC}\xspace). ``$;$'' stands for column-wise concatenation. \label{alg::GDC}} \KwIn{Stereo depth map $\textcolor{lightpurple}{Z}\in\R^{(n+m)\times 1}$, the corresponding pseudo-LiDAR (PL) point cloud $P \in \mathbb{R}^{(n+m)\times 3}$, and LiDAR depths $G\in \R^{n\times 1}$ on the first the $n$ pixels.} \KwOut{Corrected depth map $\textcolor{lightblue}{Z'} \in \R^{(n+m)\times 1}$} \SetAlgoLined \SetKwBlock{Begin}{function}{end function} \Begin($\text{\method{GDC}\xspace} {(} \textcolor{lightpurple}{Z}, P, G, K {)}$){ Solve: $W = \arg\min_{W\in\R^{(n+m)\times(n+m)}} \|W\|^2$ \\ \hspace{2.55em} s.t. ${Z} - W\cdot {Z} = 0$,\\ \hspace{4em} $W_{ij} = 0$ if $j\notin\mathcal{N}_i$ according to $P$,\\ \hspace{4em} $\sum_{j}W_{ij} = 1$ for $\forall i = 1, \dots, n+m$.\\ Solve: $Z_{PL}' = \arg\min_{Z_{PL}'\in \R^{m\times 1}} \|[G; Z_{PL}'] - W[G; Z_{PL}']\|^2$\\ \Return $[G; Z_{PL}']$ } \end{algorithm*} \section{Experimental Setup} \label{ssec:ES} \subsection{Sparse LiDAR generation} \label{ssec:sparse} In this section, we explain how we generate sparser LiDAR with fewer beams from a 64-beam LiDAR point cloud from KITTI dataset in detail. For every point $(x_i,y_i,z_i)\in\R^3$ of the point cloud in one scene (in LiDAR coordinate system ($x$: front, $y$: left, $z$: up, and $(0, 0, 0)$ is the location of the LiDAR sensor)), we compute the elevation angle $\theta_i$ to the LiDAR sensor as \begin{displaymath} \theta_i = \arg\cos\left(\frac{\sqrt{x_i^2 + y_i^2}}{\sqrt{x_i^2 + y_i^2 + z_i^2}}\right). \end{displaymath} We order the points by their elevation angles and slice them into separate lines by step $0.4^{\circ}$, starting from $-23.6^{\circ}$ (close to the Velodyne 64-beam LiDAR SPEC). We select LiDAR points whose elevation angles fall within $[-2.4^{\circ}, -2.0^{\circ}) \cup [-0.8^{\circ}, -0.4^{\circ})$ to be the 2-beam LiDAR signal, and similarly $ [-2.4^{\circ}, -2.0^{\circ}) \cup [-1.6^{\circ}, -1.2^{\circ}) \cup [-0.8^{\circ}, -0.4^{\circ}) \cup [0.0^{\circ}, 0.4^{\circ})$ to be the 4-beam LiDAR signal. We choose them in such a way that consecutive lines has a $0.8^{\circ}$ interval, following the SPEC of the ``cheap'' 4-beam LiDAR ScaLa. We visualize these sparsed LiDAR point clouds from the bird's-eye view on one example scene in \autoref{fig::bevsparsed}. \begin{figure*}[!htb] \centering \begin{subfigure}[b]{0.29\textwidth} \includegraphics[width=\textwidth]{figures/v_lidar2L.png} \caption{2-beam} \end{subfigure} \begin{subfigure}[b]{0.29\textwidth} \includegraphics[width=\textwidth]{figures/v_lidar4L.png} \caption{4-beam} \end{subfigure} \begin{subfigure}[b]{0.29\textwidth} \includegraphics[width=\textwidth]{figures/v_lidar64L.png} \caption{64-beam (full)} \end{subfigure} \caption{Bird's-eye views of sparsed LiDAR point clouds on an example scene. The observer is on the bottom side looking up. We filter out points not visible from the left-image. (One floor square is 10m $\times$ 10m.) \label{fig::bevsparsed}} \end{figure*} \subsection{3D object detection algorithms} \label{ssec:3D} In this section, we provide more details about the way we train 3D object detection models on pseudo-LiDAR point clouds. For \method{AVOD}\xspace, we use the same model as in \cite{pseudoLiDAR}. For \method{P-RCNN}\xspace, we use the implementation provided by the authors. Since the \method{P-RCNN}\xspace model exploits the sparse nature of LiDAR point clouds, when training it with pseudo-LiDAR input, we will first sparsify the point clouds into 64 beams using the method described in \autoref{ssec:sparse}. For \method{PIXOR$^\star$}\xspace, we implement the same base model structure and data augmentation specified in \cite{yang2018pixor}, but without the ``decode fine-tune'' step and focal loss. Inspired by the trick in \cite{liang2018deep}, we add another image feature (ResNet-18~\cite{he2016deep}) branch along the LiDAR branch, and concatenate the corresponding image features onto the LiDAR branch at each stage. We train \method{PIXOR$^\star$}\xspace using RMSProp with momentum $0.9$, learning rate $10^{-5}$ (decay by 10 after 50 and 80 epochs) for 90 epochs. The BEV evaluation results are similar to the reported results, see \autoref{tbMain}. \section{Additional Results} \label{ssec:AR} \subsection{Ablation study} \label{ssec:AS} In \autoref{stbl:ablation_sdn} and \autoref{stbl:ablation_lidar} we provide more experimental results aligned with experiments in \autoref{sec:exp_result} of the main paper. We conduct the same experiments on two other models, \method{AVOD}\xspace and \method{PIXOR$^\star$}\xspace, and observe similar trends of improvements brought by learning with the depth loss (from \method{PSMNet}\xspace to \method{PSMNet}\xspace+DL), constructing the depth cost volume (from \method{PSMNet}\xspace+DL to \method{SDN}\xspace), and applying \method{GDC}\xspace to correct the bias in stereo depth estimation (comparing \method{SDN}\xspace+\method{GDC}\xspace with \method{SDN}\xspace). \begin{table*}[hbt!] \centering \caption{\textbf{Ablation study on stereo depth estimation.} We report AP$_\text{BEV}$\xspace ~/ AP$_\text{3D}$\xspace (in \%) of the \textbf{car} category at IoU$=0.7$ on the KITTI validation set. DL stands for depth loss. \label{stbl:ablation_sdn}} \tabcolsep 2.5pt \begin{tabular}{l|c|c|c|c|c|c} \hline \multicolumn{1}{c|}{\multirow{2}{*}{Depth Estimation}} & \multicolumn{3}{c|}{\method{PIXOR$^\star$}\xspace} & \multicolumn{3}{c}{\method{AVOD}\xspace} \\ \cline{2-7} \multicolumn{1}{c|}{} & Easy & Moderate & Hard & Easy & Moderate & Hard \\ \hline \method{PSMNet}\xspace & 73.9 / - \hspace{10pt} & 54.0 / - \hspace{10pt} & 46.9 / - \hspace{10pt} & 74.9 / 61.9 & 56.8 / 45.3 & 49.0 / 39.0 \\ \method{PSMNet}\xspace + DL & 75.8 / - \hspace{10pt} & 56.2 / - \hspace{10pt} & 51.9 / - \hspace{10pt} & 75.7 / 60.5 & 57.1 / 44.8 & 49.2 / 38.4 \\ \method{SDN}\xspace & 79.7 / - \hspace{10pt} & 61.1 / - \hspace{10pt} & 54.5 / - \hspace{10pt} & 77.0 / 63.2 & 63.7 / 46.8 & 56.0 / 39.8 \\ \hline \end{tabular} \end{table*} \begin{table*}[hbt!] \centering \caption{\textbf{Ablation study on leveraging sparse LiDAR.} We report AP$_\text{BEV}$\xspace ~/ AP$_\text{3D}$\xspace (in \%) of the \textbf{car} category at IoU$=0.7$ on the KITTI validation set. L\# stands for 4-beam LiDAR signal. \method{SDN}\xspace+L\# means we simply replace the depth of a portion of pseudo-LiDAR points by L\#. \label{stbl:ablation_lidar}} \tabcolsep 2.5pt \begin{tabular}{l|c|c|c|c|c|c} \hline \multicolumn{1}{c|}{\multirow{2}{*}{Depth Estimation}} & \multicolumn{3}{c|}{\method{PIXOR$^\star$}\xspace} & \multicolumn{3}{c}{\method{AVOD}\xspace} \\ \cline{2-7} \multicolumn{1}{c|}{} & Easy & Moderate & Hard & Easy & Moderate & Hard \\ \hline \method{SDN}\xspace & 79.7 / - \hspace{10pt} & 61.1 / - \hspace{10pt} & 54.5 / - \hspace{10pt} & 77.0 / 63.2 & 63.7 / 46.8 & 56.0 / 39.8 \\ L\# & 72.0 / - \hspace{10pt} & 64.7 / - \hspace{10pt} & 63.6 / - \hspace{10pt} & 77.0 / 62.1 & 68.8 / 54.7 & 67.1 / 53.0 \\ \method{SDN}\xspace + L\# & 75.6 / - \hspace{10pt} & 59.4 / - \hspace{10pt} & 53.2 / - \hspace{10pt} & 84.1 / 66.0 & 67.0 / 53.1 & 58.8 / 46.4 \\ \method{SDN}\xspace + \method{GDC}\xspace & 84.0 / - \hspace{10pt} & 71.0 / - \hspace{10pt} & 65.2 / - \hspace{10pt} & 86.8 / 70.7 & 76.6 / 56.2 & 68.7 / 53.4 \\ \hline \end{tabular} \end{table*} \subsection{Using fewer LiDAR beams} \label{ssec:FewerLiDAR} In PL++ (\ie, \method{SDN}\xspace+ \method{GDC}\xspace), we use 4-beam LiDAR to correct the predicted point cloud. In \autoref{tbl:ablation_beam}, we investigate using fewer (and also potentially cheaper) LiDAR beams for depth correction. We observe that even with 2 beams, \method{GDC}\xspace can already manage to combine the two signals and yield a better performance than using 2-beam LiDAR or pseudo-LiDAR alone. \begin{table*}[htb!] \centering \caption{\textbf{Ablation study on the sparsity of LiDAR.} We report AP$_\text{BEV}$\xspace ~/ AP$_\text{3D}$\xspace (in \%) of the \textbf{car} category at IoU$=0.7$ on the KITTI validation set. L\# stands for using sparse LiDAR signal alone. The number in brackets indicates the number of beams in use. \label{tbl:ablation_beam}} \tabcolsep 2.5pt \begin{tabular}{l|c|c|c|c|c|c} \hline \multicolumn{1}{c|}{\multirow{2}{*}{Depth Estimation}} & \multicolumn{3}{c|}{\method{P-RCNN}\xspace} & \multicolumn{3}{c}{\method{PIXOR$^\star$}\xspace} \\ \cline{2-7} \multicolumn{1}{c|}{} & Easy & Moderate & Hard & Easy & Moderate & Hard \\ \hline L\# (2) & 69.2 / 46.3 & 62.8 / 41.9 & 61.3 / 40.0 & 66.8 / - \hspace{10pt} & 55.5 / - \hspace{10pt} & 53.3 / - \hspace{10pt} \\ L\# (4) & 73.2 / 56.1 & 71.3 / 53.1 & 70.5 / 51.5 & 72.0 / - \hspace{10pt} & 64.7 / - \hspace{10pt} & 63.6 / - \hspace{10pt} \\ \hline \method{SDN}\xspace + \method{GDC}\xspace (2) & 87.2 / 73.3 & 72.0 / 56.6 & 67.1 / 54.1 & 82.0 / - \hspace{10pt} & 65.3 / - \hspace{10pt} & 61.7 / - \hspace{10pt} \\ \method{SDN}\xspace + \method{GDC}\xspace (4) & 88.2 / 75.1 & 76.9 / 63.8 & 73.4 / 57.4 & 84.0 / - \hspace{10pt} & 71.0 / - \hspace{10pt} & 65.2 / - \hspace{10pt} \\ \hline \end{tabular} \end{table*} \subsection{Qualitative results} \label{ssec:QR} In \autoref{fig:qualitative}, we show detection results using \method{P-RCNN}\xspace with different input signals on a randomly chosen scene in the KITTI object validation set. Specifically, we show the results from the frontal-view images and the bird's-eye view (BEV) point clouds. In the BEV map, the observer is on the left-hand side looking to the right. For nearby objects (\ie, bounding boxes close to the left in the BEV map), we see that \method{P-RCNN}\xspace with any point cloud performs fairly well in localization. However, for far away objects (\ie, bounding boxes close to the right), \method{pseudo-LiDAR}\xspace with depth estimated from \method{PSMNet}\xspace predicts objects (green boxes) deviated from the ground truths (red boxes). Moreover, the noisy \method{PSMNet}\xspace points also leads to several false positives. In contrast, the detected boxes by our \method{pseudo-LiDAR}\xspace++, either with \method{SDN}\xspace alone or with \method{SDN}\xspace+\method{GDC}\xspace, aligns pretty well with the ground truth boxes, justifying our targeted improvement in estimating far away depths. \begin{figure*}[htb!] \centering \includegraphics[width=.8\linewidth]{figures/visualization.png} \caption{\textbf{Qualitative Comparison.} We show the detection results on a KITTI validation scene by \method{P-RCNN}\xspace with different input point clouds. We visualize them from both frontal-view images and bird's-eye view (BEV) point maps. Ground-truth boxes are in red and predicted bounding boxes are in green. The observer is at the left-hand side of the BEV map looking to the right. In other words, ground truth boxes on the right are more far away (\ie deeper) from the observer, and hence hard to localize. Best viewed in color. \label{fig:qualitative}} \end{figure*}
{'timestamp': '2019-08-27T02:17:04', 'yymm': '1906', 'arxiv_id': '1906.06310', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06310'}
arxiv
\section{Introduction and related work} Multidimensional convolution arises in several mathematical models across different fields and is the cornerstone of Convolutional Neural Networks (CNNs)~\citep{krizhevsky2012imagenet,lecun1998gradient}. Indeed, the convolution operator is the key layer of CNNs, enabling them to effectively learn from high-dimensional data by mitigating the curse of dimensionality~\citep{poggio2018theory}. However, CNNs are computational demanding models, with the computational cost associated to convolutions being dominant during both training and inference. Therefore, there is an increasing interest in improving the efficiency of multidimensional convolutions. Several efficient implementations of convolutions have been proposed. For instance, 2D convolution can be efficiently implemented as matrix multiplication by converting the convolution kernel to a Toeplitz matrix. However, this procedure requires replicating the kernel values multiple times across different matrix columns in the Toeplitz matrix and hence the memory requirements are increased. Implementing convolutions via the im2col approach is also memory intensive due to the space required for building the column matrix. The space requirements of these approaches may be far too large to fit in the memory of a mobile or embedded devices hindering the deployment of CNNs in resource-limited platforms. In general, most existing attempts to efficient convolutions are isolated and there currently is no unified framework to study them. In particular we are interested in two different branches, which we review here after. First, approaches that leverage tensor methods for efficient convolutions, either to compress or reformulate them for speed. Second, approaches that directly formulate efficient neural architecture, e.g. using separable convolutions. \paragraph{Tensor methods for deep learning} The properties of tensor methods~\citep{tensor_decomposition_kolda} made them a prime choice for deep neural network. Beside the theoretical study of the properties of deep neural networks~\citep{expressive_deep_tensor}, they have been especially studied in the context of reparametrizing existing layer. One goal of such reparametrization is parameter space savings. \citet{novikov2015tensorizing} for instance proposed to reshape the weight matrix of fully-connected layers into high-order tensors and apply tensor decomposition (specifically Tensor-Train (TT)~\citep{oseledets2011tensor} ) on the resulting tensor. In a followup work~\citep{garipov2016ultimate}, the same strategy is applied to both fully connected and convolutional layers. Fully connected layers and flattening layers can be removed altogether and replaced with tensor regression layers~\citep{kossaifi2018tensor}. These express outputs through a low-rank multi-linear mapping from a high-order activation tensor to an output tensor of arbitrary order. Parameter space saving can also be obtained, while maintaining multi-linear structure, by applying tensor contraction~\citep{kossaifi2017tensor}. Another advantage of tensor reparametrization is computational speed-up. In particular, tensor decomposition is an efficient way to obtain separable filters from convolutional kernels. These separable convolutions were proposed in computer vision by~\cite{rigamonti2013learning} in the context of filter banks. \citet{jaderberg2014speeding} first applied this concept to deep learning and proposed leveraging redundancies across channels using separable convolutions. This is optimized layer by layer via alternating least-squares by minimizing the reconstruction error between the pretrained weights and the corresponding approximation. \citet{lebedev2015speeding} proposed to apply CP decomposition directly to the (\(4\) dimensional) kernels of pretrained \(2\)D convolutional layers, making them separable. The resulting formulation allows to speed up the convolution by rewriting it as a series of smaller convolutions. The incurred loss in performance is compensated by fine-tuning. A similar efficient rewriting of convolutions was proposed by \citet{yong2016compression} using Tucker decomposition instead of CP to decompose the convolutional layers of a pre-trained network. This allows to rewrite the convolution as a \(1 \times 1\) convolutions, followed by regular convolution with a smaller kernel and, finally, another \(1 \times 1\) convolution. Note that in this case, the spatial dimensions of the convolutional kernel are left untouched and only the input and output channels are compressed. Again, the loss in performance is compensated by fine-tuning the whole network. CP decomposition is also used by~\citet{astrid2017cp} to reparametrize the layers of deep convolutional neural networks, but the tensor power method is used instead of an alternating least-squares algorithm. The network is then iteratively fine-tuned to restore performance. Similarly,~\citet{tai2015convolutional} proposes to use tensor decomposition to remove redundancy in convolutional layers and express these as the composition of two convolutional layers with less parameters. Each 2D filter is approximated by a sum of rank--\(1\) matrices. Thanks to this restricted setting, a closed-form solution can be readily obtained with SVD. This is done for each convolutional layer with a kernel of size larger than 1. Here, we propose to unify the above works and propose a generalisation of separable convolutions to higher orders.\vspace{-10pt} \paragraph{Efficient neural networks} While concepts such as separable convolutions have been studied since the early successes of deep learning using tensor decompositions, they only relatively recently been ``rediscovered'' and proposed as standalone, end-to-end trainable efficient neural network architectures. First attempts in the direction of neural network architecture optimization were proposed early one in the ground-breaking VGG network~\citep{simonyan2014very} where the large convolutional kernels used in AlexNet~\citep{krizhevsky2009learning} were replaced with a series of smaller one that have an equivalent receptive field size: i.e a convolution with a $5\times5$ kernel can be replaced by two consecutive convolutions of size $3\times3$. In parallel, the idea of decomposing larger kernels into a series of smaller ones is explored in the multiple iterations of the Inception block~\citep{szegedy2015going,szegedy2016rethinking,szegedy2017inception} where a convolutional layer with a $7\times7$ kernel is approximated with two $7\times1$ and $1\times7$ kernels. \citet{he2016deep} introduced the so-called \emph{bottleneck} module that reduces the number of channels on which the convolutional layer with higher kernel size ($3\times3$) operate on by projection back and forth the features using two convolutional layers with $1\times1$ filters. \citet{xie2017aggregated} expands upon this by replacing the $3\times3$ convolution with a grouped convolutional layer that can further reduce the complexity of the model while increasing the representational power at the same time. Recently,~\citet{mobilenet} introduced the \emph{MobileNet} architecture where they proposed to replace the $3\times3$ convolutions with a depth-wise separable module: a depth-wise $3\times3$ convolution (the number of groups is equal with the number of channels) followed by a $1\times1$ convolutional layer that aggregates the information. This type of structures were shown to offer a good balance between the performance offered and the computational cost they incur. \citet{mobilenet-v2} go one step further and incorporate the idea of using separable convolutions in an \emph{inverted bottleneck} module. The proposed module uses the $1\times1$ layers to expand and then contract the channels (hence inverted bottleneck) while using separable convolutions for the $3\times3$ convolutional layer. \paragraph{In this work} we show that many of the aforementioned architectural improvements, such as \emph{MobileNet} or \emph{ResNet}'s \emph{Bottleneck} blocks, are in fact drown from the same larger family of the tensor decomposition methods and propose a new, efficient higher order convolution based on tensor factorization. Specifically, we make the following contributions: \begin{itemize} \item We review convolutions under the lens of tensor decomposition and establish the link between various tensor decomposition and efficient convolutional blocks~(Section \ref{sec:tensor-convs}). \item We propose a general framework unifying tensor decomposition and efficient architectures, showing how these efficient architectures can be derived from regular convolution to which tensor decomposition has been applied~(Section \ref{ssec:efficient-conv}). \item Based on this framework, we propose a higher-order CP convolutional layer for convolutions of any order, that are both memory and computationally efficient~(Section \ref{sec:ho-cp-conv}). \item We demonstrate the performance of our approach on both 2D and 3D data, and show that it offers better performance while being more computation and memory efficient~(Section \ref{sec:experiments}). \end{itemize} \section{Tensor factorization for efficient convolutions}\label{sec:tensor-convs} Here, we explore the relationship between tensor methods and deep neural networks' convolutional layers. Without loss of generality, we omit the batch size in all the following formulas. \subsection{Mathematical background and notation} We denote \(1\myst\)--order tensors (vectors) as \(\myvector{v}\), \(2\mynd\)--order tensor (matrices) as \(\mymatrix{M}\) and tensors of order \( \geq 3\) as \(\mytensor{T}\). We write the regular convolution of \(\mytensor{X}\) with \(\mymatrix{W}\) as \(\mytensor{X} \myconv_n \mymatrix{W}\). In the case of a \(1\)--D convolution, we write the convolution of a tensor \(\mytensor{X} \in \myR^{I_0, \cdots, I_N}\) with a vector \(\myvector{w} \in \myR^{K}\) along the \(n\myth\)--mode as \(\mytensor{X} \myconv_n \myvector{v}\). Note that in practice, as done in current deep learning frameworks~\citep{pytorch}, we use cross-correlation, which differs from convolution by the flipping of th kernel. This does not impact the results since the weights are learned end-to-end. In other words, \(\left( \mytensor{X} \myconv_n \myvector{v}\right)_{i_0, \cdots, i_N} = \sum_{k = 1}^K \myvector{v}_k \mytensor{X}_{i_0, \cdots, i_{n-1}, i_n + k, i_{n+1}, \cdots, I_N}\). \subsection{\(1 \times 1\) convolutions and tensor contraction} Next, we show that \(1 \times 1\) convolutions are equivalent to a tensor contraction with the kernel of the convolution along the channels dimension. Let's consider a \(1\times1\) convolution \(\Phi\), defined by kernel \(\mytensor{W} \in \myR^{T \times C \times 1 \times 1}\) and applied to an activation tensor \(\mytensor{X} \in \myR^{C \times H \times W}\). We denote the squeezed version of \(\mytensor{W}\) along the first mode as \(\mymatrix{W} \in \myR^{T \times C}\). The tensor contraction of a tensor \(\mytensor{T} \in \myR^{I_0 \times I_1 \times \cdots \times I_N}\) with matrix \(\mymatrix{M} \in \myR^{J \times I_n}\), along the \(n\myth\)--mode (\(n \in \myrange{0}{N}\)), known as \emph{n--mode product}, is defined as \(\mytensor{P} = \mytensor{T} \times_n \mytensor{M}\), with: \begin{equation} \label{eq:n-mode-product} \mytensor{P}_{i_0, \cdots, i_n} = \sum_{k=0}^{I_n} \mytensor{T}_{i_0, \cdots, i_{n-1}, k, i_{k+1}, \cdots, i_N} \mymatrix{M}_{i_n, k} \end{equation} By plugging~(\ref{eq:n-mode-product}) into the expression of \(\Phi(\mytensor{X})\), we can observe that the \(1 \times 1\) convolution is equivalent with an n-mode product between \mytensor{X} and the matrix \mymatrix{W}. This can readily be seen by writing: \begin{equation} \label{eq:n-mode-1x1} \Phi(\mytensor{X})_{t, y, x} = \mytensor{X} \myconv \mytensor{W} = \sum_{k=0}^C \mytensor{W}_{t, k, y, x} \mytensor{X}_{k, y, x} = \mytensor{X} \times_0 \mymatrix{W} \end{equation} \subsection{Separable convolutions}\label{ssec:cp-conv} Here we show how separable convolutions can be obtained by applying CP decomposition to the kernel of a regular convolution~\cite{lebedev2015speeding}. We consider a convolution defined by its kernel weight tensor\(\mytensor{W} \in \myR^{T \times C \times K_H \times K_W}\), applied on an input of size \(\myR^{C \times H \times W}\). Let \(\mytensor{X} \in \myR^{C \times H \times W}\) be an arbitrary activation tensor. If we define the resulting feature map as \(\mytensor{F} = \mytensor{X} \myconv \mytensor{W}\), we have: \begin{equation} \label{eq:convolution} \mytensor{F}_{t, y, x} = \myblue{\sum_{k=1}^C} \myred{\sum_{j=1}^H} \mygreen{\sum_{i=1}^W} \mytensor{W}(t, \myblue{k}, \myred{j}, \mygreen{i}) \mytensor{X}(\myblue{k}, \myred{j + y}, \mygreen{i + x}) \end{equation} Assuming a low-rank Kruskal structure on the kernel \(\mytensor{W}\) (which can be readily obtained by applying CP decomposition), we can write: \begin{equation} \label{eq:kruskal-kernel} \mytensor{W}_{t, s, j, i} = {\color{black}{\sum_{r=0}^{R-1}}} \mymatrix{U}^{(T)}_{t, r} \mymatrix{U}^{(C)}_{s, r} \mymatrix{U}^{(H)}_{j, r} \mymatrix{U}^{(W)}_{i, r} \end{equation} By plugging~\ref{eq:kruskal-kernel} into~\ref{eq:convolution} and re-arranging the terms, we get: \begin{equation} \label{eq:separable-convolution} \mytensor{F}_{t, y, x} = \underbrace{\sum_{r=0}^{R-1} \mymatrix{U}^{(T)}_{t, r} \underbrace{\left[\mygreen{\sum_{i=1}^W} \mymatrix{U}^{(W)}_{\mygreen{i}, r} \underbrace{\left(\myred{\sum_{j=1}^H} \mymatrix{U}^{(H)}_{\myred{j}, r} \underbrace{\left[\myblue{\sum_{k=1}^C} \mymatrix{U}^{(C)}_{\myblue{k}, r}\mytensor{X}(\myblue{k}, \myred{j + y}, \mygreen{i + x}) \right]}_{\myblue{1\times1 \text{ conv}}} \right)}_{\myred{\text{ depthwise conv}}} \right]}_{\mygreen{\text{ depthwise conv}}} }_{1\times 1 \text{ convolution}} \end{equation} This readily gives us a recipe to rewrite the original convolution as a series of convolutions along one of the dimensions, as illustrated in figure~\ref{fig:kruskal-conv}. Given the previous equality of~(\ref{eq:n-mode-1x1}), we can rewrite this compactly as: \begin{equation} \label{eq:separable-convolution-compact} \mytensor{F} = \left( \left[ \left(\mytensor{X} \times_0 \mymatrix{U}^{(C)} \right) \myconv_1 \mymatrix{U}^{(W)}\right] \myconv_2 \mymatrix{U}^{(H)} \right) \times_0 \mymatrix{U}^{(T)} \end{equation} \begin{figure} \centering \includegraphics[width=1\textwidth,trim={0 150 0 150},clip]{cp-conv} \caption{Kruskal convolution expressed as a series of small efficient (1D) convolutions.} \label{fig:kruskal-conv} \end{figure} \subsection{Bottleneck layer}\label{ssec:tucker-conv} As previously, we consider the convolution \(\mytensor{F} = \mytensor{X} \myconv \mytensor{W}\). However, instead of a Kruskal structure, we now assume a low-rank Tucker structure on the kernel \(\mytensor{W}\) (which can be readily obtained by applying Tucker decomposition) and yields an efficient formulation~\cite{yong2016compression}. We can write: \begin{equation} \label{eq:tucker-kernel} \mytensor{W}(t, s, j, i) = \sum_{r_0=0}^{R_0-1} \sum_{r_1=0}^{R_1-1} \sum_{r_2=0}^{R_2-1} \sum_{r_3=0}^{R_3-1} \mytensor{G}_{r_0, r_1, r_2, r_3} \mymatrix{U}^{(T)}_{t, r_0} \mymatrix{U}^{(C)}_{k, r_1} \mymatrix{U}^{(H)}_{j, r_2} \mymatrix{U}^{(W)}_{i, r_3} \end{equation} Plugging back into a convolution, we get: \begin{equation} \mytensor{F}_{t, y, x} = \sum_{k=1}^C \sum_{j=1}^H \sum_{i=1}^W \sum_{r_0=0}^{R_0-1} \sum_{r_1=0}^{R_1-1} \sum_{r_2=0}^{R_2-1} \sum_{r_3=0}^{R_3-1} \mytensor{G}_{r_0, r_1, r_2, r_3} \mymatrix{U}^{(T)}_{t, r_0} \mymatrix{U}^{(C)}_{k, r_1} \mymatrix{U}^{(H)}_{j, r_2} \mymatrix{U}^{(W)}_{i, r_3} \mytensor{X}_{k, j + y, i + x} \end{equation} We can further absorb the factors along the spacial dimensions into the core by writing: \begin{equation} \mytensor{H} = \mytensor{G} \times_2 \mymatrix{U}^{(H)}_{j, r_2} \times_3 \mymatrix{U}^{(W)}_{i, r_3} \end{equation} In that case, the expression above simplifies to: \begin{equation}\label{eq:tucker-conv-basic} \mytensor{F}_{t, y, x} = \sum_{k=1}^C \sum_{j=1}^H \sum_{i=1}^W \sum_{r_0=0}^{R_0-1} \sum_{r_1=0}^{R_1-1} \mytensor{H}_{r_0, r_1, j, i} \mymatrix{U}^{(T)}_{t, r_0} \mymatrix{U}^{(C)}_{k, r_1} \mytensor{X}_{k, j + y, i + x} \end{equation} In other words, this is equivalence to first transforming the number of channels, then applying a (small) convolution before returning from the rank to the target number of channels. This can be seen by rearranging the terms from equation~\ref{eq:tucker-conv-basic}: \begin{equation}\label{eq:tucker-conv} \mytensor{F}_{t, y, x} = \underbrace{ \mygreen{\sum_{r_0=0}^{R_0-1}} \mymatrix{U}^{(T)}_{t, \mygreen{r_0}} \left[ \underbrace{ \myred{ \sum_{j=1}^H \sum_{i=1}^W \sum_{r_1=0}^{R_1-1} } \mytensor{H}_{\mygreen{r_0}, \myred{r_1}, \myred{j}, \myred{i}} \left[ \underbrace{ \myblue{\sum_{k=1}^C} \mymatrix{U}^{(C)}_{\myblue{k}, \myred{r_1}} \mytensor{X}(\myblue{k}, \myred{j + y}, \myred{i + x}) }_{\myblue{1 \times 1 \text{ conv}}} \right] }_{\myred{H \times W \text{ conv}}} \right] }_{\mygreen{1 \times 1 \text{ conv}}} \end{equation} In short, this simplifies to the following expression, also illustrated in figure~\ref{fig:tucker-conv}: \begin{equation} \mytensor{F} = \left( \left(\mytensor{X} \times_0 \mymatrix{U}^{(C)} \right) \myconv \mytensor{G} \right) \times_0 \mymatrix{U}^{(T)} \end{equation} \begin{figure} \centering \includegraphics[width=1\textwidth,trim={0 130 0 150},clip]{tucker-conv} \caption{Tucker convolution expressed as a series of small efficient convolutions. Note that this is the approach taken by ResNet for the Bottleneck blocks.} \label{fig:tucker-conv} \end{figure} \subsection{Efficient convolutional blocks as a tensorized convolution}\label{ssec:efficient-conv} While tensor decomposition have been explored in the context of deep learning for years, and in the mathematical context for decades, they are regularly rediscovered and re-introduced in different forms. Here, we revisit popular deep neural network architectures under the lens of tensor factorization. Specifically, we show how these blocks can be obtained from a regular convolution by applying tensor decomposition to its kernel. In practice, batch-normalisation layers and non-linearities are inserted in between the intermediary convolution to facilitate learning from scratch. \textbf{ResNet Bottleneck block:} \citet{resnet} introduced a block, coined \emph{Bottleneck block} in their seminal work on deep residual networks. It consists in a series of a \(1 \times 1\) convolution, to reduce the number of channels, a smaller regular (\(3 \times 3\)) convolution, and another \(1 \times 1\) convolution to restore the rank to the desired number of output channels. Based on the equivalence derived in section~\ref{ssec:tucker-conv}, it is straightforward to see this as applying Tucker decomposition to the kernel of a regular convolution. \textbf{ResNext and Xception:} ResNext~\citep{xie2017aggregated} builds on this bottleneck architecture, which, as we have shown, is equivalent to applying Tucker decomposition to the convolutional kernel. In order to reduce the rank further, the output is expressed as a sum of such bottlenecks, with a lower-rank. This can be reformulated efficiently using grouped-convolution~\citep{xie2017aggregated}. In parallel, a similar approach was proposed by~\citet{chollet2017xception}, but without \(1 \times 1\) convolution following the grouped depthwise convolution. \textbf{MobileNet v1:} MobileNet v1~\citep{mobilenet} uses building blocks made of a depthwise separable convolutions (spatial part of the convolution) followed by a \(1 \times 1\) convolution to adjust the number of output channels. This can be readily obtained from a CP decomposition (section~\ref{ssec:cp-conv}) as follows: first we write the convolutional weight tensor as detailed in equation~\ref{eq:kruskal-kernel}, with a rank equal to the number of input channels, i.e. \(R = C\). The first depthwise-separable convolution can be obtained by combining the two spatial \(1\)D convolutions \(\mymatrix{U}^{(H)}\) and \(\mymatrix{U}^{(W)}_{i, r}\). This results into a single spatial factor \(\mymatrix{U}^{(S)} \in \myR^{H \times W \times R}\), such that \(\mymatrix{U}^{(S)}_{j, i, r} = \mymatrix{U}^{(H)}_{j, r} \mymatrix{U}^{(W)}_{i, r} \). The \(1 \times 1\) convolution is then given by the matrix-product of the remaining factors, \(\mymatrix{U}^{(F)} = \mymatrix{U}^{(T)} \left(\mymatrix{U}^{(C)}\right)\myT \in \myR^{T \times C}\). This is illustrated in Figure~\ref{fig:mobilenet-conv}. \begin{figure} \centering \includegraphics[width=0.7\textwidth,trim={0 120 0 140},clip]{mobilenet-conv} \caption{MobileNet blocks are a special case of CP convolutions, where the first convolution is ignored, and the spatial factors are combined into one.} \label{fig:mobilenet-conv} \end{figure} \textbf{MobileNet v2:} MobileNet v2~\citep{mobilenet-v2} employs a similar approach by grouping the spatial factors into one spatial factor \(\mymatrix{U}^{(S)} \in \myR^{H \times W \times R}\), as explained previously for the case of MobileNet. However, the other factors are left untouched. The rank of the decomposition, in this case, corresponds, for each layer, to the expansion factor $\times$ the number of input channels. This results in two \(1 \times 1\) convolutions and a \( 3 \times 3\) depthwise separable convolution. Finally, the kernel weight tensor (displayed graphically in figure~\ref{fig:mobilenet-v2-conv}) is expressed as: \begin{equation} \label{eq:mobilenet-v2} \mytensor{W}_{t, s, j, i} = {\color{black}{\sum_{r=0}^{R-1}}} \mymatrix{U}^{(T)}_{t, r} \mymatrix{U}^{(C)}_{s, r} \mymatrix{U}^{(S)}_{j, i, r} \end{equation} In practice, MobileNet-v2 also includes batch-normalisation layers and non-linearities in between the convolutions, as well as a skip connection to facilitate learning. \begin{figure} \centering \includegraphics[width=1\textwidth,trim={0 130 0 150},clip]{mobilenet-v2-conv} \caption{MobileNet-v2 blocks are a special case of CP convolutions, with the spatial factors merged into a depthwise separable convolution.} \label{fig:mobilenet-v2-conv} \end{figure} \section{Efficient N-D convolutions via higher-order factorization}\label{sec:ho-cp-conv} We propose to generalize the framework introduced above to convolutions of any arbitrary order. Specifically, we express, in the general case, separable ND-convolutions as a series of 1D convolutions, and show how this is derived from a CP convolution on the N--dimensional kernel. In particular, here, we consider an \(N\myth\)--order input activation tensor \(\mytensor{X} \in \myR^{C \times D_0 \times \cdots \times D_N}\) with \(C\) channels. We define a general, high order separable convolution \(\Phi\) defined by a kernel \(\mytensor{W} \in \myR^{T \times C \times K_0 \times \cdots \times K_N}\), and expressed as a Kruskal tensor, i.e. \(\mytensor{W} = \mykruskal{\mymatrix{U}^{(T)}, \mymatrix{U}^{(C)}, \mymatrix{U}^{(K_0)}, \cdots, \mymatrix{U}^{(K_N)}}\). We can then write: \begin{equation} \label{eq:ho-conv-1} \Phi(\mytensor{X})_{t, i_0, \cdots, i_N} = \sum_{r = 0}^{R} \sum_{s = 0}^C \sum_{i_0 = 0}^{K_0} \cdots \sum_{i_N = 0}^{K_N} \mymatrix{U}^{(T)}_{t, r} \mymatrix{U}^{(C)}_{s, r} \mymatrix{U}^{(K_0)}_{i_0, r} \cdots \mymatrix{U}^{(K_N)}_{i_N, r} \mytensor{X}_{s, i_0, \cdots, i_N} \end{equation} By rearranging the terms, this expression can be rewritten as: \begin{equation} \label{eq:ho-conv-2} \mytensor{F} = \left( \left(\mytensor{X} \times_0 \mymatrix{U}^{(T)} \right) \myconv_1 \mymatrix{U}^{(K_0)} \myconv_2 \mymatrix{U}^{(K_1)} \myconv \cdots \myconv_{N+1} \mymatrix{U}^{(K_N)} \right) \times_0 \mymatrix{U}^{(C)} \end{equation} Tensor decomposition (and, in particular, decomposed convolutions) are notoriously hard to train end-to-end~\citep{jaderberg2014speeding,lebedev2015speeding,tai2015convolutional}. As a result, most existing approach rely on first training an uncompressed network, then decomposing the convolutional kernels before replacing the convolution with their efficient rewriting and fine-tuning to recover lost performance. However, this approach is not suitable for higher-order convolutions where it might not be practical to train the full ND convolution. Instead, we propose to facilitate training by adding non-linearities \(\Psi\) (e.g. bath normalisation combined with RELU), leading to the following expression: \begin{equation} \label{eq:ho-conv-3} \mytensor{F} = \Psi_{N+2}\left( \Psi_{N+1}\left(\cdots \Psi_1\left(\Psi_0 \left(\mytensor{X} \times_0 \mymatrix{U}^{(T)} \right) \myconv_1 \mymatrix{U}^{(K_0)}\right) \myconv \cdots \myconv_{N+1} \mymatrix{U}^{(K_N)}\right) \times_0 \mymatrix{U}^{(C)}\right) \end{equation} Skip connection can also be added by introducing an additional factor \(\mymatrix{U}^{(S)} \in \myR^{C \times T}\) and using \(\mytensor{F}' = \mytensor{X} + \left(\mytensor{F} \times_0 \mymatrix{U}^{(S)} \right) \). This results in an efficient higher-order CP convolution, detailed in algorithm~\ref{alg:ho-cp-conv}. \begin{algorithm} \caption{Higher-order CP convolutions} \label{alg:ho-cp-conv} \begin{algorithmic} \REQUIRE Input activation tensor $\mytensor{X}\in \myR^{C \times D_0 \times \cdots \times D_N}$\\ CP kernel weight tensor $\mytensor{W} = \mykruskal{\mymatrix{U}^{(T)}, \mymatrix{U}^{(C)}, \mymatrix{U}^{(K_0)}, \cdots, \mymatrix{U}^{(K_N)}}$\\ Skip connection weight matrix $ \mymatrix{U}^{(S)} \in \myR^{O \times C}$ \ENSURE Efficient N-D convolution on \(\mytensor{X}\) \STATE Efficient \(1D\) convolution on the channels: $\mytensor{H} \Leftarrow \mytensor{X} \times_0 \mymatrix{U}^{(C)}$ \FOR{ i:=1 \TO \(N - 2\)} \STATE $\mytensor{H} \Leftarrow \mytensor{H} \myconv_i \mymatrix{U}^{(K_i)}$ (\(1\)--D convolution along the i\myth mode) \STATE $\mytensor{H} \Leftarrow \text{PReLU}\left(\mytensor{H}\right) $ or $\text{ReLU}\left(\mytensor{H}\right)$ [optional] \STATE $\mytensor{H} \Leftarrow \text{Batch-Norm}\left(\mytensor{H}\right)$ [optional] \ENDFOR \STATE Efficient \(1D\) convolution from the rank to the output number of channels: $\mytensor{H} \Leftarrow \mytensor{H} \times_1 \mymatrix{U}^{(T)}$ \IF{ Skip-connection} \RETURN $\mytensor{H} + \mytensor{X} \times_0 \mymatrix{U}^{(S)} $ \ELSE \RETURN $\mytensor{H}$ \ENDIF \end{algorithmic} \end{algorithm} This formulation is significantly more efficient than that of a regular convolution. Let's consider an N-dimensional convolution, with \(C\) input channels and \(T\) output channels, i.e. a weight of size \(\mytensor{W} \in \myR^{C \times T \times I_0 \times \cdots \times I_{N-1}}\). Then a regular 3D convolution has \(C \times T \times \left(\prod_{k=0}^{N-1} I_k\right)\) parameters. By contrast, our HO-CP convolution with rank \(R\) has only \(R\left( C + T + \sum_{k=0}^{N-1} I_k\right)\) parameters. For instance, for a 3D convolution with a cubic kernel (of size \(K \times K \times K\), a regular 3D convolution would have \(CTK^3\) parameters, versus only \(R(C + T + 3K)\) for our proposed HO-CP convolution. This reduction in the number of parameters translates into much more efficient operations in terms of floating point operations (FLOPs). We show, in figure~\ref{fig:FLOP}, a visualisation of the number of Giga FLOPs (GFLOPs, with 1GFLOP = \(1e^{9}\) FLOPs), for both a regular 3D convolution and our proposed approach, for an input of size \(32 \times 32 \times 16\), varying the number of input and output channels, with a kernel size of \(3 \times 3 \times 3\). \begin{figure} \centering \includegraphics[width=0.65\textwidth]{FLOP} \caption{\textbf{Comparison of the number of Giga-FLOP between regular 3D convolutions and our proposed CP-HOConv.} We consider an input of size \(32 \times 32 \times 16\), and vary the size of the input and output channels (the x-axis shows input $\times$ output channels). Our proposed HO-CP convolution, here for a rank equal to 6 and 3 times the input channels (\emph{CP-HOConv-6} and \emph{CP-HOConv-3}), has significantly less FLOP than the regular convolution (\emph{3D-Conv}).} \label{fig:FLOP} \end{figure} \section{Experimental setting}\label{sec:experiments}\vspace{-5pt} In this section, we introduce the experimental setting and the databases used. We then detail the implementation details and results obtained with our method. \subsection{Datasets}\vspace{-5pt} We empirically assess the performance of our model on the popular task of image classification for both the \(2\)D and \(3\)D case, on two popular dataset, namely CIFAR-10 and 20BN-Jester. \textbf{CIFAR-10~\citep{krizhevsky2009learning}} is a dataset for image classification composed of \(10\) classes with \(6,000\) image which, divided into \(5000\) images per class for training and \(1000\) images per class for testing, on which we report the results. \textbf{20BN-Jester Dataset v1} is a dataset\footnote{Dataset available at \url{https://www.twentybn.com/datasets/jester/v1}.} of \(148,092\) videos, each representing one of \(27\) hand gestures (e.g. \emph{swiping left}, \emph{thumb up}, etc). Each video contains a person performing one of gestures in front of a web camera. Out of the $148,092$ videos $118,562$ are used for training, $14,787$ for validation on which we report the results. \subsection{Implementation details} We implemented all models using PyTorch~\citep{pytorch} and TensorLy~\citep{tensorly}. For the CIFAR-10 experiments, we used a MobileNet-v2 as our baseline. For our approach, we simply replaced the full MobileNet-v2 blocks with ours (which, in the 2D case, differs from MobileNet-v2 by the use of two separable convolutions along the spatial dimensions instead of a single 2D kernel). For the 20BN-Jester dataset, we used a convolutional column composed of \(4\) convolutional blocks with kernel size \(3 \times 3 \times 3\), with respective input and output of channels: $(3, 64), (64, 128), (128, 256)$ and $(256, 256)$, followed by two fully-connected layers to reduce the dimensionality to \(512\) first, and finally to the number of classes. Between each convolution we added a batch-normalisation layer, non-linearity (ELU) and \(2\times 2 \times 2\) max-pooling. The full architecture is detailed in the supplementary materials. For our approach, we used the same setting but replaced the 3D convolutions with our proposed block and used, for each layer, \(6 \times n_\text{input-channels}\) for the rank of the HO-CP convolution. The dataset was processed by batches of \(32\) sequences of RGB images, with a temporal resolution of \(18\) frames and a size of \(84 \times 84\). We validated the learning rate in the range \(0.1, 0.00001\) with decay on plateau by a factor of 10. In all cases we report average performance on the over \(3\) runs. \vspace{-5pt} \subsection{Results} \vspace{-10pt} \begin{table} \caption{\textbf{Results on the CIFAR-10 dataset}} \label{tab:cifar} \centering \begin{tabular}{llc} \toprule \textbf{Network} & \textbf{\# parameters} & \textbf{Accuracy (\%)} \\ \midrule MobileNet-v2 & $2,30$ & $94$ \\ HOSConv (\textbf{Ours}) & $2,29$ & $94$ \\ \bottomrule \end{tabular} \end{table} Here, we present the performance of our approach for the 2D and 3D case. While our method is general and applicable to data of any order, these are the most popular cases and the ones for which the existing work, both in terms of software support and algorithm development, is done. We therefore focus our experiments on these two cases. \textbf{Results for 2D convolutional networks} We compared our method with a MobileNet-v2 with a comparable number of parameters, Table~\ref{tab:cifar}. Unsurprisingly, both approach yield similar results since, in the 2D case, the two networks architectures are similar. It is worth noting that our method has marginally less parameters than MobileNet-v2, for the same number of channels, even though that network is already optimized for efficiency. \vspace{-10pt} \begin{table}[htb] \caption{\textbf{Results on the 20BN-Jester Dataset}} \label{tab:jester} \centering \begin{tabular}{llll} \toprule & & \multicolumn{2}{c}{\textbf{Accuracy (\%)}} \\ \cmidrule(r){3-4} \multirow{-2}{*}{\textbf{Network}} & \multirow{-2}{*}{\textbf{\#conv parameters}} & \textbf{Top-1} & \textbf{Top-5} \\ \midrule 3D-ConvNet & $2.9$M & $83.2$ & $97.0$ \\ HO-CP ConvNet (\textbf{Ours}) & $1.2$M & $83.8$ & $97.4$ \\ HO-CP ConvNet-S (\textbf{Ours}) & $1.2$M & $\mathbf{85.4}$ & $\mathbf{98.6}$ \\ \bottomrule \end{tabular} \end{table} \textbf{Results for 3D convolutional networks} For the 3D case, we test our Higher-Order CP convolution with regular 3D convolution in a simple neural network architecture, in the same setting, in order to be able to compare them. Our approach is more computationally efficient and gets better performance, Table~\ref{tab:jester}. In particular, the basic version without skip connection and with RELU (emph{HO-CP ConvNet}) has \(1.7\) million less parameters in the convolutional layers compared to the regular 3D network, and yet, converges to better Top-1 and Top-5 accuracy. The version with skip-connection and PReLU (\emph{HO-CP ConvNet-S}) beats all approaches. \section{Conclusions}\vspace{-10pt} In this paper, we established the link between tensor factorization and efficient convolutions, in a unified framework. We showed how efficient architectures can be directly derived from this framework. Building up on these findings, we proposed a new efficient convolution, defined for any arbitrary number of dimensions. We theoretically derive an efficient algorithm for computing this \(N\)D convolutions for any \(N \in \myN\) by leveraging higher-order tensor factorization. Specifically, we express the convolution as a superposition of rank-1 tensors, allowing us to reformulate it efficiently. We empirically demonstrate that our approach is efficient on both 2D and 3D tasks using existing frameworks, in terms of performance (accuracy), memory requirements and computational burden. {\small
{'timestamp': '2019-06-17T02:14:01', 'yymm': '1906', 'arxiv_id': '1906.06196', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06196'}
arxiv
\section{Introduction} \label{introduction} Machine learning models have gathered a large amount of success in recent years, with applications in several industries. These models are increasingly being used in safety critical scenarios with data that is both public or private, such as health data or customer photos. As we increasingly rely on machine learning, it is critical to assess the dangers of the vulnerabilities in these models. In a supervised learning environment several components make up the learning pipeline of a machine learning model: collection of training data, definition of model architecture, model training, and model outputs -- test and evaluation. This pipeline presents a broader attack surface, where adversaries can leverage system vulnerabilities to compromise data privacy and/or model performance. There are four main types of attacks discussed in literature: \begin{itemize} \item model fooling -- small perturbation to the user input leads to large changes in the model output \cite{goodfellowexplaining}, \cite{carlini2017adversarial} \item model extraction -- the model is reverse engineered from its outputs \cite{tramer2016stealing}. \item model poisoning-- the training process is altered to create vulnerabilities at inference \cite{hitaj2017deep}, \cite{yang2017generative}. \item model inversion-- the model is used to re-generate or gain information on the training data \cite{yang2017generative}, \cite{shokri2017membership} \end{itemize} However these attacks are assumed to be performed in vacuum, with little discussion on the interplay between defense strategies for different types of attacks. In this paper we focus on model fooling and model inversion, with emphasis on how mitigating one attack can increase vulnerabilities in the other. \begin{figure}[ht] \vskip 0.2in \begin{center} \centerline{\includegraphics[width=\columnwidth]{ICML_ATT.pdf}} \caption{Model inversion results on ATT data. } \label{ATT} \end{center} \vskip -0.2in \end{figure} Model inversion attacks directly attack the privacy of the training dataset. There are several scenarios where the data needs to be kept private either for financial reasons or because we want to protect the training members privacy. For example if we train our model on text data that includes social security numbers, we do not want anyone to be able to access such information from the training data if we make the model public. Previous work on model inversion has explored small datasets and small models. \cite{fredrikson2015model} performed model inversion of facial images on a logisitic regression model trained with the ATT dataset \cite{att_faces}. Although the methods were successful on the small dataset (400 gray-scale images) they do not directly extend to larger datasets as demonstrated by \cite{shokri2017membership}. Even with the small dataset and model, this approach only works on classes that do not vary in pose or position within the dataset, as demonstrated in Figure \ref{ATT}. Here the top images demonstrate a successful reconstruction and the bottom images show results, using the same methodology, on another category that is not well reconstructed. \cite{shokri2017membership} demonstrated the difficulty of model inversion by applying the Frederickson attack to a convolutional neural network trained on the CIFAR-10 dataset. The reconstructed images demonstrated no recognizable semantic meaning demonstrating the ineffectiveness of the attack. Model fooling attacks have gathered much more attention and success. With several variations of a gradient based attack, the model’s output can be drastically changed with a small change in the input to the model. Several different defenses have been proposed to alleviate this problem, including model distillation, image blurring and denoising \cite{papernot2016distillation}, \cite{liao2018defense}, \cite{carlini2017adversarial}. Recently, a promising defense has been obtained with the idea of adversarially trained models (ATM) \cite{madry2017towards}, \cite{tsipras2018robustness}. This involves formulating the traditional training process as a min-max problem. First an adversarial example is maximized to fool the model, while staying within a L2 distance from the training image. Then the model is trained to minimize the loss to these adversarial examples. \cite{madry2017towards} demonstrated that adversarial training also comes with other consequences, namely a trade-off with accuracy as well as better alignment of semantic representation between a model and human perception. In this paper we explore how this improved semantic representation of ATM affects the privacy of training data specific to model inversion attacks. We demonstrate that by improving the semantic representation that models have, we are able to generate better model inversion reconstructions. \section{Approach} \label{Approach} This work focuses on three image classification models, referred here as the target models. The target models are trained to classify images of the CIFAR-10 dataset \cite{krizhevsky2009learning}, \cite{krizhevsky2010convolutional}. One model is robustly trained and the other two models are trained in a traditional manner. The target models are then attacked with three different model inversion attacks. In this scenario the goal of the model inversion attack is to reconstruct an image from the training dataset. \subsection{Target Models} The first model that we test is a traditionally trained model(TTM) using the VGG16 architecture (TTM-VGG16) changing the fully connected layers to handle the CIFAR image size \cite{simonyan2014very}. The model was trained for 100 epochs with a batch size of 128, using an Adam optimizer with a learning rate of 0.001. This resulted in a model with 82.2\% validation accuracy and 99.2\% training accuracy. The second model that was used is based on the w28-10 wide-resnet architecture and again was traditionally trained (TTM-Res) \cite{zagoruyko2016wide}. The model optimizer was stochastic gradient descent with momentum of 0.9 and weight decay of 0.0002. The learning rate was 0.01 for 100 epochs. The final accuracies were 84.9\% and 95.7\% for the validation and training respectively. The final model, an adversarially trained model (ATM), is based on the w28-10 wide-resnet architecture (ATM-Res) following the work of \cite{madry2017towards}. This model was trained with adversarial examples generated with the Fast gradient sign method (FGSM) \cite{goodfellowexplaining}. The attack was allowed to perturb the image up to 10 pixel counts with the image range being from 0-255. The step size of the attack was 2 and the attack had 10 iterations to find an adversarial example. The model optimizer was stochastic gradient descent with momentum of 0.9 and weight decay of 0.0002. The learning rate was 0.1 for the first 100 epochs and 0.01 for the next 50 and 0.001 for the following 50 epochs, for a total of 200 epochs. The final accuracies were 78.5\% and 99.7\% for the validation and training respectively. \subsection{Model Inversion Attacks} The first attack that we explore is a basic gradient based attack. Here we start by inputting a blank gray image (128 for 0-255 range) and backpropagate to optimize the image such that it maximizes a particular output category that we are interested in extracting. We start with a blank image instead of random inputs as the optimization does not remove all of the randomness that it is initialized with and a crisper reconstruction is generated with a homogenous image input. The image does not necessarily have to start as gray and other homogeneous initialization could be used but gray gives best results for the most classes. Instead of changing the weights of our model, as in regular training, we change the input pixels of the image to maximize a category that we want to extract. This method is very similar to the projected gradient descent (PGD) that is used for model fooling, mainly changing the input from a natural image to a blank input. The gradient step is calculated as follows, \begin{equation} \label{PGD_step} X_{t+1} = clip(X_t + lr * G) \end{equation} with $X_{t}$ being the image at iteration t, clipping is applied to keep the image within the 0-255 range. G is the loss gradient with respect to the image, where the loss is the output of the model for a particular class before softmax. The next model inversion attack is based on the principle of Google’s DeepDream method of optimizing at different image resolution scales \cite{mordvintsev2015deepdream}. The way the original DeepDream algorithm works is by taking a natural image as an input and scaling it down a preset number of octaves with each octave scaling down the image by a preset octave scale. This scaled down image is then scaled back up to the original image dimensions effectively blurring the image and focusing on low frequency features. Once this low resolution image has been optimized it is upscaled and reoptimized at a higher resolution until all octaves are optimized. We use this technique for model inversion by inputting a blank image and running through the entire DeepDream method for 5 iterations. We use a downsampling octave scale of 2 and run a total of 4 octaves for each downsampled image we run 10 iterations of gradient descent optimization. We also added normalization loss as in \cite{mahendran2016visualizing}. The gradient step is modified from the PGD attack as, \begin{equation} \label{Dream_step} X_{t+1} = clip\left(X_t + lr * \frac{G}{|G|_{mean}}\right) \end{equation} where $\frac{G}{|G|_{mean}}$ is the average of the absolute value of the gradients at that iteration step. \begin{figure}[ht] \vskip 0.2in \begin{center} \centerline{\includegraphics[width=\columnwidth]{ICML_GAN_figure.pdf}} \caption{Diagram of the generative adversarial network used for model inversion. a vector of one-hot class labels and random normal numbers is input to the generator. The generator creates an image I' which is then fed to the discriminator with real images. The discriminator is trained to classify real images and to discriminate real images from generated images. The generated images are also fed to the target model and the generator is trained to generate real images and fool the target model. } \label{GAN_figure} \end{center} \vskip -0.2in \end{figure} \begin{figure*}[t!] \vskip 0.2in \begin{center} \centerline{\includegraphics[width=\textwidth]{ICML_figures_CIFAR10_PGD.pdf}} \caption{Reconstructed images of the 10 CIFAR-10 classes generated from gradient ascent model inversion attack. Top middle and bottom row are attacking the TTM-VGG, TTM-Res and ATM-Res respectively.} \label{CIFAR10_PGD_figure} \end{center} \vskip -0.2in \end{figure*} Figure \ref{GAN_figure} illustrates the architecture of the generative adversarial network (GAN) used for model inversion. The main goal of using a GAN for model inversion is to better constrain reconstructed images to be realistic images. We followed the auxiliary classifier (AC) GAN method, modifying it to use the classification loss from the target model \cite{odena2017conditional}. The method starts by inputting a vector of one-hot class labels followed by random numbers. This input vector is fed into the generator, which is composed of 7 transpose convolutions each followed by a ReLU. The generator outputs an image that is fed to the discriminator. The discriminator is made of 7 blocks of convolutional, batchnorm, leaky ReLUs, and dropout layers. The convolutional layers are 5 by 5 filters, the leaky ReLU has a negative slope of 0.2, and the dropout rate was 0.5. The discriminator is trained on a real-fake loss and a class loss, the class loss is only calculated for real images since the target model will classify the generated images. The real images that are used to train the discriminator are the validation images for the CIFAR-10 dataset representing what could be used in a real world attack to constrain the generated images to realistic images, this out of set images for model inversion is called shadow data in literature \cite{salem2018ml}. The generated images are also fed into the target model to calculate the class loss for the generator. The generator is trained on the discriminators real-fake loss as well as the target models class loss. The optimizer for both the discriminator and generator are Adam optimizers with a learning rate of 0.0002 and betas of 0.5 and 0.999. \section{Results} \label{Results} In this section we demonstrate the differences between attacking a TTM and an ATM. The main goal of this comparison is to understand how adversarial attacks and privacy attacks are related. We focus on answering three fundamental questions: \begin{enumerate} \item Is there a difference in the vulnerability to privacy attacks by defending against adversarial attacks? \item What fundamentally is causing this relationship? \item Are privacy concerns enough to keep models from being robustly trained? \end{enumerate} \subsection{PGD model inversion} Just like\cite{shokri2017membership} we observe that PGD attacks for model inversion do not reconstruct semantically meaningful images for TTM. At best the images generated can aide in identifying the label of a particular class, but does not provide any information on a particular data point. Images generated from TTM-VGG have very sharp edges and lines throughout with some slight semantic meaning. TTM-Res has slightly more semantic meaning but is plagued by fractal patterns of the category being generated (This is highlighted in \ref{DeepDream_subsection}). These images also have extensive checker patterns throughout the images. As shown in Figure \ref{CIFAR10_PGD_figure}, once a model is adversarially trained, the reconstructions become more semantically meaningful. The images are clearer and focused on individual samples of the category. \begin{figure}[ht] \vskip 0.2in \begin{center} \centerline{\includegraphics[width=\columnwidth]{PGD_iterations.png}} \caption{ The activation loss during the gradient descent process for 10000 iterations for generating a bird. The dashed and solid line represent the adversarially trained and traditionally trained model respectively. The y-axis on the left is for the normally trained model while the y-axis on the right is for the adversarially trained model. Note the order of magnitude difference in the two axis.} \label{PGD_iterations} \end{center} \vskip -0.2in \end{figure} The optimization process of the reconstructions also significantly changes. As seen in Figure \ref{PGD_iterations} the TTM-Res quickly optimizes the image, creating an image that is classified as a bird within 3 iterations, while the ATM-Res takes 1136 iterations to be classified as the target class of bird. This highlights the prevalence of adversarial examples in the input space of the TTM. Even if we randomly initialize the images with different inputs, the TTM takes two orders of magnitude fewer iterations to generate an image that is classified as the class that we are targeting. Because the model embedding of the TTM does not have a strong semantic representation, a wide range of adversarial examples satisfy the target category boundary conditions-- for almost any image initialization there is an adversarial example that is near that input. \begin{figure}[ht] \vskip 0.2in \begin{center} \centerline{\includegraphics[width=\columnwidth]{ICML_figures_cat_optimize.pdf}} \caption{Reconstructed images from the input cat for traditionally and adversarially trained models.} \label{ICML_cat} \end{center} \vskip -0.2in \end{figure} \label{DeepDream_subsection} \begin{figure*}[t!] \vskip 0.2in \begin{center} \centerline{\includegraphics[width=\textwidth]{ICML_figures_CIFAR10_DREAM.pdf}} \caption{Reconstructed images of the 10 CIFAR-10 classes generated from deep dream model inversion attack. Top middle and bottom row are attacking the TTM-VGG, TTM-Res and ATM-Res respectively.} \label{DeepDream_CIFAR} \end{center} \vskip -0.2in \end{figure*} The activation values of TTM-Res, and ATM-Res differ by almost an order of magnitude, with the bird activations being 150 and 44 for the TTM-Res and ATM-Res respectively. The average activation value on the training data is 11 and 7 for the traditionally trained model and adversarially trained model respectively. When we input the reconstructed image from the ATM-Res into the TTM-Res we get a bird activation value of 21 still significantly smaller than 150, but much higher than the average training image. This demonstrates that all of the reconstructions have higher activations than naturally occurring images. The adversarially trained reconstruction is not a minimum in the TTM-Res because of the nearby adversarial examples and once those examples are removed it becomes a minimum. Inputting a real training image into the model inversion we can further distinguish the characteristics of the two models. In Figure \ref{ICML_cat} we can see that inputting a cat image from the training data to TTM-Res, the model inversion attack begins to generate multiple extra cats and drastically changes the image. The overall image information is lost and none of the shapes are preserved. While for ATM-Res, the reconstructed image focuses more on emphasizing traits that defined a cat in the entire dataset and focuses on contrasting the cat from the background. The robustly trained model reconstruction also begins to remove information about the background, for example blurring the foot and pants. \subsection{DeepDream model inversion} DeepDream model inversion is able to push the image reconstruction away from adversarial examples through its use of multiple scales. This acts as a filter focusing the reconstruction first on low frequency features and then adding higher frequency characteristics as the reconstruction is scaled up. This greatly improves the reconstruction in TTM as demonstrated in Figure \ref{DeepDream_CIFAR}. But since ATM have a decreased prevalence of adversarial examples this method does not improve the model inversion on these models. This method is more successful with TTM-VGG than TTM-Res. TTM-Res tend to generate reconstructions that attempt to have multiples of the class in question. As seen Figure \ref{DeepDream_CIFAR} the TTM-Res generated images have several wheels, antlers, cats, dogs, for the classes of trucks, deer, cats and dogs respectively. This is one of the defining traits in the DeepDream method, but is not observed in the TTM-VGG, suggesting that the skip connections in the resnet architecture allow the model to consider more examples of a class as more likely being that class. This characteristic make model inversion more difficult as small scale features can be extracted but larger scale features are more difficult to obtain. By adversarially training the resnet model, this characteristic of having multiple examples of the class in one image is also removed. The ATM-Res extracted images are highly focused on one single, specific, individual and create distinct contrast between the main subject/category and the image background. The background of the extracted images highlights what remains private in the model, with backgrounds of dogs mainly being contrasting colors, while the background for planes, deer, horses, boats, trucks have blue skies, grass, open field, water, and roads reflecting backgrounds consistent within all of these classes while dogs have more varied backgrounds in the dataset. \subsection{GAN model inversion} By using a GAN we are further constraining the image generation process to generate real images. The goal is to push the generated images away from adversarial images or non-semantically meaningful images, toward realistic looking images. For the TTM the training process quickly finds a way to fool the target network, in essence adding a small amount of noise and focusing on fooling the discriminator. This limits the ability to extract information from the target model as the generated images are more representative of the shadow dataset than the target dataset. \begin{figure*}[t!] \vskip 0.2in \begin{center} \centerline{\includegraphics[width=0.9 \textwidth]{ICML_figures_CIFAR10_GAN.png}} \caption{Reconstructed images of the 10 CIFAR-10 classes generated from a GAN model inversion attack with different weights on the target class.} \label{GAN_CIFAR} \end{center} \vskip -0.2in \end{figure*} \section{Discussion} \label{Discussion} \subsection{Generating different samples} Although the number of training images that are vulnerable to model inversion are limited, it is possible to obtain different reconstructions using different inputs. For PGD model inversion, we can input homogeneous images but that limits our reconstruction to a handful of images. We can also input random values but this hurts the overall structure of the image. As seen in Figure \ref{Bird_figure_PGD} the reconstructions do generate various birds but start loosing the detailed information. Furthermore to create more varied birds one would require larger variance in the noise, which further amplifies the loss in semantic representation of the images. Blurring and incorporating an L2 loss to the optimization can aid with these problems but does not improve significantly. \begin{figure}[ht] \vskip 0.2in \begin{center} \centerline{\includegraphics[width=\columnwidth]{ICML_BIRD_various_PGD.pdf}} \caption{Nine different example birds reconstructed with PGD model inversion using random inputs.} \label{Bird_figure_PGD} \end{center} \vskip -0.2in \end{figure} Figure \ref{Bird_figure} illustrates nine different birds obtained from the DeepDream model inversion. The DeepDream model inversion is more suitable for inputting different random inputs as it naturally blurs and smooths out the random input into the reconstructed image. In Figure \ref{Bird_figure} we can see that the color of the birds changes but also some of the shapes, namely an apparent ostrich and hummingbird in the middle and bottom left image respectively. \begin{figure}[ht] \vskip 0.2in \begin{center} \centerline{\includegraphics[width=\columnwidth]{ICML_BIRD_various.pdf}} \caption{Nine different example birds reconstructed with DeepDream model inversion using random inputs.} \label{Bird_figure} \end{center} \vskip -0.2in \end{figure} \subsection{Model inversion metrics} \begin{figure*}[t!] \vskip 0.2in \begin{center} \centerline{\includegraphics[width=\textwidth]{ICML_BIRD_nearest_train.pdf}} \caption{Nearest cosine similar training images to model inversion image on the left. First row is for TTM-VGG bird, second row is TTM-Res bird, third row is ATM-Res bird and fourth row is ATM-Res horse.} \label{training_birds} \end{center} \vskip -0.2in \end{figure*} The success of the model inversion attack is one of the main challenges when developing different attack methods. When evaluating the attack there are two main challenges, finding the nearest image in the dataset and quantifying the similarity between the reconstructed image and the image in the dataset. For this reason previous model inversion attacks were analyzed qualitatively. We take a two prong approach to provide a quantitative metric to judge model inversion attack efficacy-- identifying the nearest data point to the reconstructed image and quantifying the similarity separately. First we identify the most similar data point by inputting the images into the target model, and extract a feature vector from the final convolutional layer. This feature vector is then used to find the cosine similarity of the nearest image to our reconstructed image. Figure \ref{training_birds} shows training images that were found to be the closest to our model inversion attack reconstruction (here for bird category). Note training images closest to our TTM model reconstructions have large variability in pose, type of bird, and background, whereas those found for the ATM reconstruction pertain to the same type of bird. Here we can see the blue neck and black body of the birds similar to our reconstruction. To show this is not category dependent, we also show results for horse for the ATM. ATM-Res and TTM-Res have an average maximum similarity score of 0.85 and 0.78 respectively while TTM-VGG has an average similarity score of 0.99. This suggest that TTM-VGG cannot differentiate intra-class variability. Once we obtain the image that the model believes is most similar we can then calculate the L2 image distance to quantify the similarity of our reconstructed image to the nearest training image. The average L2 is 82.4, 132.5, 97.1 for ATM-Res, TTM-VGG, and TTM-Res respectively. Figure \ref{adversarial_privacy} demonstrates the trade-off between the privacy loss we describe and an adversarial radius. The adversarial radius is calculated by applying the PGD adversarial attack until the image is misclassified. The four points on Figure \ref{adversarial_privacy} are from the TTM-VGG, TTM-Res, ATM-Res10, ATM-Res, where ATM-Res10 is ATM-Res after 10 epochs. Here we can see how the increase in adversarial radius by making the model more robust decreases the privacy loss. \begin{figure}[ht] \vskip 0.2in \begin{center} \centerline{\includegraphics[width=\columnwidth]{adversarial_privacy.png}} \caption{Adversarial radius vs privacy loss, for TTM-VGG, TTM-Res, ATM-Res10, and ATM-Res from left to right.} \label{adversarial_privacy} \end{center} \vskip -0.2in \end{figure} \subsection{Background privacy} The difference between TTM and ATM is drastic when it comes to privacy vulnerabilities. Image data can hide within the adversarial examples but are easier to obtain in ATM. Even with ATM features that are not necessary to identify a particular class remain occluded. Advertisement on trucks and logos on planes can be seen but the specifics cannot be identified and are only seen as blured lines in the reconstructed images. \section{Conclusion} \label{Conclusion} In this paper we presented the trade-offs between defending against an adversarial attack and a privacy attack by applying three model inversion attacks to three different models. We demonstrated that training a model adversarially (a common adversarial defense) leaves it vulnerable to privacy attacks, namely model inversion attacks that can reconstruct training images directly from the target model. Throughout our three different model inversion attacks, we found it difficult to attack the privacy of TTM while they were trivial to attack adversarially. On the other hand, we were able to better attack ATM but required a greater L2 distance to attack adversarially. By looking at the activations of the two models we observed that TTM have adversarial examples with the highest activations of any of the models. The reconstructed images from ATM were found to have a high value in both the TTM and ATM activations. This suggest that these images are minimums for both models if not for the adversarial examples. When these semantically meaningless adversarial examples are removed, as done in the case of an ATM, the highest activations decrease and are left with semantically meaningful minimums. We further analyze this by looking at how these attacks work when seeded with a training image. An ideal model inversion attack would output the same input training image without modification. We observe that the TTM changes the image into an adversarial example while the ATM highlights the key features of the class while blurring out non-key features. We also observed that when features are not consistent throughout a class' data samples the information is maintained private in the model, such as backgrounds of some classes, but when they are important such as a boat being in the ocean or cars on the road this information is maintained. This is the crucial step in obtaining privacy defenses for ATM. The three attacks that we use highlight how traditional model inversion attacks on TTM can be improved with more sophisticated methods but do not provide as much information as a gradient attack on an ATM. The prevalence of adversarial examples in TTM is such that there is almost always an adversarial minimum near any point making model inversion difficult. PGD was only successful with ATM and could only generate a limited amount of images for ATM. Just like for adversarial cases it works well as a standard attack for privacy attacks. DeepDream attacks extend PGD attacks to generate more various images, while maintaining larger structures. DeepDream model inversion attacks improved the results on TTM but still are not capable of providing fine scale reconstructions. When applied on ATM the reconstructions do not improve significantly but are stable enough to receive random noise as input allowing for different images to be generated. We also presented a method for quantifying the success of the model inversion metric, by using the output of the last convolutional layers as a feature vector. We then used this feature vector to find the nearest cosine similarity between our model inverted image and the images in the training dataset. The success of the model inversion attack was then calculated as the L2 between the nearest cosine similar image and the model inverted image. With ATM increasing the vulnerabilities of privacy attacks, model inversion attacks must be reconsidered when working on private data. Models should at the very least be qualitatively analyzed for data leaks. For the most part, backgrounds are kept private but color and shape of some of the training data is not safe from privacy attacks. More work needs to be done to address the quantification of the success of these privacy attacks, to be able to separate whether an attack extracts a specific training sample or trends in the dataset. Additionally, a better evaluation metric will allow for more advanced attacks and defenses to be developed.
{'timestamp': '2019-06-18T02:03:54', 'yymm': '1906', 'arxiv_id': '1906.06449', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06449'}
arxiv
\section{Introduction} \label{sec:introduction} The way a piece of music is performed expressively constitutes a very important aspect of our enjoyment of the music. In Western art music, performers convey expression in their performances through variations in expressive dimensions such as tempo, dynamics and articulation, among others. While most computational models of expressive performance allow for modeling only a single performance strategy, musicians can interpret a piece of music with a wide variety of stylistic and expressive inflections~\cite{Kirke:2013th,CancinoChacon:2018po}. Some computational models allow users to control global characteristics of the performance (like tempo and dynamics) in real time~\cite{dixon2005air,Chew:2006:ERC:1178723.1178744,baba2010virtualphilharmony}. In this work we present a prototype of a system that allows users to generate individualized piano performances by weighting the contribution of individual aspects of the musical score to the overall performance. The rest of this paper is structured as follows: Section \ref{sec:basis_function_models} provides a brief overview of the basis function models. Section \ref{sec:user_controlled} describes the proposed extension to the basis function models to allow the user to weight the contribution of individual aspects of the score to shape expressive performances. Finally, the paper is concluded in Section \ref{sec:conclusions}. \section{Basis Function Models} \label{sec:basis_function_models} The basis function models are a data-driven framework for modeling musical expressive performance of notated music~\cite{Grachten:2012hk,CancinoChacon:2016wi}. In this framework, numerical representations of expressive dimensions such as tempo and dynamics (which we refer to as \emph{expressive parameters}) are modeled as function of \emph{score basis functions}: numerical encodings of structural aspects of a musical score. These aspects include low-level notated features such as pitch and metrical information, as well as music theoretic features and cognitively motivated features. More formally, an expressive parameter can be written as $y_i = f(\boldsymbol{\varphi}_i)$, where $\boldsymbol{\varphi}_i$ is a vector of basis functions evaluated on score element $x_i$ (e.g., a note or a position in the score, which we refer to as \emph{score onset}) and $f(\cdot)$ is (non-linear) function (the output of a neural network, as described below). For a thorough description of the basis function models, see \cite{Cancino2018:th}. \subsection{Representing Performance Information} In order to capture the sequential nature of music, we divide the performance information into onset-wise and note-wise parameters. Onset-wise parameters capture aspects of the performance with respect to the corresponding temporal (score) position, while note-wise features capture aspects of the performance of each note: \subsubsection{Onset-wise parameters} \begin{enumerate} \item \textbf{MIDI velocity trend} (vt). Maximal MIDI velocity at each score onset \item \textbf{Log Beat Period Ratio} (lbpr). Logarithm of the beat period, i.e., the time interval between consecutive beat grids, divided by the average beat period of the piece. \end{enumerate} \subsubsection{Note-wise parameters} \begin{enumerate} \item \textbf{MIDI velocity deviations} (vd). The deviation of the MIDI velocity for each note from the trend. \item \textbf{Timing} (tim). Onset deviations of the individual notes from the grid established by the local beat period. \item \textbf{Articulation} (art). Logarithm of the ratio of the actual duration of a performed note to its reference (notated) duration according to the local beat period. \end{enumerate} These parameters are then standardized per piece to be zero-mean and unit variance. \subsection{Modeling Expressive Performance} We use bi-directional LSTMs to model onset-wise as well as note-wise parameters, given their sequential nature. The input of the networks for predicting onset-wise parameters are the basis functions evaluated for each score onset, while the input of the networks for note-wise parameters are the basis functions evaluated for every note. The models are trained in a supervised fashion to minimize the reconstruction error on the Magaloff/Chopin \cite{Flossmann:2011ty} and Zeilinger/Beethoven \cite{CancinoChacon:2017ht} datasets. These datasets consists of recordings of piano music performed on computer controlled B\"osendorfer grand pianos, which have been aligned to their scores. \section{User-controlled Basis Function Models}\label{sec:user_controlled} In order to allow the users to explore and adjust the contribution of individual score features, we need first to compute the contribution of a feature to the output of the model. A way to do so is to define a locally-linear approximation of the output of the neural networks modeling each expressive parameter as follows \begin{equation} \tilde{y}_i = c + \left({\dpar{}{\boldsymbol{\varphi}}f(\boldsymbol{\varphi}_{*})}\right)\tp (\boldsymbol{\varphi}_i - \boldsymbol{\varphi}_{*}), \end{equation} where $\tilde{y}$ is the approximated value of the expressive parameter for score element $x_i$, $c$ is a user defined constant value (e.g.~the average lbpr or MIDI velocity of the piece), $\boldsymbol{\varphi}_i$ is the vector of basis functions evaluated for score element $x_i$ and ${\dpar{}{\boldsymbol{\varphi}}f(\boldsymbol{\varphi}_{*})}$ is the gradient of $f$ with respect to $\boldsymbol{\varphi}$ evaluated in $\boldsymbol{\varphi}_*$. We can naturally extend this locally-linear approximation to onset-wise models, by constructing a \emph{temporal} Jacobian matrix, in which its $ij$-th element can be interpreted as the ``contribution'' of the $j$-th basis function (e.g., the pitch, the inter-onset-interval, etc) to the performance of the $i$-th score onset. \subsection{Interactive Interface} The interface allows users to explore the contribution of individual score descriptors (e.g., the velocity on downbeats, the timing surrounding a beat phase) by adjusting the scaling of each column of the temporal Jacobian matrix. Curves indicating velocity and beat period will be updated to visualize the changes. The onset-wise and note-wise parameters will be calculated with the locally-linear approximation, and a new performance will be rendered and displayed for listening. The users will also be able to indicate their preference on overall tempo and articulation of the piece by adjusting the mean and standard deviation. In this way, they can shape the way a performance is rendered, while exploring the contribution of different musical dimensions (Figure \ref{fig:scanner}). \begin{figure} \centering \includegraphics[width=\linewidth]{interface.png} \caption{The user interface where the waveform of the predicted performance is displayed. Sliders are provided for the user to shape the performance. Curves indicating expressive parameters are updated as the user change the sliders. } \label{fig:scanner} \end{figure} \section{Conclusions}\label{sec:conclusions} In this paper we have presented a prototype of an interface that allows users to explore the contribution of individual score descriptors to the expressiveness of the performance. Such an interface could have potential pedagogical applications: users can interactively explore the complex patterns through which score features contribute to the overall expressiveness, while at the same time allowing for creating personalized interpretation, as the performer gives more importance to certain parameters. \section*{Acknowledgements} This research has received funding from the European Research Council (ERC) under the European Union's Horizon 2020 research and innovation programme under grant agreement No. 670035 (project ``Con Espressione").
{'timestamp': '2019-06-18T02:03:08', 'yymm': '1906', 'arxiv_id': '1906.06428', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06428'}
arxiv
\section{Introduction} Tensor networks have seen numerous applications in the physical sciences~\cite{Fannes, White, Vidal, Perez-Garcia, MERA, MERA2, MERAalgorithms, Shi, Tagliacozzo, Murg, PEPS1, PEPS2, PEPS3, rev1, rev2, rev3, rev4, rev5, MERA, MERA2, MERAalgorithms, QC1, QC2, QC3, QC4,cMPS,cMERA, CTMRG, TRG, TEFRG, TNR, Swingle, dS1, dS2, dS3, MERAgeometry}, but there has been significant progress recently in applying the same methods to problems in machine learning~\cite{ML1, ML3, ML9, ML2, ML4, ML5, ML6, ML7, ML8, ML10, ML11}. The TensorNetwork library~\cite{library} was created to facilitate this research and accelerate the adoption of tensor network methods by the ML community. In a previous paper~\cite{paper1} we showed how TensorNetwork could be used in a physics setting. Here we are going to illustrate how to use a matrix product state (MPS) tensor network to classify MNIST and Fashion-MNIST images. The basic technique was applied to the MNIST dataset by Stoudenmire and Schwab~\cite{ML1}, who adapted the DMRG algorithm from physics~\cite{White} to train the network. Our implementation differs from theirs and follows more closely the implementation in the specialized TorchMPS library~\cite{torchmps}. The most significant change from Stoudenmire and Schwab is that we use automatic gradients to train the model rather than DMRG. This method of training is familiar to ML practitioners and is built-in to TensorFlow~\cite{TensorFlow}, which is the TensorNetwork backend we use. We also empirically find it useful to use an alternative contraction order compared to Stoudenmire and Schwab when computing components of the MPS for ease of parallelization. MPS methods were previously applied into Fashion-MNIST in~\cite{fashionMPS}, and we achieve the same accuracy here. In terms of speed, we note that a factor of more than 10 improvement is gained moving from CPU to GPU hardware using the same code with a TensorFlow backend. Up to a few tweaks of implementation, the main strategies we employ for image classification can be found elsewhere. The purpose of this note is to be a resource for machine learning practitioners who wish to learn how tensor networks can be applied to classification problems. An important part of this is the code that we have uploaded to GitHub~\cite{library}, which we hope will also be a valuable resource for the community. To summarize the results, we find that using an MPS tensor network for classification results in 98\% test accuracy for MNIST and 88\% test accuracy for Fashion-MNIST. The only hyperparameter in the model is the bond dimension, $\chi$, but we find that the results are largely independent of $\chi$ for $\chi \gtrsim 10$. We also compare training times on CPU and GPU, and find that the GPU leads to about 10x speedup over the 64-core CPU. \section{Setup} \subsection{Encoding Data in a Tensor Network}\label{sec-encoding} In this section we will briefly review the structure of a tensor network and how it is used to encode image data. See~\cite{library} for further background that does not assume expertise in quantum physics. The motivation for using a tensor network for data analysis is similar to the motivation for using a kernel method. Even though tensor networks are most useful for linear operations on data, they act on a very high-dimensional space, and that high dimensionality can be leveraged into representation power. We begin by carefully defining that high-dimensional space. For us an image consists of a list of $N$ greyscale pixels. In the MNIST and Fashion-MNIST datasets $N = 28^2 = 784$. By flattening the images into a list we lose the two-dimensional nature of the image. This is obviously a drawback and will negatively impact the performance, but our goal is just to illustrate the ideas of a tensor network in a simple application. More complicated schemes could be employed to get around this limitation. See, for example,~\cite{ML9} for an example of two-dimensional tensor network applied to image classification. The $N$ pixel values of an image will be encoded in a $2^N$-dimensional vector space as follows. First, each pixel of the image is encoded into its own two-dimensional pixel space according to a \textit{local feature map}. One local feature map, used in~\cite{ML1}, is \[ \Phi(p) = \begin{pmatrix} \cos \pi p/2 \\ \sin{\pi p/2} \end{pmatrix}. \] Here $p\in [0,1]$ is the pixel value normalized to unit range. Notice that the pixel values $0$ and $1$ get mapped to independent vectors in this space, and all other pixel values are linear combinations of those. If the image were purely black-and-white this would simply be a one-hot encoding of the pixel values. Another feature map which has similar properties is \[ \Phi(p) = \begin{pmatrix} 1-p \\ p \end{pmatrix}. \] In practice we will use the latter, linear feature map, though this is not very important. With color images it would make sense to consider a higher-dimensional pixel space, such as a $2\times 3 = 6$-dimensional space encoding the RGB values of each pixel. Finally, by way of notation we will refer to the components $\Phi(p)_i$, where the $i$ index takes on two values. So for the linear feature map, $\Phi(p)_0 = 1-p$ and $\Phi(p)_1 = p$. The total image space is defined as the tensor product of all of the pixel spaces. A key property of this space is that flipping a single pixel value from black to white results in an independent image vector. In equations, an image $(p_1,p_2,\ldots, p_N)$ is encoded in the image space as \[ (p_1,p_2,\ldots, p_N) \mapsto \Phi(p_1) \otimes \Phi(p_2) \otimes \cdots \otimes \Phi(p_N). \] We will refer to this object as a ``data tensor" or ``data state." The data tensor has $2^N$ components, each of which is the product of one of the two components of the local feature map (e.g., $p$ or $1-p$) over all of the pixels. In index notation, the components of the data tensor are given by \[ \Phi(p_1)_{i_1} \Phi(p_2)_{i_2} \cdots \Phi(p_N)_{i_N}. \] Since there are two possible values for each of the $i_k$ indices, the total number of components is $2^N$. \begin{figure} \includegraphics[width=0.4\textwidth]{MPS} \caption{Matrix Product State (MPS) tensor network. The free indices correspond to the pixels in the image.}\label{fig-MPS} \end{figure} The MPS tensor network represents another type of vector in the image space. As such, it also has $2^N$ components, and the MPS writes each of those components in terms of the product of $N$ matrices. Letting $T$ represent the total MPS tensor, we have \begin{equation}\label{eq-MPS} T_{i_1i_2\cdots i_N} = \sum_{\alpha_1,\alpha_2,\ldots\alpha_N} A^{(1)}_{i_1 \alpha_1}A^{(2)}_{i_2 \alpha_1\alpha_2}A^{(3)}_{i_3 \alpha_2\alpha_3}\cdots A^{(N)}_{i_N \alpha_N}. \end{equation} The ranges of each of the $\alpha_k$ indices, called the bond dimensions, are hyperparameters of the model. The bond dimensions determine the sizes of the $A$ tensors. The components of the $A$ tensors are variational parameters, or weights, that are fixed via training. There is some redundancy in those parameters, known as gauge freedom~\cite{gauge}, but we will not concern ourselves with that here. To summarize, we have described an image space and an embedding of our data into that space in the form of the data tensors. The MPS tensor $T$ is another vector in that space which is not itself the data tensor of a single image. Intuitively speaking, we would like the MPS tensor $T$ to be equal to a linear combination of all of the images in a given class. An image not belonging to the class will be orthogonal to $T$, while an image belonging to the class will not. In the next section we will describe how to train the MPS to have this property. When we have multiple classes to label, we can either construct MPS vectors or add an extra ``label" node to the MPS to keep track of the class. The details of this are discussed in the following sections. \subsection{Objective Function} The classification task can be expressed as finding a map $f$ from the space of objects to the space of labels. In the MNIST case $f$ should map each handwritten image to the corresponding digit from the set $\{0,1,2,\dots ,9\}$. In a machine learning setting $f$ is parametrized using a large number of variational parameters that are then optimized using pairs $(\mathbf{x},y)$ of labeled examples. Here $\mathbf{x}=(p_1,p_2,\dots p_N)\in [0,1]^N$ represents a flattened image and $y\in \{0, 1, \dots, L-1\}$ the corresponding label (with $N=784$ and $L=10$ for MNIST). Typical choices for such parametrization range from a simple linear regression or support vector machines to more complicated deep neural networks. In our setting, following~\cite{ML1}, we define the classification map as follows: First we calculate the inner product between the encoded image vector (see Section~\ref{sec-encoding}) and a variational MPS $T_{i_1i_2...i_N}^l$: \begin{figure} \includegraphics[width=0.4\textwidth]{MPS-data} \caption{Inner product between the variational MPS (blue nodes) and the encoded data vector (red nodes). Notice the free MPS label index, depicted in lighter grey.}\label{fig-MPS-data} \end{figure} \begin{equation}\label{eq-f} f^{(l)}(\mathbf{x}) = \sum _{i_1,i_2,...,i_N=0}^1T_{i_1i_2...i_N}^l\Phi(p_1)_{i_1} \Phi(p_2)_{i_2} \cdots \Phi(p_N)_{i_n}. \end{equation} The inner product is depicted in Fig.~\ref{fig-MPS-data} in tensor network graphical notation. Note that all pixel indices of the MPS are contracted with data, except the index $l=0,1,\dots, L-1$ which is free and used to distinguish the different labels. The position of the $l$ index in the MPS chain is arbitrary, and a typical choice is in the middle (position $N/2$). After calculating the inner product $f^{(l)}(\mathbf{x})$ the classification map is defined as: \[ f(\mathbf{x}) = \mathrm{argmax}_l~f^{(l)}(\mathbf{x}). \] In other words, for each image we select the label whose MPS has the largest overlap with the corresponding encoded image vector. Following the typical machine learning procedure, the variational parameters $A^{(j)}_{i_j\alpha \beta }$ that define each MPS $T$ (see Eq.~\eqref{eq-MPS}) should be tuned to minimize an objective function in the training set. In the original work~\cite{ML1}, the average mean squared error was chosen as the objective function. Here we choose instead to optimize the multi-class cross-entropy defined on our training set $\mathcal{D}$ as: \begin{equation}\label{eq-loss} \text{CE} = -\sum _{(\mathbf{x}_i, y_i)\in \mathcal{D}} \log \mathrm{softmax}~f^{(y_i)}(\mathbf{x}_i), \end{equation} where \[ \mathrm{softmax}~f^{(y_i)}(\mathbf{x}_i) = \frac{e^{f^{(y_i)}(\mathbf{x}_i)}}{\sum _{l=0}^{L-1}e^{f^{(l)}(\mathbf{x}_i)}}. \] Note that the outputs the softmax function can be interpreted as the predicted probabilities for each label. The final prediction corresponds to the label with the maximum probability. The cross-entropy following a softmax activation is a choice that is well suited to classification problems, as is known from standard machine learning methods. \subsection{Implementation} High level frameworks such as TensorFlow allow for an efficient implementation of standard machine learning algorithms, such us neural networks, through a very simple API. One of the reasons for this simplicity is the automatic calculation of gradients used in the famous backpropagation algorithm~\cite{backprop}. The user only needs to define the forward pass of the model, which is generally straightforward, while the more complicated backward pass is handled automatically by the library. Gradient optimization methods are not the typical choice for optimizing tensor networks. In most physics applications, sweeping algorithms, such as the celebrated Density Matrix Renormalization Group (DMRG)~\cite{White} are preferred, as they can lead to faster convergence. Regardless of that, a "brute force" optimization using the gradients of the objective function is will work for the tensor network case, too. This approach may be suboptimal when compared to a more sophisticated sweeping method, but the simplicity of the underlying code for gradient-based optimization when written in a high-level machine learning library can be more attractive to machine learning practitioners. \begin{figure} \includegraphics[width=0.7\textwidth]{MPS-left-contraction} \caption{Contract MPS in order.}\label{fig-MPS-left-contr} \end{figure} The way the automatic differentiation works is strongly dependent on how the forward pass is defined by the user. When using high-level libraries, one should take advantage of the efficiency of vectorized operations, as this will lead to a more efficient forward pass and possibly more efficient gradients as well. In our case, the forward pass amounts to calculating the inner product of Eq.~\eqref{eq-f} (see Fig.~\ref{fig-MPS-data}). A straightforward way to calculate this inner product (or equivalently to contract the tensor network), which is also commonly used in sweeping methods, is depicted in Fig.~\ref{fig-MPS-left-contr}. Denoting with $d$ the dimension of the pixel space (size of vertical legs in the figure, where $d=2$ for the feature map described in Section~\ref{sec-encoding}) and $\chi $ the bond dimension (size of horizontal legs) which we assume to be constant across the MPS, then the cost of contracting a vertical leg is $O(\chi d)$, while the cost of contracting a horizontal leg is $O(d\chi ^2)$. Assuming that we continue the contraction as depicted from left to right, once we pass the free label index we will have to keep tack of the label for the rest of the contractions, increasing all costs by a factor of $L$ (the number of different labels) and leading to a total cost of order $O(NLd\chi ^2)$. An easy way to avoid the extra factor of $L$ is to start a contraction from both ends of the chain and contract with the tensor that carries the label index in the final step, resulting to an improved total cost of $O(Nd\chi ^2)$. Note that this analysis only takes into account the forward pass, that is calculating $f^{(l)}(\mathbf{x})$ for a given $\mathbf{x}$, and not its gradients with respect the MPS parameters, for which we cannot avoid the additional $L$ factors. \begin{figure} \includegraphics[width=0.7\textwidth]{MPS-bin-contraction} \caption{Parallelized MPS contraction. (i) Contract all of the pixel indices with a data tensor. This creates new effective tensors depicted as dark blue squares. (ii) Contract the new tensors in pairs. This step can be done independently and in parallel for each pair. The result is a new chain with half as many effective tensors. (iii) Contract again in pairs, and repeat until the chain is fully contracted.}\label{fig-MPS-bin-contr} \end{figure} Although this method of contraction is expected to work well when coded using a low-level language, we empirically find it to be suboptimal for our specific application and the particular choices of the parameters $N$, $d$ and $\chi $, both in the forward pass and also in the automatic backward pass. We follow an alternative contraction order inspired by the implementation of~\cite{torchmps} and depicted in Fig~\ref{fig-MPS-bin-contr}. The total cost of this contraction is $O(Nd\chi ^2 + \chi^3\log N)$, where the first term comes from step (i) and the second term from the consecutive pairwise contractions. This method requires fewer contractions per site, however the cost scales as $\chi^3$ as it requires matrix-matrix multiplications. In contrast, the first method only has matrix-vector contractions. Even though the total cost is higher asymptotically for the second method, an advantage is that each step is easy to parallelize as the matrix multiplications are independent and do not require results from the neighboring calculation (as they do in the first method). This is of particular importance when using a machine learning library such as TensorFlow, as the supported batching operations can be used to easily implement these contractions in parallel. We note that this implementation does not only lead to a faster forward pass, but also to a more efficient automatic gradient calculation. \subsection{Optimization} As described in the previous section, upon defining our model's forward pass as depicted in Fig.~\ref{fig-MPS-bin-contr}, TensorFlow automatically calculates the gradients of the loss function in Eq.~\eqref{eq-loss}. These gradients are then used to minimize the loss via a stochastic gradient descent method. A typical setting that we find to perform well is to use Adam optimizer~\cite{adam} with a learning rate of $10^{-4}$ and batch sizes ranging from $10$ to $100$ samples depending on the total amount of training data used. We note that in the original sweeping DMRG-like optimization method proposed in~\cite{ML1} each step updates two of the MPS tensors. In contrast, in gradient based methods using automatic differentiation typically all variational tensors are updated simultaneously in each update step. A disadvantage of this method, when implemented naively, is that the bond dimension $\chi $ is an additional hyperparameter that is set a priori and is kept constant during training. In the sweeping implementation, a singular value decomposition (SVD) step allows to adaptively change bond dimensions during training. This is a particularly interesting feature as it allows the model to change the number of its variational parameters according to the complexity of data to be learned. \section{Results} \begin{figure} \includegraphics[width=0.9\textwidth]{mnist_softmax.pdf} \caption{Evolution of training (solid) and test (dashed) loss and accuracy during training on the MNIST dataset.}\label{fig-mnist-training} \end{figure} \begin{figure} \includegraphics[width=0.9\textwidth]{fashion_softmax.pdf} \caption{Evolution of training (solid) and test (dashed) loss and accuracy during training on the Fashion-MNIST dataset.}\label{fig-fashion-training} \end{figure} We implement the contraction method described in Fig.~\ref{fig-MPS-bin-contr} using TensorNetwork with the TensorFlow backend, and we optimize using the built-in automatic differentiation and Adam optimizer with learning rate set to $10^{-4}$. We first train on the total MNIST training set consisting of 60,000 images of size $28\times 28$ and we show the relevant training history in Fig.~\ref{fig-mnist-training}. Each training epoch corresponds to a full iteration over the training set using a batch size of $50$. We observe that with this setting the model requires about $50$ epochs to converge to almost 100\% training accuracy and about 98\% test accuracy. Here test accuracy is calculated on the whole test dataset consisting of 10,000 images. Training with automatic gradients is found to be independent of the used bond dimension, with largest bond dimensions being of course more computationally expensive. In Fig.~\ref{fig-acc} left we plot the final training and test accuracies as a function of the bond dimension. Here the test accuracy is calculated on the MNIST test set of $10,000$ images once training is completed. We again find no dependence on the bond dimension obtaining about 98\% test accuracy, in agreement with previous works. Furthermore we compare optimizing with our softmax cross-entropy loss (denoted as CE) with the original mean square loss from~\cite{ML1} and we find no significant difference in terms of final accuracies. The square loss is more efficient to calculate and thus leads to slightly faster convergence in terms of actual wall time, however the difference is negligible as the bond dimension is increased, when contractions dominate the computation time. \begin{figure} \includegraphics[width=0.9\textwidth]{all_acc.pdf} \caption{Final accuracies on the full train (60,000 images) and test (10,000) sets as a function of bond dimension. The left plot is on the MNIST dataset of hand-written digits and the right plot on Fashion-MNIST. Blue color (squares and circles) corresponds to the training set and red color (triangles and diamonds) to the test set. For MNIST we also compare performance using the cross-entropy loss (solid lines) to the mean square loss (dotted lines) employed in~\cite{ML1}.}\label{fig-acc} \end{figure} We repeat the same optimization schedule for Fashion-MNIST, a dataset that has exactly the same structure as MNIST ($28\times 28$ grayscale images of clothing with $L=10$ labels), however it is significantly harder to classify, with state of the art deep learning methods obtaining about 93\% test accuracy~\cite{fashionSOTA}. The corresponding training dynamics are shown in Fig.~\ref{fig-fashion-training}. As demonstrated in Fig.~\ref{fig-acc} right we are able to obtain 88\% test accuracy and we again find no significant dependence on the bond dimension. Finally, it is well known that the use of accelerators such us GPU can greatly reduce training time for many machine learning models, particularly in cases where complexity is dominated by linear algebra operations. Since this is the case with tensor networks, we expect to see some advantage in our methods. TensorNetwork with the TensorFlow backend allows direct implementation on a GPU without any changes in the code. In Fig.~\ref{fig-times} we verify the advantage, with the GPU being four times faster for the smallest bond dimension and the relative speed-up increasing with increasing bond dimension. \begin{figure} \includegraphics[width=0.7\textwidth]{cpu_times.pdf} \caption{Wall-time required per optimization epoch when implementing the same TensorNetwork/TensorFlow code on GPU and CPU. One epoch corresponds to a full iteration over the whole training set.}\label{fig-times} \end{figure} \section{Conclusion} Here we have described a tensor network algorithm for image classification using MPS tensor networks. All of the code required for reproducing the results in the open source TensorNetwork library is available on GitHub~\cite{library}. We are hopeful that the techniques we reviewed here will be taken up by the wider ML community, and that the code examples we are providing will become a valuable resource. By using TensorFlow as a backend, we were able to access automatic gradients for optimization of the tensor network, which moves us beyond the physics-centric techniques ordinarily used. Furthermore, TensorFlow already offers high-level methods for deploying state-of-the-art deep learning models. Adding tensor network machinery to that same library will allow direct comparison between these tools to more traditional machine learning methods, such as neural networks, a particularly active research area. Ultimately, one might be even able to further push the state-of-the-art by combining tensor networks with more traditional methods, something that can be implemented very easily using TensorNetwork on top of TensorFlow. \begin{acknowledgements} We would like to thank Glen Evenbly, Martin Ganahl, Ash Milsted, Chase Roberts, Miles Stoudenmire, and Guifre Vidal for valuable discussions. X is formerly known as Google[x] and is part of the Alphabet family of companies, which includes Google, Verily, Waymo, and others (www.x.company). \end{acknowledgements}
{'timestamp': '2019-06-17T02:18:34', 'yymm': '1906', 'arxiv_id': '1906.06329', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06329'}
arxiv
\section{Introduction} \label{intro} Neural Machine Translation (NMT) has made considerable progress in recent years~\cite{bahdanau2014neural, gehring2017convolutional, vaswani2017attention}. Traditional NMT has relied solely on parallel sentence pairs for training data, which can be an expensive and scarce resource. This motivates the use of monolingual data, usually more abundant \cite{lambert2011investigations}. Approaches using monolingual data for machine translation include language model fusion for both phrase-based \cite{brants2007large,koehn2009statistical} and neural MT \cite{gulcehre2015using,gulcehre2017integrating}, back-translation \cite{sennrich2016improving,poncelas2018investigating}, unsupervised machine translation \cite{lample2017unsupervised, artetxe2018unsupervised}, dual learning \cite{cheng2016semisupervised, he2016dual, xia2017dual}, and multi-task learning \cite{domhan2017using}. We focus on back-translation (BT), which, despite its simplicity, has thus far been the most effective technique \cite{sennrich2017edinburgh,ha2017effective,garcia2017lium}. Back-translation entails training an intermediate target-to-source model on genuine bitext, and using this model to translate a large monolingual corpus from the target into the source language. This allows training a source-to-target model on a mixture of genuine parallel data and synthetic pairs from back-translation. We build upon \newcite{edunov2018understanding} and \newcite{imamura2018enhancement}, who investigate BT at the scale of hundreds of millions of sentences. Their work studies different decoding/generation methods for back-translation: in addition to regular beam search, they consider sampling and adding noise to the one-best hypothesis produced by beam search. They show that sampled BT and noised-beam BT significantly outperform standard BT, and attribute this success to increased source-side diversity (sections 5.2 and 4.4). Our work investigates noised-beam BT (NoisedBT) and questions the role noise is playing. Rather than increasing source diversity, our work instead suggests that the performance gains come simply from signaling to the model that the source side is back-translated, allowing it to treat the synthetic parallel data differently than the natural bitext. We hypothesize that BT introduces both helpful signal (strong target-language signal and weak cross-lingual signal) and harmful signal (amplifying the biases of machine translation). Indicating to the model whether a given training sentence is back-translated should allow the model to separate the helpful and harmful signal. To support this hypothesis, we first demonstrate that the permutation and word-dropping noise used by \citet{edunov2018understanding} do not improve or significantly degrade NMT accuracy, corroborating that noise might act as an indicator that the source is back-translated, without much loss in mutual information between the source and target. We then train models on WMT English-German (EnDe) without BT noise, and instead explicitly tag the synthetic data with a reserved token. We call this technique ``Tagged Back-Translation" (TaggedBT). These models achieve equal to slightly higher performance than the noised variants. We repeat these experiments with WMT English-Romanian (EnRo), where NoisedBT underperforms standard BT and TaggedBT improves over both techniques. We demonstrate that TaggedBT also allows for effective iterative back-translation with EnRo, a technique which saw quality losses when applied with standard back-translation. To further our understanding of TaggedBT, we investigate the biases encoded in models by comparing the entropy of their attention matrices, and look at the attention weight on the tag. We conclude by investigating the effects of the back-translation tag at decoding time. \section{Related Work} This section describes prior work exploiting target-side monolingual data and discusses related work tagging NMT training data. \subsection{Leveraging Monolingual Data for NMT} Monolingual data can provide valuable information to improve translation quality. Various methods for using target-side LMs have proven effective for NMT~\cite{he2016improved,gulcehre2017integrating}, but have tended to be less successful than back-translation -- for example, \citet{gulcehre2017integrating} report under +0.5 \BLEU over their baseline on EnDe newstest14, whereas \citet{edunov2018understanding} report over +4.0 \BLEU on the same test set. Furthermore, there is no straighforward way to incorporate source-side monolingual data into a neural system with a LM. Back-translation was originally introduced for phrase-based systems~\cite{bertoldi2009domain,bojar2011improving}, but flourished in NMT after work by~\newcite{sennrich2016improving}. Several approaches have looked into iterative forward- and BT experiments (using source-side monolingual data), including \newcite{cotterell2018explaining}, \newcite{hoang2018iterative}, and \newcite{niu2018bidirectional}. Recently, iterative back-translation in both directions has been devised has a way to address unsupervised machine translation~\cite{lample2018phrase,artetxe2018unsupervised}. Recent work has focused on the importance of diversity and complexity in synthetic training data. \citet{fadaee2018backtranslation} find that BT benefits difficult-to-translate words the most, and select from the back-translated corpus by oversampling words with high prediction loss. \citet{imamura2018enhancement} argue that in order for BT to enhance the encoder, it must have a more diverse source side, and sample several back-translated source sentences for each monolingual target sentence. Our work follows most closely \citet{edunov2018understanding}, who investigate alternative decoding schemes for BT. Like \citet{imamura2018enhancement}, they argue that BT through beam or greedy decoding leads to an overly regular domain on the source side, which poorly represents the diverse distribution of natural text. Beyond the scope of this work, we briefly mention alternative techniques leveraging monolingual data, like forward translation~\cite{ueffing2007semi,kim-rush-2016-sequence}, or source copying~\cite{currey2017}. \subsection{Training Data Tagging for NMT} Tags have been used for various purposes in NMT. Tags on the source sentence can indicate the target language in multi-lingual models~\cite{johnson2016google}. \citet{yamagishi2016controlling} use tags in a similar fashion to control the formality of a translation from English to Japanese. \citet{kuczmarski2018gender} use tags to control gender in translation. Most relevant to our work, \citet{kobus2016controlling} use tags to mark source sentence domain in a multi-domain setting. \section{Experimental Setup} This section presents our datasets, evaluation protocols and model architectures. It also describes our back-translation procedure, as well as noising and tagging strategies. \subsection{Data} We perform our experiments on WMT18 EnDe bitext, WMT16 EnRo bitext, and WMT15 EnFr bitext respectively. We use WMT Newscrawl for monolingual data (2007-2017 for De, 2016 for Ro, 2007-2013 for En, and 2007-2014 for Fr). For bitext, we filter out empty sentences and sentences longer than 250 subwords. We remove pairs whose whitespace-tokenized length ratio is greater than 2. This results in about 5.0M pairs for EnDe, and 0.6M pairs for EnRo. We do not filter the EnFr bitext, resulting in 41M sentence pairs. For monolingual data, we deduplicate and filter sentences with more than 70 tokens or 500 characters. Furthermore, after back-translation, we remove any sentence pairs where the back-translated source is longer than 75 tokens or 550 characters. This results in 216.5M sentences for EnDe, 2.2M for EnRo, 149.9M for RoEn, and 39M for EnFr. For monolingual data, all tokens are defined by whitespace tokenization, not wordpieces. The DeEn model used to generate BT data has 28.6 \SacreBLEU on newstest12, the RoEn model used for BT has a test \SacreBLEU of 31.9 (see Table~\ref{enro}.b), and the FrEn model used to generate the BT data has 39.2 \SacreBLEU on newstest14. \subsection{Evaluation} We rely on \BLEU score~\cite{papineni2002bleu} as our evaluation metric. While well established, any slight difference in post-processing and \BLEU computation can have a dramatic impact on output values \cite{post2018call}. For example, \citet{lample2019cross} report 33.3 \BLEU on EnRo using unsupervised NMT, which at first seems comparable to our reported 33.4 \SacreBLEU from iterative TaggedBT. However, when we use their preprocessing scripts and evaluation protocol, our system achieves 39.2 \BLEU on the same data, which is close to 6 points higher than the same model evaluated by \SacreBLEU. We therefore report strictly \SacreBLEU\footnote{BLEU + case.mixed + lang.LANGUAGE\_PAIR + numrefs.1 + smooth.exp + test.SET + tok.13a + version.1.2.15}, using the reference implementation from ~\newcite{post2018call}, which aims to standardize \BLEU evaluation. \subsection{Architecture} We use the transformer-base and transformer-big architectures~\cite{vaswani2017attention} implemented in {\it lingvo}~\cite{shen2019lingvo}. Transformer-base is used for the bitext noising experiments and the EnRo experiments, whereas the transformer-big is used for the EnDe tasks with BT. Both use a vocabulary of 32k subword units. As an alternative to the checkpoint averaging used in \newcite{edunov2018understanding}, we train with exponentially weighted moving average (EMA) decay with weight decay parameter $\alpha=0.999$~\cite{buduma2017fundamentals}. Transformer-base models are trained on 16 GPUs with synchronous gradient updates and per-gpu-batch-size of 4,096 tokens, for an effective batch size of 64k tokens/step. Training lasts 400k steps, passing over 24B tokens. For the final EnDe TaggedBT model, we train transformer-big similarly but on 128 GPUs, for an effective batch size of 512k tokens/step. A training run of 300M steps therefore sees about 150B tokens. We pick checkpoints with newstest2012 for EnDe and newsdev2016 for EnRo. \subsection{Noising} \label{section:noising} We focused on noised beam BT, the most effective noising approach according to \citet{edunov2018understanding}. Before training, we noised the decoded data \cite{lample2017unsupervised} by applying 10\% word-dropout, 10\% word blanking, and a 3-constrained permutation (a permutation such that no token moves further than 3 tokens from its original position). We refer to data generated this way as NoisedBT. Additionally, we experiment using only the 3-constrained permutation and no word dropout/blanking, which we abbreviate as P3BT. \subsection{Tagging} \label{section:tagging} We tag our BT training data by prepending a reserved token to the input sequence, which is then treated in the same way as any other token. We also experiment with both noising and tagging together, which we call Tagged Noised Back-Translation, or TaggedNoisedBT. This consists simply of prepending the $<$BT$>$ tag to each noised training example. An example training sentence for each of these set-ups can be seen in Table~\ref{noise_example}. We do not tag the bitext, and always train on a mix of back-translated data and (untagged) bitext unless explicitly stated otherwise. \begin{table}[ht] \small \centering \begin{tabular}{l|l} Noise type & Example sentence \\ \hline [no noise] & Raise the child, love the child. \\ P3BT & child Raise the, love child the. \\ NoisedBT & Raise child \underline{\hspace{5mm}} love child, the. \\ TaggedBT & $<$BT$>$ Raise the child, love the child. \\ TaggedNoisedBT & $<$BT$>$ Raise, the child the \underline{\hspace{5mm}} love. \\ \end{tabular} \caption{Examples of the five noising settings examined in this paper \label{noise_example}} \end{table} \section{Results} This section studies the impact of training data noise on translation quality, and then presents our results with TaggedBT on EnDe and EnRo. \subsection{Noising Parallel Bitext} We first show that noising EnDe bitext sources does not seriously impact the translation quality of the transformer-base baseline. For each sentence pair in the corpus, we flip a coin and noise the source sentence with probability $p$. We then train a model from scratch on this partially noised dataset. Table \ref{noise_bitext} shows results for various values of $p$. Specifically, it presents the somewhat unexpected finding that even when noising 100\% of the source bitext (so the model has never seen well-formed English), \BLEU on well-formed test data only drops by 2.5. This result prompts the following line of reasoning about the role of noise in BT: (i) By itself, noising does not add meaningful signal (or else it would improve performance); (ii) It also does not damage the signal much; (iii) In the context of back-translation, the noise could therefore signal whether a sentence were back-translated, without significantly degrading performance. \begin{table}[ht] \small \centering \begin{tabular}{l|cc} & \multicolumn{2}{c}{\SacreBLEU} \\ \% noised & Newstest '12 & Newstest '17 \\ \hline\hline 0\% & 22.4 & 28.1 \\ 20\% & 22.4 & 27.9 \\ 80\% & 21.5 & 27.0 \\ 100\% & 21.2 & 25.6 \\ \end{tabular} \caption{\SacreBLEU degradation as a function of the proportion of bitext data that is noised. \label{noise_bitext}} \end{table} \subsection{Tagged Back-Translation for EnDe} We compare the results of training on a mixture of bitext and a random sample of 24M back-translated sentences in Table~\ref{en_de_bt}.a, for the various set-ups of BT described in sections \ref{section:noising} and \ref{section:tagging}. Like \newcite{edunov2018understanding}, we confirm that BT improves over bitext alone, and noised BT improves over standard BT by about the same margin. All methods of marking the source text as back-translated (NoisedBT, P3BT, TaggedBT, and TaggedNoisedBT) perform about equally, with TaggedBT having the highest average \BLEU by a small margin. Tagging and noising together (TaggedNoisedBT) does not improve over either tagging or noising alone, supporting the conclusion that tagging and noising are not orthogonal signals but rather different means to the same end. \begin{table*}[ht] \small \centering \begin{tabular}{l|cccccccccc} \multicolumn{4}{c}{a. Results on 24M BT Set}\\ Model & AVG 13-18 & 2010 & 2011 & 2012 & 2013 & 2014 & 2015 & 2016 & 2017 & 2018 \\ \hline\hline Bitext & 32.05 & 24.8 & 22.6 & 23.2 & 26.8 & 28.5 & 31.1 & 34.7 & 29.1 & 42.1 \\ \hline BT & 33.12 & 24.7 & 22.6 & 23.5 & 26.8 & 30.8 & 30.9 & 36.1 & 30.6 & 43.5 \\ \hline NoisedBT & 34.70 & 26.2 & \textbf{23.7 }& \textbf{24.7} & \textbf{28.5 }& 31.3 & 33.1 & 37.7 & \textbf{31.7 }& \textbf{45.9} \\ P3BT & 34.57 & 26.1 & 23.6 & 24.5 & 28.1 & 31.8 & 33.0 & 37.4 & 31.5 & 45.6 \\ TaggedBT & \textbf{34.83 } & \textbf{26.4} & 23.6 & 24.5 & 28.1 & \textbf{32.1} & \textbf{33.4} & \textbf{37.8} &\textbf{ 31.7} & \textbf{45.9} \\ TaggedNoisedBT & 34.52 & 26.3 & 23.4 & 24.6 & 27.9 & 31.4 & 33.1 & 37.4 &\textbf{ 31.7} & 45.6 \\ \hline BT alone & 31.20 & 23.5 & 21.2 & 22.7 & 25.2 & 29.3 & 29.4 & 33.7 & 29.1 & 40.5 \\ NoisedBT alone & 30.28 & 23.2 & 21.0 & 22.1 & 24.6 & 28.4 & 28.2 & 33.0 & 28.1 & 39.4 \\ \hline Noised(BT + Bitext) & 32.07 & 24.2 & 22.1 & 23.5 & 26.2 & 29.7 & 30.1 & 35.1 & 29.4 & 41.9 \\ + Tag on BT & 33.53 & 25.5 & 22.8 & 24.5 & 27.6 & 30.3 & 31.9 & 36.9 & 30.4 & 44.1 \\ \multicolumn{4}{c}{}\\ \multicolumn{4}{c}{b. Results on 216M BT Set}\\ Model & AVG 13-18 & 2010 & 2011 & 2012 & 2013 & 2014 & 2015 & 2016 & 2017 & 2018 \\ \hline\hline \citet{edunov2018understanding} & 35.28 & & & 25.0 & \textbf{29.0} & \textbf{33.8} & 34.4 & 37.5 & \textbf{32.4} & 44.6 \\ NoisedBT & 35.17 & \textbf{26.7} & 24.0 & \textbf{25.2 }& 28.6 & 32.6 & 33.9 & 38.0 & 32.2 & 45.7 \\ TaggedBT & \textbf{35.42} & 26.5 & \textbf{24.2 }& \textbf{25.2} & 28.7 & 32.8 & \textbf{34.5} & \textbf{38.1 }& \textbf{32.4} & \textbf{46.0} \\ \end{tabular} \caption{\SacreBLEU on Newstest EnDe for different types of noise, with back-translated data either sampled down to 24M or using the full set of 216M sentence pairs. \label{en_de_bt}} \end{table*} Table~\ref{en_de_bt}.b verifies our result at scale applying TaggedBT on the full BT dataset (216.5M sentences), upsampling the bitext so that each batch contains an expected 20\% of bitext. As in the smaller scenario, TaggedBT matches or slightly out-performs NoisedBT, with an advantage on seven test-sets and a disadvantage on one. We also compare our results to the best-performing model from \newcite{edunov2018understanding}. Our model is on par with or slightly superior to their result\footnote{\SacreBLEU for the WMT-18 model at \url{github.com/pytorch/fairseq}}, out-performing it on four test sets and under-performing it on two, with the largest advantage on Newstest2018 (+1.4 \BLEU). As a supplementary experiment, we consider training only on BT data, with no bitext. We compare this to training only on NoisedBT data. If noising in fact increases the quality or diversity of the data, one would expect the NoisedBT data to yield higher performance than training on unaltered BT data, when in fact it has about 1 \BLEU lower performance (Table \ref{en_de_bt}.a, ``BT alone" and ``NoisedBT alone"). We also compare NoisedBT versus TaggedNoisedBT in a set-up where the bitext itself is noised. In this scenario, the noise can no longer be used by the model as an implicit tag to differentiate between bitext and synthetic BT data, so we expect the TaggedNoisedBT variant to perform better than NoisedBT by a similar margin to NoisedBT's improvement over BT in the unnoised-bitext setting. The last sub-section of Table \ref{en_de_bt}.a confirms this. \subsection{Tagged Back-Translation for EnRo} We repeat these experiments for WMT EnRo (Table \ref{enro}). This is a much lower-resource task than EnDe, and thus can benefit more from monolingual data. In this case, NoisedBT is actually harmful, lagging standard BT by -0.6 \BLEU. TaggedBT closes this gap and passes standard BT by +0.4 \BLEU, for a total gain of +1.0 \BLEU over NoisedBT. \begin{table}[ht] \small \centering \begin{tabular}{l|cc} \multicolumn{3}{c}{a. Forward models (EnRo)} \\ Model & dev & test \\ \hline\hline \citet{gehring2017convolutional} & & \textit{29.9} \\ Sennrich 2016 (BT) & \textit{29.3} &\textit{ 28.1} \\ \hline bitext & 26.5 & 28.3 \\ \hline BT & 31.6 & 32.6 \\ NoisedBT & 29.9 & 32.0 \\ TaggedBT & 30.5 & 33.0 \\ It.-3 BT & 31.3 & 32.8 \\ It.-3 NoisedBT & 31.2 & 32.6 \\ It.-3 TaggedBT & 31.4 & \textbf{33.4} \\ \multicolumn{3}{c}{} \\ \multicolumn{3}{c}{b. Reverse models (RoEn)} \\ Model & dev & test \\ \hline\hline bitext & 32.9 & 31.9 \\ It.-2 BT & 39.5 & \textbf{37.3} \\ \end{tabular} \caption{Comparing \SacreBLEU scores for different flavors of BT for WMT16 EnRo. Previous works' scores are reported in italics as they use \texttt{detok.multi-bleu} instead of \SacreBLEU, so are not guaranteed to be comparable. In this case, however, we do see identical \BLEU on our systems when we score them with \texttt{detok.multi-bleu}, so we believe it to be a fair comparison. \label{enro}} \end{table} \subsection{Tagged Back-Translation for EnFr} We performed a minimal set of experiments on WMT EnFr, which are summarized in Table \ref{enfr}. This is a much higher-resource language pair than either EnRo or EnDe, but \citet{edunov2018understanding} demonstrate that noised BT (using sampling) can still help in this set-up. In this case, we see that BT alone hurts performance compared to the strong bitext baseline, but NoisedBT indeed surpasses the bitext model. TaggedBT out-performs all other methods, beating NoisedBT by an average of +0.3 \BLEU over all test sets. It is worth noting that our numbers are lower than those reported by \citet{edunov2018understanding} on the years they report (36.1, 43.8, and 40.9 on 2013, 2014, and 2015 respectively). We did not investigate this result. We suspect that this is an error/inoptimlaity in our set-up, as we did not optimize these models, and ran only one experiment for each of the four set-ups. Alternately, sampling could outperform noising in the large-data regime. \begin{table*}[ht] \small \centering \begin{tabular}{l|ccccccccc} Model & Avg & 2008 & 2009 & 2010 & 2011 & 2012 & 2013 & 2014 & 2015 \\ \hline\hline Bitext & 32.8 & 26.3 & 28.8 & 32.0 & 32.9 & 30.1 & 33.5 & 40.6 & 38.4 \\ BT & 29.2 & 22.2 & 27.3 & 28.8 & 29.3 & 27.9 & 30.7 & 32.6 & 34.8 \\ NoisedBT & 33.8 & 26.8 & 29.9 & 33.4 & \textbf{33.9} & \textbf{31.3} & 34.3 & 42.3 & 38.8 \\ TaggedBT & \textbf{34.1} & \textbf{ 27.0 }& \textbf{30.0} & \textbf{33.6} & \textbf{33.9} & 31.2 & \textbf{34.4} & \textbf{42.7} & \textbf{39.8} \\ \hline \end{tabular} \caption{Results on WMT15 EnFr, with bitext, BT, NoisedBT, and TaggedBT. \label{enfr}} \end{table*} \subsection{Iterative Tagged Back-Translation} We further investigate the effects of TaggedBT by performing one round of iterative back-translation \cite{cotterell2018explaining,hoang2018iterative,niu2018bidirectional}, and find another difference between the different varieties of BT: NoisedBT and TaggedBT allow the model to bootstrap improvements from an improved reverse model, whereas standard BT does not. This is consistent with our argument that data tagging allows the model to extract information out of each data set more effectively. For the purposes of this paper we call a model trained with standard back-translation an \textbf{Iteration-1 BT model}, where the back-translations were generated by a model trained only on bitext. We inductively define the \textbf{Iteration-k BT model} as that model which is trained on BT data generated by an \mbox{\textbf{Iteration-(k-1) BT}} model, for $k>1$. Unless otherwise specified, any BT model mentioned in this paper is an Iteration-1 BT model. We perform these experiments on the English-Romanian dataset, which is smaller and thus better suited for this computationally expensive process. We used the (Iteration-1) TaggedBT model to generate the RoEn back-translated training data. Using this we trained a superior RoEn model, mixing 80\% BT data with 20\% bitext. Using this Iteration-2 RoEn model, we generated new EnRo BT data, which we used to train the Iteration-3 EnRo models. \SacreBLEU scores for all these models are displayed in Table~\ref{enro}. We find that the iteration-3 BT models improve over their Iteration-1 counterparts only for NoisedBT (+1.0 \BLEU, dev+test avg) and TaggedBT (+0.7 \BLEU, dev+test avg), whereas the Iteration-3 BT model shows no improvement over its Iteration-1 counterpart (-0.1 \BLEU, dev+test avg). In other words, both techniques that (explicitly or implicitly) tag synthetic data benefit from iterative BT. We speculate that this separation of the synthetic and natural domains allows the model to bootstrap more effectively from the increasing quality of the back-translated data while not being damaged by its quality issues, whereas the simple BT model cannot make this distinction, and is equally ``confused" by the biases in higher or lower-quality BT data. An identical experiment with EnDe did not see either gains or losses in \BLEU from iteration-3 TaggedBT. This is likely because there is less room to bootstrap with the larger-capacity model. This said, we do not wish to read too deeply into these results, as the effect size is not large, and neither is the number of experiments. A more thorough suite of experiments is warranted before any strong conclusions can be made on the implications of tagging on iterative BT. \section{Analysis} In an attempt to gain further insight into TaggedBT as it compares with standard BT or NoisedBT, we examine attention matrices in the presence of the back translation tag and measure the impact of the tag at decoding time. \begin{figure*}[!ht] \begin{subfigure}{.5\textwidth} \begin{subfigure}{1.0\textwidth} \centering \includegraphics[width=.8\linewidth]{ende-bt.png} \caption{EnDe BT} \label{pretty-attention:ende-bt} \end{subfigure} \begin{subfigure}{1.0\textwidth} \centering \includegraphics[width=.8\linewidth]{ende-nbt.png} \caption{EnDe NoisedBT} \label{pretty-attention:ende-nbt} \end{subfigure} \begin{subfigure}{1.0\textwidth} \centering \includegraphics[width=.8\linewidth]{ende-tbt.png} \caption{EnDe TaggedBT} \label{pretty-attention:ende-tbt} \end{subfigure} \end{subfigure}% \begin{subfigure}{.5\textwidth} \begin{subfigure}{1.0\textwidth} \centering \includegraphics[width=.8\linewidth]{enro-bt.png} \caption{EnRo BT} \label{pretty-attention:enro-bt} \end{subfigure} \begin{subfigure}{1.0\textwidth} \centering \includegraphics[width=.8\linewidth]{enro-nbt.png} \caption{EnRo NoisedBT} \label{pretty-attention:enro-nbt} \end{subfigure} \begin{subfigure}{1.0\textwidth} \centering \includegraphics[width=.8\linewidth]{enro-tbt.png} \caption{EnRo TaggedBT} \label{pretty-attention:enro-tbt} \end{subfigure} \end{subfigure} \caption{Comparison of attention maps at the first encoder layer for a random training example for BT (row 1), NoisedBT (row 2), and TaggedBT (row 3), for both EnDe (col 1) and EnRo (col 2). Note the heavy attention on the tag (position 0 in row 3), and the diffuse attention map learned by the NoiseBT models. These are the models from Table~\ref{en_de_bt}.a} \label{pretty-attention} \end{figure*} \subsection{Attention Entropy and Sink-Ratio} To understand how the model treats the tag and what biases it learns from the data, we investigate the entropy of the attention probability distribution, as well as the attention captured by the tag. We examine decoder attention (at the top layer) on the first source token. We define Attention Sink Ratio for index $j$ ($\textrm{ASR}_j$) as the averaged attention over the $j$th token, normalized by uniform attention, i.e. $$ \textrm{ASR}_j(x, \hat y) = \frac{1}{|\hat y|} \sum_{i = 1}^{ | \hat y | } \frac{\alpha_{ij}}{\tilde{\alpha}} $$ where $\alpha_{ij}$ is the attention value for target token $i$ in hypothesis $\hat y$ over source token $j$ and $\tilde{\alpha} = \frac{1}{|x|}$ corresponds to uniform attention. We examine ASR on text that has been noised and/or tagged (depending on the model), to understand how BT sentences are treated during training. For the tagged variants, there is heavy attention on the tag when it is present (Table \ref{attn_stats}), indicating that the model relies on the information signalled by the tag. Our second analysis probes word-for-word translation bias through the average source-token entropy of the attention probability model when decoding natural text. Table~\ref{attn_stats} reports the average length-normalized Shannon entropy: $$ \tilde \textrm{H}(x, \hat y) = - \frac{1}{|\hat y|} \sum_{i=1}^{| \hat y|} \frac{1}{\log |x|} \sum_{j=1}^{|x|}\alpha_{ij} \log(\alpha_{ij}) $$ The entropy of the attention probabilities from the model trained on BT data is the clear outlier. This low entropy corresponds to a concentrated attention matrix, which we observed to be concentrated on the diagonal (See Figure~\ref{pretty-attention:ende-bt} and \ref{pretty-attention:enro-bt}). This could indicate the presence of word-by-word translation, a consequence of the harmful part of the signal from back-translated data. The entropy on parallel data from the NoisedBT model is much higher, corresponding to more diffuse attention, which we see in Figure~\ref{pretty-attention:ende-nbt} and ~\ref{pretty-attention:enro-nbt}. In other words, the word-for-word translation biases in BT data, that were incorporated into the BT model, have been manually undone by the noise, so the model's understanding of how to decode parallel text is not corrupted. We see that TaggedBT leads to a similarly high entropy, indicating the model has learnt this without needing to manually ``break" the literal-translation bias. As a sanity check, we see that the entropy of the P3BT model's attention is also high, but is lower than that of the NoisedBT model, because P3 noise is less destructive. The one surprising entry on this table is probably the low entropy of the TaggedNoisedBT. Our best explanation is that TaggedNoisedBT puts disproportionately high attention on the sentence-end token, with 1.4x the $\textrm{ASR}_{|x|}$ that TaggedBT has, naturally leading to lower entropy. \begin{table}[ht] \small \centering \begin{tabular}{l|c|c|c} Model & $\textrm{ASR}_0$ & $\textrm{ASR}_{|x|}$ & $\tilde \textrm{H}$ \\ \hline\hline Bitext baseline & 0.31 & 10.21 & 0.504 \\ BT & 0.28 & 10.98 & \textbf{0.455} \\ P3BT & 0.37 & 7.66 & 0.558 \\ NoisedBT & 1.01 & 3.96 & 0.619 \\ TaggedBT & \textbf{5.31} & 5.31 & 0.597 \\ TaggedNoisedBT & \textbf{7.33} & 7.33 & 0.491 \\ \end{tabular} \small \caption{Attention sink ratio on the first and last token and entropy (at decoder layer 5) for the models in Table~\ref{en_de_bt}.a, averaged over all sentences in newstest14. For ASR, data is treated as if it were BT (noised and/or tagged, resp.), whereas for entropy the natural text is used. Outliers discussed in the text are bolded. \label{attn_stats}} \end{table} \subsection{Decoding with and without a tag} \begin{table*}[ht] \small \centering \begin{tabular}{l|cccccccccc} Model & Decode type & AVG 13-17 & 2010 & 2011 & 2012 & 2013 & 2014 & 2015 & 2016 & 2017 \\ \hline\hline TaggedBT & \multicolumn{1}{l}{standard} & \textbf{33.24} & 26.5 & \textbf{24.2} & \textbf{25.2} & \textbf{28.7} & \textbf{32.8} &\textbf{ 34.5 }& \textbf{38.1} & \textbf{32.4} \\ & \multicolumn{1}{l}{as BT (tagged)} & 30.30 & 24.3 & 22.2 & 23.4 & 26.6 & 30.0 & 30.5 & 34.2 & 30.2 \\ NoisedBT & \multicolumn{1}{l}{standard} & 33.06 & \textbf{26.7} & 24.0 & \textbf{25.2} & 28.6 & 32.6 & 33.9 & 38.0 & 32.2 \\ & \multicolumn{1}{l}{as BT (noised)} & 10.66 & 8.1 & 6.5 & 7.5 & 8.2 & 11.1 & 10.0 & 12.7 & 11.3 \\ \hline \end{tabular} \caption{Comparing standard decoding with decoding as if the input were back-translated data, meaning that it is tagged (for the TaggedBT model) or noised (for the NoisedBT model) . \label{tagged_decode}} \end{table*} \begin{table*}[ht] \small \centering \begin{tabular}{l|ll} Model & Decode type & Example \\ \hline\hline TaggedBT & \multicolumn{1}{l|}{standard} & Wie der Reverend Martin Luther King Jr. vor f{\" u}nfzig Jahren sagte: \\ & \multicolumn{1}{l|}{as-if-BT (tagged)} & Wie sagte der Reverend Martin Luther King jr. Vor f{\" u}nfzig Jahren: \\ NoisedBT & \multicolumn{1}{l|}{standard} & Wie der Reverend Martin Luther King Jr. vor f{\" u}nfzig Jahren sagte: \\ & \multicolumn{1}{l|}{as-if-BT (noised)} & Als Luther King Reverend \underline{\hspace{5mm}} Jr. vor f{\" u}nfzig Jahren:\\ \hline Source & & As the Reverend Martin Luther King Jr. said fifty years ago:\\ Reference & & Wie Pastor Martin Luther King Jr. vor f{\" u}nfzig Jahren sagte: \\ \end{tabular} \small \caption{Example decodes from newstest2015 for decoding in standard and ``as-if-BT" varieties. Here, NoisedBT and TaggedBT produce equivalent outputs with standard decoding; TaggedBT produces less natural output with tagged input; and NoisedBT produces a low-quality output with noised input. \label{decode_examples}} \end{table*} In this section we look at what happens when we decode with a model on newstest data as if it were back-translated. This means that for the TaggedBT model we tag the true source, and for the NoisedBT model, we noise the true source. These ``as-if-BT" decodings contrast with ``standard decode", or decoding with the true source. An example sentence from newstest2015 is shown in Table~\ref{decode_examples}, decoded by both models both in the standard fashion and in the ``as-if-BT" fashion. The \BLEU scores of each decoding method are presented in Table~ \ref{tagged_decode}. The noised decode -- decoding newstest sentences with the NoisedBT model after noising the source -- yields poor performance. This is unsurprising given the severity of the noise model used (recall Table~\ref{noise_example}). The tagged decode, however, yields only somewhat lower performance than the standard decode on the same model (-2.9\BLEU on average). There are no clear reasons for this quality drop -- the model correctly omits the tag in the outputs, but simply produces slightly lower quality hypotheses. The only noticeable difference in decoding outputs between the two systems is that the tagged decoding produces about double the quantity of English outputs (2.7\% vs. 1.2\%, over newstest2010-newstest2017, using a language ID classifier). That the tagged-decode \BLEU is still quite reasonable tells us that the model has not simply learned to ignore the source sentence when it encounters the input tag, suggesting that the $p(y|\textrm{BT}(x))$ signal is still useful to the model, as \newcite{sennrich2016improving} also demonstrated. The tag might then be functioning as a domain tag, causing the model to emulate the domain of the BT data -- including both the desirable target-side news domain and the MT biases inherent in BT data. To poke at the intuition that the quality drop comes in part from emulating the NMT biases in the synthetic training data, we probe a particular shortcoming of NMT: copy rate. We quantify the copy rate with the unigram overlap between source and target as a percentage of tokens in the target side, and compare those statistics to the bitext and the back-translated data (Table \ref{st_overlap}). We notice that the increase in unigram overlap with the tagged decode corresponds to the increased copy rate for the back-translated data (reaching the same value of 11\%), supporting the hypothesis that the tag helps the model separate the domain of the parallel versus the back-translated data. Under this lens, quality gains from TaggedBT/NoisedBT could be re-framed as transfer learning from a multi-task set-up, where one task is to translate simpler ``translationese" \cite{gellerstam1986translationese, freitag2019repair} source text, and the other is to translate true bitext. \begin{table}[ht] \small \centering \begin{tabular}{l|c} Data & src-tgt unigram overlap \\ \hline\hline TaggedBT (standard decode) & 8.9\% \\ TaggedBT (tagged decode) & 10.7\%\\ Bitext & 5.9\%\\ BT Data & 11.4 \%\\ \hline \end{tabular} \caption{Source-target overlap for both back-translated data with decoding newstest as if it were bitext or BT data. Model decodes are averaged over newstest2010-newstest2017. \label{st_overlap}} \end{table} \section{Negative Results} In addition to tagged back-translation, we tried several tagging-related experiments that did not work as well. We experimented with tagged forward-translation (TaggedFT), and found that the tag made no substantial difference, often lagging behind untagged forward-translation (FT) by a small margin ($\sim$ 0.2 \BLEU). For EnDe, (Tagged)FT underperformed the bitext baseline; for EnRo, (Tagged)FT performed about the same as BT. Combining BT and FT had additive effects, yielding results slightly higher than iteration-3 TaggedBT (Table \ref{enro}), at 33.9 \SacreBLEU on test; but tagging did not help in this set-up. We furthermore experimented with year-specific tags on the BT data, using a different tag for each of the ten years of newscrawl. The model trained on these data performed identically to the normal TaggedBT model. Using this model we replicated the ``as-if-bt" experiments from Table \ref{decode_examples} using year-specific tags, and although there was a slight correlation between year tag and that year's dataset, the standard-decode still resulted in the highest \BLEU. \section{Conclusion} In this work we develop TaggedBT, a novel technique for using back-translation in the context of NMT, which improves over the current state-of-the-art method of Noised Back-Translation, while also being simpler and more robust. We demonstrate that while Noised Back-Translation and standard Back-Translation are more or less effective depending on the task (low-resource, mid-resource, iterative BT), TaggedBT performs well on all tasks. On WMT16 EnRo, TaggedBT improves on vanilla BT by 0.4 \BLEU. Our best \BLEU score of 33.4 \BLEU, obtained using Iterative TaggedBT, shows a gain of +3.5 \BLEU over the highest previously published result on this test-set that we are aware of. We furthermore match or out-perform the highest published results we are aware of on WMT EnDe that use only back-translation, with higher or equal \BLEU on five of seven test sets. In addition, we conclude that noising in the context of back-translation acts merely as an indicator to the model that the source is back-translated, allowing the model to treat it as a different domain and separate the helpful signal from the harmful signal. We support this hypothesis with experimental results showing that heuristic noising techniques like those discussed here, although they produce text that may seem like a nigh unintelligible mangling to humans, have a relatively small impact on the cross-lingual signal. Our analysis of attention and tagged decoding provides further supporting evidence for these conclusions. \section{Future Work} A natural extension of this work is to investigate a more fine-grained application of tags to both natural and synthetic data, for both back-translation and forward-translation, using quality and domain tags as well as synth-data tags. Similarly, tagging could be investigated as an alternative to data selection, as in \newcite{dynamiccds,Axelrod2011}, or curriculum learning approaches like fine-tuning on in-domain data \cite{W18-6313,model_stacking, DBLP:journals/corr/FreitagA16}. Finally, the token-tagging method should be contrasted with more sophisticated versions of tagging, like concatenating a trainable domain embedding with all token embeddings, as in \newcite{kobus2016controlling}. \section{Acknowledgements} Thank you to Markus Freitag, Melvin Johnson and Wei Wang for advising and discussions about these ideas; thank you to Keith Stevens, Mia Chen, and Wei Wang for technical help and bug fixing; thank you to Sergey Edunov for a fast and thorough answer to our question about his paper; and of course to the various people who have given comments and suggestions throughout the process, including Bowen Liang, Naveen Arivazhagan, Macduff Hughes, and George Foster.
{'timestamp': '2019-06-18T02:03:47', 'yymm': '1906', 'arxiv_id': '1906.06442', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06442'}
arxiv
\section{Introduction} \label{intro} Additive manufacturing (AM) is widely considered to be a key technology for future advances in engineering. AM offers highest flexibility in part design while still achieving the mechanical properties required for functional parts~\cite{Gibson2015}. In metal powder bed fusion additive manufacturing (PBFAM) multiple layers of metal powder are successively molten at selected positions, which eventually form the cross-sections of the final part after solidification. Energy is commonly deposited by a laser or electron beam giving rise to the respective names selective laser melting (SLM) and electron beam melting (EBM). These processes come with very challenging thermophysical phenomena on multiple length and time scales \cite{Herzog2016}. Accordingly, existing modeling approaches can be classified with respect to the resolved length scales: Macroscale approaches commonly aim at determining spatial distributions of physical fields such as temperature, residual stresses or dimensional warping on the scale of the design part. Mesoscale approaches resolve the length scale of individual powder particles on domains smaller than one powder layer to either study the melt pool thermo-fluid dynamics during the melting process \cite{Khairallah2014,Korner2011,Wessels2018,Markl2015,Russell2018,Yan2018} or the cohesive powder flow during the previous powder recoating process \cite{Herbold2015,Meier2019,Meier2019a}. Last, microscale approaches predict the evolution of the metallurgical microstructure during solidification \cite{Zhang2013,Gong2015,Rai2016,Salsi2018,Lindgren2016}. A broad overview of state-of-the-art modeling approaches on these different length scales can be found in \cite{Meier2017}. The present article focuses on the development of a thermal macroscale model for metal PBFAM processes. Macroscale PBFAM models typically treat the powder phase as a homogenized continuum described via effective, i.e., spatially averaged, thermal and mechanical properties, without resolving individual powder particles. Also, the complex fluid dynamics within the melt pool are typically not explicitly resolved. Instead, a pure thermo-(solid-)mechanical problem is solved, usually based on a Lagrangean description and a spatial finite element discretization, with specific temperature- and phase-dependent thermal and mechanical constitutive parameters for the (homogenized) powder phase, the melt phase and the solidified phase. On the one hand, from a modeling point of view, such a procedure considerably simplifies the coupling of the different phase domains. On the other hand, this approach seems to be well-justified for certain simulations and quantities of interest since the mechanical forces transferred from powder and liquid phase onto the solid phase are often negligible in good approximation. In their works \cite{Gusarov2005,Gusarov2008,Gusarov2009}, Gusarov et al.\ proposed a model for powder bed laser absorption, which has been incorporated in many existing macroscale modelling approaches. For example, by using this absorption model, \cite{Hodge2014,Hodge2016} proposed a thermo-mechanical finite element (FE) model accounting for temperature- and phase-dependent thermal and mechanical constitutive behavior. Further developments in this field consider e.g. the accuracy of the physical model by adding additional physical effects such as residual stress relaxation \cite{Denlinger2015}, improved models for temperature and phase-dependent thermal conductivity of the powder \cite{Cervera1999,Childs2005} and melt \cite{Shen2012} phase, anisotropic conductivity \cite{Kollmannsberger2019}, phase-dependent laser absorptivity \cite{Roy2018}, thermodynamically consistent constitutive modelling based on phase energies \cite{Bartel2018}, or by explicitly modeling the melt pool fluid dynamics \cite{Jamshidinia2013}, an approach inspired by similar schemes in the context of laser and electron beam welding \cite{Chang2015,Geiger2009,Rai2009}. Another important aspect for macroscale PBFAM models is computational efficiency, which has been addressed, among others, by applying dynamic mesh adaptivity schemes \cite{Kollmannsberger2017,Riedlbauer2017,Denlinger2014,Zhang2018a}, code parallelization and load balancing techniques~\cite{Neiva2019} as well as process layer agglomeration approaches \cite{Zaeh2010,Hodge2016,Zhang2018a}. The present work addresses two important aspects of macroscale PBFAM models, namely the modeling of phase change and latent heat effects. Concerning the first aspect, we propose phase fraction variables which allow to formulate temperature- and phase-dependent material parameters in phase transition regions by consistent interpolation of the single phase parameters. While the definition of phase fraction variables is often somehow hidden in existing works, the present contribution defines these phase fraction variables in a transparent and systematic manner. Moreover, as basis of these phase fraction variables, different interpolation strategies, e.g. temperature-based or enthalpy-based interpolation, are discussed in detail. Concerning the modeling of latent heat effects, the two schemes that are most widely used in PBFAM models, namely the simple apparent (heat) capacity approach~\cite{Comini1974,DeMoraes2018,Morgan1978,Riedlbauer2017} and the more involved heat integration method~\cite{Rolph1982,Hodge2014,Oliveira2016}, will be investigated in the present work. It is known in the context of PBFAM process simulation that the specific choice of the latent heat model might considerably influence the overall efficiency of the numerical model~\cite{Hodge2014}. In the present work, the two aforementioned schemes, namely the apparent capacity approach and the heat integration method, are critically reviewed and compared with respect to numerical efficiency and overall accuracy. Eventually, a novel variant of the heat integration scheme is proposed that allows to directly control efficiency and accuracy by means of a user-defined tolerance. Depending on the chosen tolerance, it is shown that this novel approach offers increased numerical efficiency for a given level of accuracy or improved accuracy for a given level of numerical efficiency as compared to the apparent capacity and the original heat integration scheme. To isolate the effects of interest, the present study is restricted to purely thermal problems with length and time scales characteristic for PBFAM. This article is structured as follows: Section~\ref{sec:thermal_model} summarizes the mathematical problem statement and introduces the heat source modeling of a laser beam. The general numerical solution procedure is outlined in Section~\ref{sec:numerics}. Next in Section~\ref{sec:model_phase_latent} temperature-history dependent material parameters are interpolated on the basis of properly defined phase fraction variables that allow to distinguish powder, solid and melt phase. The treatment of latent heat associated with phase change problems is considered in detail with the two mentioned methods, namely the apparent capacity and the heat integration scheme, and eventually the novel tolerance-based variant of the heat integration scheme is proposed. Numerical experiments are presented in Section~\ref{sec:examples} with a focus on accuracy and efficiency of the considered methods. A short conclusion is provided in Section~\ref{sec:conclusion}. \section{General thermal model} \label{sec:thermal_model} For the purpose of this study it is sufficient to focus on the following instationary thermal problem described by the heat equation and appropriate boundary conditions: \begin{align} \begin{aligned} \label{eq:heat_equation} C(T)\,\dot{T}+\nabla\cdot \vec{q} &= \hat{r}, &&\ \text{in}\ \Omega,\\ T &= \hat{T}, &&\ \text{on}\ \Gamma_T, \\ \vec{q}\cdot\vec{n} &= \hat{q}, &&\ \text{on}\ \Gamma_{\vec{q}}. \end{aligned} \end{align} Temperatures $T$ are prescribed on the boundary part $\Gamma_T$ and heat fluxes on $\Gamma_{\vec{q}}$. The heat flux $\vec{q}$ is specified by Fourier's law for isotropic material, \begin{align} \vec{q} = -k(T)\ \nabla T. \end{align} Material properties, namely (volumetric) heat capacity $C$ and conductivity $k$, depend on temperature but also on phase. The modeling of these parameters and the introduction of the phase change problem are found in Section~\ref{sec:model_phase_latent}. The source term $\hat{r}$ is used to model the deposited energy, here achieved by a laser beam, as a volumetric heat source based on Gusarov et al.~\cite{Gusarov2009}. This model for the laser source term is derived by considering radiative and conductive properties of the powder material. A summary of the resulting model is given here without stepping through the rather involved derivations. Let a powder layer be distributed in the $xy$-plane, where the powder material extends in positive z-direction from the powder layer surface at $z=0$ up to the layer thickness $L$ at $z=L$ (see also Fig.~\ref{fig:single_track_scan_setup}) . A laser beam of nominal power $W$ and size $R$ is applied normal to this plane. The source term is then given in a local coordinate system relative to the laser beam center by \begin{align} \label{eq:mm_gusarov_laser_model} \hat{r}(r_h,z) = -\beta_h Q_0 \pfrac{q}{\xi'}, \end{align} where $r_h$ is the distance in the $xy$-plane from the laser beam center and $\beta_h$ is the extinction coefficient. The nominal power density $Q_0$ is radially distributed around the laser beam center as \begin{align} \label{eq:mm_gusarov_nominal_power_density_Q_0} Q_0 = \begin{cases} \frac{3W_e}{\pi R^2}\left(1-\frac{r_h}{R}\right)^2 \left(1+\frac{r_h}{R}\right)^2,\ &0 < r_h < R \\ 0, &\text{otherwise} \end{cases}. \end{align} The nominal laser power $W$ has been averaged and reduced to an effective power $W_e$ to account for various losses. Thus, \eqref{eq:mm_gusarov_nominal_power_density_Q_0} describes the spatial distribution in $x$- and $y$-direction. The normalized power density $q$ is given in terms of the dimensionless coordinate $\xi' = \beta_h z$ as \begin{align} \label{eq:mm_gusarov_normalized_density} q &= \frac{\rho_h a}{(4\rho_h-3)D}\nonumber\\ &\left\{e^{-\lambda}(1-\rho_h^2)\left[e^{-2a\xi'}(1-a) + e^{2a\xi'}(a + 1)\right]\right.\nonumber\\ &-\left[e^{2a(\lambda - \xi')}(1-a - \rho_h(a + 1))\right.\nonumber\\ &+\left.\left. e^{2a(\lambda - \xi')}(a + \rho_h(a - 1) + 1)\right](\rho_h e^{-2\lambda} + 3)\right\}\nonumber\\ &-\frac{3(1-\rho_h)(e^{-\xi'} - \rho_h e^{\xi'-2\lambda} )}{4\rho_h - 3}, \end{align} with hemispherical reflectivity $\rho_h$, constant $a=\sqrt{1-\rho_h}$, optical thickness $\lambda = \beta_h L$ and the constant \begin{align} D = &(1-a)\left[1-a-\rho_h(1+a)\right]e^{-2a\lambda}\nonumber\\ &-(1-a)\left[1+a-\rho_h(1-a)\right]e^{2a\lambda}. \end{align} Apart from the optical properties, Eq.~\eqref{eq:mm_gusarov_normalized_density} only depends on the $z$-coordinate and specifies the power distribution in normal direction. The local coordinate system moves with the laser beam along a defined scanning track with velocity $v$. \section{Numerical solution procedure} \label{sec:numerics} Governing equation \eqref{eq:heat_equation} is discretized in space with the finite element method (FEM). In the scope of the present work, linear shape functions are employed. Time is discretized with a one-step theta time integration scheme. Together this yields a fully discrete, nonlinear system of equations for the discrete temperatures $T_j^{n}$, where $j$ is the nodal index of the FEM discretization and $n$ the time step index. The equations are nonlinear due to the subsequently discussed temperature-dependence of heat capacity and conductivity as well as the yet to be introduced phase change subproblem. The discrete, nonlinear problem is linearized and solved iteratively with a consistent Newton-Raphson method. All simulations are performed in the in-house research code BACI~\cite{Wall2019}, a parallel, multi-physics finite element framework. \section{Modeling phase change and solidification} \label{sec:model_phase_latent} So far we have not addressed one crucial aspect of the specific thermal problem: the phase change, first from powder to liquid and eventually to solid phase. The general mathematical basis for phase change is briefly reviewed here. Suppose a domain contains both solid and liquid phase separated by the interface $\Gamma_m$ which is defined by temperature $T$ being at melting temperature $T = T_m$. At any point on the interface the so-called Stefan-Neumann equation has to hold: \begin{align} \label{eq:mm_stefan_neumann_equation} \underbrace{\vec{n}_{sl}\cdot\left(k_s\left.\pfrac{T}{\vec{x}}\right\vert_s-k_l\left.\pfrac{T}{\vec{x}}\right\vert_l\right)}_{\Delta q_m} = H_m\vec{n}_{sl}\cdot\vec{v}_{sl}\quad\text{on}\ \Gamma_m, \end{align} where $\vec{n}_{sl}$ is the interface normal vector, $H_m$ the latent heat of melting and subscripts $(\cdot)_s$ and $(\cdot)_l$ denote quantities evaluated in solid or liquid phase, respectively. The absorbed or released heat flux $\Delta q_m$ is proportional to the velocity $\vec{v}_{sl}$ of the evolving interface. Equation~\eqref{eq:mm_stefan_neumann_equation} makes it clear that the temperature gradients and heat fluxes are in general discontinuous at the phase interface. Equation \eqref{eq:mm_stefan_neumann_equation} takes the form of a free boundary condition. An alternative formulation is obtained by multiplying it with a differential surface element $\mathrm{d} \Gamma$, which yields \begin{align} \label{eq:mm_stefan_condition_volume} \Delta q_m\, \mathrm{d}\Gamma = H_m\frac{\mathrm{d} V}{\mathrm{d} t}. \end{align} Equation \eqref{eq:mm_stefan_condition_volume} states that the absorbed or released differential heat $\Delta q_m \mathrm{d}\Gamma$ is proportional to the volume change of either phase with a proportionality factor equal to the latent heat $H_m$. This formulation will prove to be useful since it is phrased in terms of volumes and not on the phase change interface. The introduced Stefan-Neumann equation is formulated for elementally pure materials where phase change takes place at a fixed melting temperature. The temperature of a point on the interface will change only after all latent heat has been absorbed or freed. We will refer to this as isothermal phase change. For alloys, phase change typically happens in a rather narrow temperature interval between solidus temperature $T_s$ and liquidus temperature $T_l$. In this case temperature gradually changes from $T_s$ to $T_l$, reaching liquidus (solidus) temperature when all latent heat has been absorbed (released). We will refer to this as mushy phase change. In this contribution the phase interface is implicitly defined by isotherms, a common choice in the context of PBFAM process simulation. Depending on the type of phase change (isothermal or mushy) one might take the isotherm at melting temperature or both isotherms at solidus and lquidus temperature to represent the phase interface. Other approaches include explicit interface tracking e.g.~with level set schemes and discrete solution spaces provided by enriched or extended finite element approaches. Instead of a sharp boundary the interface can also be tracked by means of an explicit phase variable that changes over an interface of finite thickness~\cite{Meier2017}. \subsection{Modeling effects of latent heat} \label{sec:latent_heat} Hu and Argyropoulos~\cite{Hu1996} review various methods to account for the latent heat $H_m$ associated with phase change. In the following sections two popular methods are briefly presented and then modified with the target application in mind. \subsubsection{Apparent capacity method} \label{sec:app_capa} One of the simplest approaches is the so-called \textit{apparent capacity} (AC) method. We will first introduce it for mushy phase change. The idea is to artificially increase the heat capacity $C$ in the melting region in such a way that an increased amount of energy is necessary in the model to heat the material. This increased energy shall be equal to the latent heat $H_m$. Expressed mathematically, this means \begin{align} \label{eq:mm_apparent_capacity} \int_{T_s}^{T_l} C_\text{app}\, \mathrm{d} T = \int_{T_s}^{T_l} C(T)\, \mathrm{d} T +H_m, \end{align} where $C_\text{app}$ is the modified capacity. The shape of the modified capacity function can in principle be chosen freely. A common choice is to set it to a constant in the phase change region with a jump discontinuity at solidus and liquidus temperature. In \cite{Comini1974} this approach is used in combination with an averaging technique. In this contribution a $C^1$-continuous smoothed triangular distribution as shown in Fig.~\ref{fig:mm_apparent_heat_capacity} is used for an improved Newton convergence. \begin{figure} \centering \includegraphics[width=.65\linewidth]{figures/apparent_capacity_schematic} \caption{Illustration of the apparent heat capacity method. The modified capacity $C^*$ includes the effects of latent heat $H_m$ in an integral sense.} \label{fig:mm_apparent_heat_capacity} \end{figure}% It is also possible to apply the AC method to isothermal phase change happening at melting temperature $T_m$. In this case artificial temperatures $T_s = T_m -d$ and $T_l = T_m -d$ are introduced, which gives a nonphysical phase change interval of width $2d$. The isothermal phase change will hence conceptually be modeled as mushy. If one is interested in an accurate representation of temperatures around the melting point, the width should be chosen small. However, in terms of an energy balance the same amount of latent heat $H_m$ will be absorbed or released after the respective phase change completes due to the definition in \eqref{eq:mm_apparent_capacity}. As simple as the AC method may be, it suffers from a major drawback. When temperature increments are too large in one time step, the solution temperature might only capture part of or even step over the increased capacity peak. Consequently, phase change is not considered correctly in the sense of an energy balance. \subsubsection{Heat integration method} \label{sec:heatint} Another popular and more advanced procedure is what Hu and Argyropoulos~\cite{Hu1996} call the \textit{heat integration} (HI) method. It has first been applied to a FE setting by Rolph and Bathe~\cite{Rolph1982} and is still used in more recent contributions \cite{Hodge2014,Oliveira2016}. In short, the method adds an additional source term to the discrete, linearized form of governing equation \eqref{eq:heat_equation} in each nonlinear iteration step. In the first iteration step the system is solved as usual. In each subsequent iteration $i$ an artificial source term ${q}_p^{i-1}$ determined from the previous iterate is added to the thermal residual. The Jacobian is not changed and thus the modified thermal residual is no longer consistently linearized. \paragraph{Original method} We will first introduce our understanding of the original HI method~\cite{Rolph1982} to calculate the source term. The specific notation was inspired by the formulation in~\cite{Oliveira2016}. Starting from the control volume formulation of the Stefan-Neumann equation \eqref{eq:mm_stefan_condition_volume}, an incremental source term $\Delta q_p^i$ is defined for iteration step $i$ along with the total latent heat available $q_{p,\text{tot}}$: \begin{align} \label{eq:mm_heatint_incr_source} \Delta q_p^{i} &= -\int\limits_{\Omega}\frac{1}{\Delta t} C\left(T^{i} - T_m\right)\,\mathrm{d}\Omega,\\ \label{eq:mm_heatint_tot_source} q_{p,\text{tot}} &= - \int\limits_{\Omega} \frac{1}{\Delta t} H_m\,\mathrm{d}\Omega, \end{align} where the index $()_p$, for phase change, distinguishes these quantities from heat fluxes. Originally, the negative sign corresponds to a melting problem although our algorithm can also handle solidification, as we will see later. The term \eqref{eq:mm_heatint_incr_source} can be interpreted as a penalty for stepping over the melting temperature $T_m$. The idea is to add these terms, which represent latent heat, until the current temperature $T^{i}$ stays at a consistent melting temperature $T_m$. Alternatively, when the sum of all increments ever applied reaches the allowed total in \eqref{eq:mm_heatint_tot_source}, no more increments are added and the temperature is allowed to deviate from the melting temperature again. For simplicity the terms are formulated for isothermal phase change. Compared to typical FE integrals, equations~\eqref{eq:mm_heatint_incr_source} and~\eqref{eq:mm_heatint_tot_source} are evaluated at nodes and not at element integration points. For this purpose, the nodal lumped pseudo-mass $\tilde{m}_j$ is defined for a node $j$ as \begin{align} \label{eq:mm_heatint_nodalmass} \tilde{m}_j = \sum\limits_k \int\limits_\Omega N_jN_k\, \mathrm{d}\Omega \end{align} with the FE shape functions $N_j$ and $N_k$. This looks very similar to a lumped mass matrix ubiquitous in FEM. Scaling \eqref{eq:mm_heatint_nodalmass} with a constant density $\rho$ would give a nodal mass (hence the naming pseudo-mass), scaling with $C$ gives a nodal capacity. The lumped pseudo-mass $\tilde{m}_j$ can be computed in the beginning of a simulation and is assumed constant throughout. The total latent heat available can now be computed in the beginning for each node~$j$ as \begin{align} \label{eq:heatint_total} {q}_{p,j,\text{tot}} = -\frac{1}{\Delta t}H_m \tilde{m}_j, \end{align} which is the lumped version of \eqref{eq:mm_heatint_tot_source}. Each node stores a history-variable $q_{p,j}^\text{hist}$ accumulating the amount of latent heat that has been absorbed over the whole simulation. It is initialized as zero for solid material. After each Newton iteration $i$ in time step $n+1$ the following calculations are performed: \begin{enumerate} \item Skip node $j$ if \begin{align} \label{eq:heat_int_skip_orig} &\left[T_{j,n+1}^i < T_s\ \text{and}\ T_{j,n} < T_s\right]\ \textbf{or}\nonumber\\ &\left[T_{j,n+1}^i > T_l\ \text{and}\ T_{j,n} > T_l\right] \end{align} which means it is not undergoing phase change. In this case the source term increment $\Delta q_{p,j}^{i}$ is set equal to zero. Here, $T_{j,n}$ denotes the converged temperature value of node $j$ at the last time step $n$. \item Else, for each node $j$ which is undergoing phase change compute the increment \begin{align} \label{eq:heat_int_increment} \Delta q_{p,j}^{i} = -\frac{1}{\Delta t}C^\ast\left(T_{j,n+1}^i -T^\ast\right)\tilde{m}_j, \end{align} which is the lumped version of \eqref{eq:mm_heatint_incr_source}. Here, $T^\ast$ is an intermediate temperature given by \begin{align} \label{eq:mm_heatint_intermediate_temp} T^\ast = T_s + \left\vert\frac{q_{p,j}^\text{hist}}{{q}_{p,j,\text{tot}}}\right\vert\, (T_l-T_s), \end{align} calculated from the amount of latent heat already absorbed (released) during melting (freezing). The modified capacity is computed as \begin{align} C^\ast = \left({\frac{T_l-T_s}{H_m} + \frac{2}{C_s+C_l}}\right)^{-1}, \end{align} where $C_s$ and $C_l$ are the values of heat capacity at $T_s$ and $T_l$, respectively. In case of isothermal phase change, the intermediate temperature simplifies to the melting temperature, i.e. $T^\ast = T_m = T_s = T_l$, and the modified capacity simplifies to the averaged capacity at the melting point, i.e. $C^\ast = \frac{1}{2}(C_s+C_l)$. \item Limit each increment $\Delta q_{p,j}^{i}$ such that the following condition is fulfilled: \begin{align} \label{eq:mm_heatint_limiting_cond} 0 \geq q_{p,j}^\text{hist} + \Delta q_{p,j}^{i} \geq {q}_{p,j,\text{tot}}. \end{align} The last increment (before phase change is completed) is limited such that the respective bound is exactly reached. Afterwards add it to the history $q_{p,j}^\text{hist} \leftarrow q_{p,j}^\text{hist}+\Delta q_{p,j}^{i}$. \item For each node $j$ where $\vert\Delta q_{p,j}^{i}\vert > 0$ reset the temperature \begin{align} \label{eq:mm_heatint_tempreset} T_{j,n+1}^i = T^\ast. \end{align} \item Calculate the total source term as the sum of all increments from previous iterations within this time step, \begin{align} \label{eq:mm_heatint_sourceterm} {q}_{p,j}^{i} = \sum\limits_{k=0}^i \Delta {r}_{p,j}^{k}, \end{align} where the first iteration in each time step starts with a vanishing source term, i.e. $q_{p,j}^0 = 0$. \end{enumerate} It is again emphasized that the history value $q_{p,j}^\text{hist}$ in~\eqref{eq:mm_heatint_limiting_cond} accumulates enthalpy increments $\Delta q_{p,j}^{i}$ over the whole simulation, i.e. over all nonlinear iteration steps in all time steps, while the source term in~\eqref{eq:mm_heatint_sourceterm} only accumulates the increments $\Delta q_{p,j}^{i}$ over all iterations of the current time step $n+1$. This method ensures that phase change is captured accurately: the thermal residual is modified and at the same time the temperature is fixed to a consistent value until all latent heat has been absorbed or released. Limiting condition \eqref{eq:mm_heatint_limiting_cond} allows to use the same algorithm for both melting and solidification as discussed at the end of this section. As noted by the authors of the original work~\cite{Rolph1982}, the HI method requires the consistent use of the nodal lumped capacity. Thus, when using this algorithm, the capacity matrix must enter the residual and Jacobian in Newton's method in lumped form to obtain a robust scheme. Nevertheless, the original HI method converges slowly due to the inconsistent modification of the residual. This was already noted by \cite{Hodge2014} and \cite{Hu1996}. As a remedy we propose a tolerance-based HI method in the following paragraph. \paragraph{Tolerance-based method} So far the number of iterations needed in the nonlinear solution procedure of one time step is only determined by the standard tolerance of Newton's method. We propose to introduce another tolerance to control the accuracy of the phase change representation. Hence, we stop adding increments when they are small compared to the total latent heat, i.e., \begin{align} \label{eq:mm_relative_increment} \left\vert\frac{ \Delta q_{p,j}^{i}}{{q}_{p,j,\text{tot}}}\right\vert < \varepsilon_\text{tol}. \end{align} where $\varepsilon_\text{tol}<1$ is a relative tolerance and describes the relative amount of latent heat which is not absorbed (released) after melting (solidification) is complete. Inserting \eqref{eq:heatint_total} and \eqref{eq:heat_int_increment} into \eqref{eq:mm_relative_increment} yields an alternative for step 1: \begin{itemize} \item [1.$^\ast$] Skip node $j$ if \begin{align} \label{eq:heatint_skip_tolerance} \vert T_{j,n+1}^i - T^\ast\vert < \varepsilon_\text{tol}\frac{ H_m}{ C^\ast}. \end{align} \end{itemize} The new criterion provides a way to stop HI when a certain accuracy is achieved. At first glance this seems to significantly change the outcome of the algorithm since \eqref{eq:heat_int_increment} will be evaluated for nodes that are far away from a phase change. However, the limiting condition \eqref{eq:mm_heatint_limiting_cond} will automatically neglect all nodes that are not undergoing phase change as demonstrated in the following. First, consider a node that is heated up and the material is undergoing a melting process. Initially, the node is in solid state, i.e. $q_{p,j}^\text{hist}=0$, with a temperature below the solidus temperature, i.e. $T_{j,n+1}^i < T_s$. The calculated increment \eqref{eq:heat_int_increment} would be positive. Since there is no phase change yet, no increment should be added. Indeed, limiting according to \eqref{eq:mm_heatint_limiting_cond} will not allow a positive increment with a zero history and the increment is set to zero. When the temperature rises above the solidus temperature $T_s$, however, the increments become negative and will be considered according to~\eqref{eq:mm_heatint_limiting_cond}. The history $q_{p,j}^\text{hist}$ accumulates negative increments until it reaches the allowed total $q_{p,j,\text{tot}}$, which by definition~\eqref{eq:heatint_total} is also negative. Then the material is fully molten. Next, the phase change is reversed by cooling a node with material in the molten state. If material is molten, then $q_{p,j}^\text{hist} = q_{p,j,\text{tot}} <0 $. Looking at the limiting condition~\eqref{eq:mm_heatint_limiting_cond} shows that only positive increments are allowed, when material is molten. As expected, positive increments~\eqref{eq:heat_int_increment} are obtained, and the solidification process is initiated, as soon as temperature drops below the liquidus temperature $T_l$. The positive increments are added to the history $q_{p,j}^\text{hist}$ until it reaches zero. Then the material has returned to a solid state. The phase change as it was just described is fully reversible. \subsection{Temperature- and phase-dependent parameters} \label{sec:temp_dep_params} As common in macroscale PBFAM models, all three phases are modeled as pseudo-solid materials with varying material parameters. On the one hand, this procedure considerably simplifies the numerical schemes for coupling the different phases. On the other hand, this approach is justified since the mechanical forces transferred from powder and liquid phase onto the solid phase are negligible in good approximation for many questions. It is important to note that the powder phase does not represent a phase in the same sense as solid, liquid and gaseous state: once powder is molten it becomes a consolidated phase and can never return to powder state. In the following we will expand on these considerations considering only mushy phase change for now. \label{sec:temp-phase-params} \begin{figure} \centering \includegraphics[width=.8\linewidth]{figures/phases} \caption{Temperature history diagram illustrating the two-dimensional nature of material parameter interpolation between powder (p), melt (m) and solid (s). Arrows indicate possible movement within the diagram.} \label{fig:mm_interpolation_phases} \end{figure} Fig.~\ref{fig:mm_interpolation_phases} gives an illustration of the possible states of a material point. The current temperature $T$ is on the ordinate, while the abscissa shows the highest temperature ever reached, $T_\text{max}$. The different areas correspond to different mixtures of powder, melt and solid. By definition there cannot be any possible state for $T>T_\text{max}$ and this area is blanked out. If $T_\text{max}<T_s$, all material must still be in powder form (p). If $T_\text{max}>T_l$, there is no more powder, all material is consolidated and thus must be solid~(s) or molten (m). The exact constitution of the two then depends on the current temperature. The same reasoning applies to the current temperature. If $T>T_l$, all material must be molten. If $T<T_s$, material is a mixture of powder and solid, where the exact constitution is depending on $T_\text{max}$. Perhaps the most interesting scenario is obtained when $T_s<T<T_\text{max}<T_l$. In this case some powder is still left and the consolidated phase is made up of melt and solid. The arrows in Fig.~\ref{fig:mm_interpolation_phases} indicate the possible evolution of phases. Due to the definition of $T_\text{max}$ the only way to increase its value is an irreversible movement along the black line in Fig.~\ref{fig:mm_interpolation_phases}. For all other locations in the diagram a reversible horizontal movement is possible. With these considerations a temperature-based interpolation procedure for any material parameter can be derived. \paragraph{Temperature-based interpolation} First, the focus is on the transition from (non-powder) solid to melt. The liquid fraction $g$ is introduced as \begin{align} \label{eq:mm_liquid_fraction} g(T) = \begin{cases} 0, & T < T_s\\ \frac{T-T_s}{T_l-T_s}, &T_s \leq T \leq T_l\\ 1, & T > T_l \end{cases} \end{align} If only solid and liquid phase were present, any material parameter $f$ could be interpolated from the solid and melt values $f_s$ and $f_m$. The history-dependent material behavior is captured by the fraction of consolidated material in time step $n+1$ according to \begin{align} \label{eq:mm_def_consolidated_fraction} r_c^{n+1} = \max\left[r_c^n,g(T)\right] \end{align} which is updated after each step and initialized with a proper start value $r_c^0$ (zero for powder, one for solid). For example, in a region that has initially been covered with powder, definition~\eqref{eq:mm_def_consolidated_fraction} equals the all-time maximum of the liquid fraction $g$ at this location which, according to~\eqref{eq:mm_liquid_fraction}, carries the same information as the maximum temperature $T_\text{max}$. In a region that has initially been covered with solid material, definition~\eqref{eq:mm_def_consolidated_fraction} equals one for all times since solid material can never transform back to powder. The monotonously increasing fraction of consolidated material $r_c^{n+1}$ together with the liquid fraction $g$ allow to define volume fractions for powder, melt and solid phases: \begin{align} \label{eq:mm_powder_fraction} r_p^{n+1} &= 1-r_c^{n+1},\\ \label{eq:mm_molten_fraction} r_m^{n+1} &= g,\\ \label{eq:mm_solid_fraction} r_s^{n+1} &= r_c^{n+1} - g. \end{align} Their physical motivation is as follows: The powder fraction $r_p^{n+1}$ given in \eqref{eq:mm_powder_fraction} is by definition the complement of the consolidated fraction $r_c^{n+1}$. The molten fraction $r_m^{n+1}$ in \eqref{eq:mm_molten_fraction} is independent of the history and is always determined by \eqref{eq:mm_liquid_fraction}. The solid fraction $r_s^{n+1}$ defined in \eqref{eq:mm_solid_fraction} is the part of the consolidated fraction which is not molten. This also implies that in a material mixture containing solid and powder the solid fraction always melts first. With more history variables, also a different behavior could be realized (e.g. powder should melt first) but this is not deemed necessary in the context of macroscale PBFAM. Note that definitions \eqref{eq:mm_powder_fraction}, \eqref{eq:mm_molten_fraction} and \eqref{eq:mm_solid_fraction} satisfy partition of unity and are thus suitable for interpolation. Any material parameter $f$ can now be interpolated from the single phase values ${f_p, f_m, f_s}$ weighted by the corresponding fractions \begin{align} \label{eq:mm_phase_interpolation} f(T) &= r_p^{n+1}(T)f_p + r_m^{n+1}(T)f_m + r_s^{n+1}(T)f_s. \end{align} For the special choice $f_p = f_s$, a two phase interpolation without history-dependent behavior is recovered. The dependence on temperature is explicitly stated in \eqref{eq:mm_phase_interpolation} since this requires a consistent linearization to achieve robust convergence of the nonlinear solver. Fig.~\ref{fig:interpolation_behavior} shows the evolution of an exemplary material parameter $f$ over the temperature history for the chosen liquid fraction definition \eqref{eq:mm_liquid_fraction}. In the left diagram powder melts completely and consequently the parameter $f$ takes on the value of a solid after cooling down below $T_s$. The right diagram shows partial melting: after cooling down below $T_s$ the parameter is a weighted average of the powder and solid value based on the consolidated fraction which is now smaller than 1. Fig.~\ref{fig:interpolation_3d} shows the same interpolation in a three-dimensional representation which makes the history-dependence on $T_\text{max}$ more explicit and shows that the parameter interpolation is also continuous over the history. This is important in the modeling of PBFAM processes since it ensures a continuous transition of material parameters between regions of molten and solidified material and regions that are still covered with unmolten powder. Note that the definition of liquid fraction determines the exact shape of the interpolating curve \eqref{eq:mm_phase_interpolation}. The kinks at $T_s$ and $T_l$ could also be smoothed out if this seemed necessary for robust Newton convergence. \begin{figure} \centering \includegraphics[width=\linewidth]{figures/interpolation_behavior} \caption{Evolution of a material parameter depending on temperature history. Left: Material is completely molten and consolidated. Right: Temperature history stays below liquidus temperature and thus a fraction of material stays powder.} \label{fig:interpolation_behavior} \end{figure} \begin{figure} \centering \includegraphics[width=.8\linewidth]{figures/interpolation_linear_3d} \caption{Three-dimensional visualization of parameter interpolation. Material parameters are continuous in $T$ and $T_\text{max}$ direction. The blue curve shows the evolution of the parameter when $T_\text{max}<T_s$.} \label{fig:interpolation_3d} \end{figure} \paragraph{Enthalpy-based interpolation} In the case of isothermal phase change, the definition of liquid fraction based on temperature as in~\eqref{eq:mm_liquid_fraction} will not work. A temperature-based parameter interpolation would still be possible based on a definition of solidus and liquidus temperature $T_s<T_m$ and $T_l>T_m$ as numerical regularization values rather than physically meaningful values. However, as a more consistent alternative approach the following formulation can be derived by rearranging~\eqref{eq:mm_heatint_intermediate_temp} to read \begin{align} \frac{T^\ast-T_s}{T_l-T_s} = \left\vert\frac{q_{p,j}^\text{hist}}{{q}_{p,j,\text{tot}}}\right\vert. \end{align} The fraction on the left-hand side is very similar to the liquid fraction~\eqref{eq:mm_liquid_fraction}. Thus, we may also interpret the right-hand side as a representation of the liquid fraction $g_j$ of node $j$, i.e. \begin{align} \label{eq:mm_heatint_enthaply_liquid_fraction} g_j = \left\vert\frac{q_{p,j}^\text{hist}}{{q}_{p,j,\text{tot}}}\right\vert, \end{align} which is guaranteed to be bounded between $[0,1]$ due to the limiting condition~\eqref{eq:mm_heatint_limiting_cond}. The liquid fraction in \eqref{eq:mm_heatint_enthaply_liquid_fraction} is no longer formulated in temperatures but rather in latent heat. For an isothermal phase change, a change in latent heat directly corresponds to a change in enthalpy. Thus, the new fraction \eqref{eq:mm_heatint_enthaply_liquid_fraction} can also be thought of as an enthalpy-dependent liquid fraction. All other parts of the interpolation procedure \eqref{eq:mm_phase_interpolation} remain unchanged. In the numerical examples, this liquid fraction based on latent heat will be employed in combination with the isothermal HI scheme. All schemes employing a finite phase change interval $[T_s;T_l]$, will use the temperature-based parameter interpolation with liquid fraction \eqref{eq:mm_liquid_fraction}. \section{Numerical results} \label{sec:examples} \subsection{Solidification front in a 1D slab} \label{sec:results_solidifcation_front} To validate the implementation, first a series of numerical experiments are conducted on a one dimensional domain for which an analytic solution is available~\cite{Hu1996}. This example has already been used to show the validity of methods for capturing latent heat~\cite{Comini1974}. A pseudo one-dimensional slab (material properties of ice / water) with length $L=\unit[1]{m}$ is subject to a fixed temperature $\hat{T}=\unit[253]{K}$ on its left edge at $x=0$. The initial temperature in the whole slab is $T_0=\unit[283]{K}$. The left part of Fig.~\ref{fig:geometry_solidification_melting} illustrates this scenario. The interface separating frozen and liquid water will slowly travel from left to right. Material parameters for water are given in Table~\ref{tab:mm_semi-inf_slab_params}, they are taken directly from \cite{Comini1974}. The problem is discretized with 25, 50 or 100 linear finite elements in space and three different fixed step sizes $\Delta t \in \{\unit[200]{s},\unit[400]{s},\unit[800]{s}\}$ in time. Total simulation time is $t_f = \unit[72\cdot 10^3]{s}$. At this point in time the temperature on the right edge is still at the initial level and the analytic solution (which is calculated on a semi-infinite domain) remains valid. \begin{table} \centering \caption{Material parameters of water \cite{Comini1974} for Sections~\ref{sec:results_solidifcation_front} and~\ref{sec:results_melting_vol}.} \label{tab:mm_semi-inf_slab_params} \begin{tabular}{llll} \hline\noalign{\smallskip} Parameter & Description & Value & Unit\\ \noalign{\smallskip}\hline\noalign{\smallskip} $T_m$ & Phase change temperature & 273 & K\\ $H_m$ & Volumetric latent heat & 338 & \unitfrac{MJ}{m$^3$}\\ $C_s$ & Volumetric specific heat, solid & 1.762 & \unitfrac{MJ}{m$^3$K}\\ $C_l$ & Volumetric specific heat, liquid & 4.226 & \unitfrac{MJ}{m$^3$K}\\ $k_s$ & Thermal conductivity, solid & 2.22 & \unitfrac{W}{mK}\\ $k_l$ & Thermal conductivity, liquid & 0.556 & \unitfrac{W}{mK}\\ \noalign{\smallskip}\hline \end{tabular} \end{table} \begin{figure} \centering \includegraphics[width=\linewidth]{geometry_melting_vol} \caption{Geometry, thermal loads, boundary and initial conditions for solidification front example (left) and melting volume example (right).} \label{fig:geometry_solidification_melting} \end{figure} \begin{figure} \centering \includegraphics[width=\linewidth]{figures/analytical_compare} \caption{Melting front example: Temperature profiles at $t_f$ of analytic solution compared to numerical results with AC and HI method. 100 elements, $\Delta t = \unit[200]{s}$.} \label{fig:compare_heatintegration_apparentcapa} \end{figure} \begin{figure*} \centering \includegraphics[width=.8\textwidth]{figures/maxerr_discretization} \caption{Melting front example: Maximum error in temperature $\left\Vert\frac{T-T_\text{ref}}{T_0-\hat{T}}\right\Vert_\infty$ of different methods for latent heat depending on spatial and temporal discretization.} \label{fig:compare_maxerr_discretization} \end{figure*} \begin{figure*} \centering \includegraphics[width=0.8\textwidth]{figures/iterations_discretization} \caption{Melting front example: Average number of nonlinear iterations of different methods for latent heat depending on spatial and temporal discretization.} \label{fig:compare_iterations_discretization} \end{figure*} The introduced HI method will be used in four variants by distinguishing a) isothermal and mushy phase change as well as b) the original criterion~\eqref{eq:heat_int_skip_orig} and the novel tolerance-based criterion~\eqref{eq:heatint_skip_tolerance}. In this example, phase change of water is isothermal and thus the isothermal HI methods with either original or tolerance-based criterion can be applied directly. For the AC method an artificial phase change interval is chosen with $T_s=\unit[270]{K}$ and $T_l=\unit[276]{K}$, i.e., $d=\unit[3]{K}$. The same interval is used to apply the original and tolerance-based mushy HI methods. Additionally, for tolerance-based HI the tolerance is chosen as $\varepsilon_\text{tol}=0.001$, i.e., up to 0.1\% of latent heat will be neglected. All approaches yield results that agree very well with the analytic solution. Fig.~\ref{fig:compare_heatintegration_apparentcapa} shows the solutions obtained with AC and original isothermal HI method on the finest mesh as an example. The maximum errors in the numerical solutions provided by the different methods are shown for the three investigated meshes and time step sizes in Fig.~\ref{fig:compare_maxerr_discretization}. The maximum errors lie below 4\% for the coarsest mesh and around 2\% for the finer meshes, which is deemed accurate enough for the intended use case. Within the considered scope, the time step size seems to have only minor effect on the accuracy. All versions of HI schemes produce errors that are slightly higher compared to the error from the AC scheme. However, for the large time step sizes $\Delta t = \unit[400]{s}$ and $\Delta t = \unit[800]{s}$ the AC method does not always converge. The real difference between the methods comes to light when numerical efficiency is investigated in terms of Newton iterations needed per time step. Fig.~\ref{fig:compare_iterations_discretization} shows a strong dependence of the original HI method~\cite{Rolph1982} on the spatial discretization with heavily increased iterations per time step in case of finer spatial resolution. On top of that a larger time step leads to a further increase in iterations. Both isothermal and mushy version of the original method suffer from this effect. Hodge et al.~\cite{Hodge2014} mention that small time steps had to be used because of the original HI method. However, our proposed tolerance-based method does not only require significantly less iterations per step in every scenario but is also less sensitive to spatial and temporal discretization. This seems beneficial when moving to simulation of PBFAM processes on a part-scale. \subsection{Melting volume in a 1D slab} \begin{figure*} \centering \includegraphics[width=\textwidth]{figures/meltvol_temp_ele100_dt200} \caption{Melting volume example: Temperature profiles at $t_f$ obtained with five different methods for latent heat. 100 elements, $\Delta t = \unit[200]{s}$.} \label{fig:meltvol_temp_ele100_dt200} \end{figure*} \begin{figure} \centering \includegraphics[width=\linewidth]{figures/meltvol_heatint_rb_tol} \caption{Melting volume example: Temperature profiles at $0.5\,{t_f}$ obtained from the original and the proposed tolerance-based HI scheme (100 elements, time step varying).} \label{fig:meltvol_heatint_rb_tol} \end{figure} \begin{figure} \centering \includegraphics[width=.9\linewidth]{figures/meltvol_heatint_tol_var} \caption{Melting volume example: Temperature profiles at $0.5\,{t_f}$ obtained from the proposed tolerance-based HI scheme for different tolerances (100 elements, $\Delta t=\unit[200]{s}$).} \label{fig:meltvol_heatint_tol_var} \end{figure} \begin{figure*} \centering \includegraphics[width=0.8\textwidth]{figures/iterations_discretization_meltvol} \caption{Melting volume example: Average number of nonlinear iterations of all investigated methods for latent heat depending on spatial and temporal discretization.} \label{fig:compare_iterations_discretization_meltvol} \end{figure*} \begin{figure*} \centering \includegraphics[width=0.8\textwidth]{figures/iterations_discretization_meltvol_reduced} \caption{Melting volume example: Average number of nonlinear iterations of best performing methods for latent heat depending on spatial and temporal discretization.} \label{fig:compare_iterations_discretization_meltvol_reduced} \end{figure*} \begin{figure*} \centering \includegraphics[width=0.8\textwidth]{figures/meltvol_appcapa_width_temp} \caption{Melting volume example: Temperature profiles at $t_f$ obtained with AC methods for three time step sizes and with different phase change interval widths $d$. 100 elements.} \label{fig:meltvol_appcapa_width_temp} \end{figure*} \label{sec:results_melting_vol} To get a better understanding of problem-dependency, we investigate the same variants on a slightly modified second example (Fig.~\ref{fig:geometry_solidification_melting}, right). The Dirichlet condition on the left boundary is dropped and all faces are assumed to be insulating. Instead a spatially varying source term $\hat{r} = 20,000(1-x)\unitfrac{W}{m^3}$ is applied to the whole slab of water which is initially frozen at $T_0=\unit[263]{K}$. Material parameters for solid and liquid water are again given in Tab.~\ref{tab:mm_semi-inf_slab_params}. In contrast to the previous example, melting will not take place at a single node representing the phase interface. Instead a whole volume can be in phase transition (i.e. melting). The same spatial and temporal discretizations from before are used, total simulation time is $t_f = \unit[20\cdot 10^3]{s}$. Again, the AC method and the four variants of HI are applied with the settings from above. No analytic solution is available for this scenario. Fig.~\ref{fig:meltvol_temp_ele100_dt200} shows the obtained temperature profiles along the one dimensional slab for the fine discretization with 100 elements and a step size of $\unit[200]{s}$. Obviously, AC and mushy HI methods will not keep temperatures fixed at the melting temperature of \unit[273]{K} during phase change. When one is concerned about exact representation of isothermal phase change, only the original and tolerance-based version of isothermal HI are accurate enough, although some oscillation around the melting temperature is observed. Looking at the final temperatures on the left edge, when melting is already finished, reveals that the latent heat of melting still is captured with good accuracy by all methods, and the predicted temperatures agree well. Given the large temperature range prevalent in the targeted application (PBFAM simulation on part-scale), a highly accurate representation of temperature profiles around the melting point is not of highest practical importance. A short look on the accuracy of isothermal HI schemes is taken in this paragraph. Solutions with the HI scheme can become quite inaccurate around the melting temperature especially when larger time steps are used. Fig.~\ref{fig:meltvol_heatint_rb_tol} shows such solutions of the original scheme at $t=0.5t_f$ for different step sizes and compares it to our proposed tolerance-based method. Both methods cannot exactly enforce isothermal phase change which would be characterized by a horizontal plateau region at $T_m$. The original method's criterion \eqref{eq:heat_int_skip_orig} for determining nodes undergoing phase change proves to be ill-suited for this scenario. Larger time steps lead to larger undershoots in temperature. The fluctuations around melting temperature obtained with the proposed tolerance-based HI scheme on the contrary are independent of step size and only controlled by the tolerance $\varepsilon_\text{tol}$. The temperature profiles resulting from three different tolerances (0.01, 0.001 and 0.0001) can be seen in Fig.~\ref{fig:meltvol_heatint_tol_var}. Next we turn to the efficiency of all methods and examine the average number of Newton iterations per time step shown in Fig.~\ref{fig:compare_iterations_discretization_meltvol}. Again, the original variants of the HI scheme need the most Newton iterations and are especially sensitive to temporal and spatial discretization. They are no longer considered in the remaining examinations. Fig.~\ref{fig:compare_iterations_discretization_meltvol_reduced} only compares iterations of the AC and tolerance-based HI methods. The iteration count increases with increasing time step size for all three methods but stays more or less constant over all spatial discretizations. In the rightmost graph showing the largest time step, the AC for the first time requires more iterations than the proposed tolerance-based HI methods. This melting volume example reveals an already mentioned problem of AC methods, namely the possibility to neglect much of latent heat by stepping over or passing through the phase change interval too fast. The AC method is used with three widths $d\in\{\unit[1]{K},\unit[2]{K},\unit[3]{K}\}$ to compute artificial solidus and liquidus temperatures $T_s = T_m -d$ and $T_l=T_m+d$. The final temperature profiles are graphed in Fig.~\ref{fig:meltvol_appcapa_width_temp} for three time step sizes and the finest mesh with 100 finite elements. Obviously, the profiles differ in the respective phase change intervals which would not be the main concern in PBFAM. Instead focus lies on the maximum temperature predicted on the left edge. For the smallest time step $\Delta t = \unit[200]{s}$ all widths reach almost the same maximum temperature. Increasing the step size leads to larger discrepancies in the maximum temperature. A smaller width $d$ correlates with higher maximum temperatures which in turn implies that not all latent heat has been absorbed. \paragraph{Summary of preliminary simulations:} Taking into account all experience gathered from the two numerical examples, the authors recommend the use of the proposed tolerance-based HI method or an AC method. We found that the new criterion \eqref{eq:heatint_skip_tolerance} to determine nodes that undergo phase change is superior to the one originally introduced by \cite{Rolph1982}. This is due to two reasons: first, the accuracy is user-controllable by setting a respective tolerance. Second, the new stopping criterion~\eqref{eq:heatint_skip_tolerance} typically leads to a significant reduction of nonlinear Newton iterations except for scenarios with very strict tolerances, which are, however, not expected to be necessary in the targeted application PBFAM. Naturally, it is hard to predict a-priori which method will lead to less Newton iterations since this depends on the specific problem, tolerances and the (artificial) phase change interval width. Therefore, in the following, an actual example in the context of PBFAM will be investigated. \subsection{Single track scan} The following example simulates the scanning of a single track in a PBFAM process and was introduced in \cite{Gusarov2009} and has also been simulated elsewhere, see \cite{Hodge2014}. A schematic sketch of the setup is shown in Fig.~\ref{fig:single_track_scan_setup}. A volumetric heat source described by Eq.~\eqref{eq:mm_gusarov_laser_model} with effective power $W=\unit[30]{W}$ and size $R=\unit[0.06]{mm}$ is applied to the powder domain. The geometry consists of a cuboid of $0.6\times 0.2\times 0.2\, \unit{mm^3}$. The top layer of \unit[0.05]{mm} in $z$-direction is in powder form and rests on top of a solid substrate domain. The material is a 316L type steel with parameters summarized in Tab.~\ref{tab:hodge_params}. The whole domain is initialized at a fixed temperature $T_0=\unit[303]{K}$. All surfaces are insulating, only $x=\unit[0.6]{mm}$ has an essential boundary condition $\hat{T}=T_0=\unit[303]{K}$. The laser beam center moves from an initial position at $x=-\unit[0.06]{mm}$ (one laser beam radius outside the domain) with a scanning speed of $v=\unitfrac[120]{mm}{s}$ in $x$-direction along the symmetry plane $y=0$. The powder layer is discretized by a regular hexahedral mesh with element size $h_0= \unit[0.0025]{mm}$, i.e. $n_\text{ele}^z=20$ elements across the powder layer height. In the substrate domain, a mesh with double element height in $z$-direction is applied. Moreover, an adaptive time stepping scheme is applied that halves the time step size if no convergence is achieved by the employed Newton-Raphson scheme (within a prescribed maximal number of iterations), and that doubles the step size again after four convergent time steps on the smaller step size level. As initial step size a value of $\Delta t^{(0)} = \unit[1]{\mu s}$ has been chosen, which has been verified to yield a sufficiently small time discretization error. \begin{table} \centering \caption{Material parameters for single track scan example \cite{Hodge2014}.} \label{tab:hodge_params} \begin{tabular}{llll} \toprule Parameter & Description & Value & Unit\\ \midrule $\rho_h$ & Hemispherical reflectivity & 0.7 & -\\ $\beta_h$ & Extinction coefficient & 60 &mm$^{-1}$\\ $C_p$ & Heat capacity, powder & 2.98 & \unitfrac{MJ}{m$^3$K}\\ $C_s$ & Heat capacity, solid & 4.25 & \unitfrac{MJ}{m$^3$K}\\ $C_m$ & Heat capacity, melt & 5.95 & \unitfrac{MJ}{m$^3$K}\\ $k_p(T)$ & Conductivity, powder & 0.2@200,&\\& & 0.3@1600 & \unitfrac{W}{mK}@K\\ $k_c$ & Conductivity, solid/melt & 20 & \unitfrac{W}{mK}\\ $T_m$ & Melting temperature & 1700 & K\\ $H_m$ & Latent heat of fusion & 2.18 & \unitfrac{GJ}{m$^3$}\\ \bottomrule \end{tabular} \end{table} \begin{figure} \centering \includegraphics[width=\linewidth]{figures/hodge_schematic} \caption{Geometry and moving laser heat source for single track scan example ~\cite{Hodge2014}}. \label{fig:single_track_scan_setup} \end{figure} \begin{figure*} \centering \includegraphics[width=\linewidth]{meltpools_120.pdf} \caption{Surface temperature profile and melt pool shape in steady-state. From left to right: current results from HI and AC scheme as well as reference results from Gusarov et al.~\cite{Gusarov2009} and Hodge et al.~\cite{Hodge2014}.} \label{fig:results_hodge_BACI_meltpool} \end{figure*} \begin{table} \centering \caption{Comparison of maximum temperature and melt pool dimensions resulting from the different latent heat models.} \label{tab:results_comparison_meltpool} \begin{tabular}{lllll} \toprule Quantity & \cite{Gusarov2009} & \cite{Hodge2014} & AC & HI\\ \midrule Max. temp. [K] & 4900 & 5000 & 4990 & 4980\\ Length [mm] & 0.30 & 0.27 & 0.28 & 0.29\\ Width [mm] & 0.20 & 0.21 & 0.20 & 0.21\\ Depth [mm] & 0.07 & 0.07 & 0.07 & 0.07\\ \bottomrule \end{tabular} \end{table} \begin{figure*} \centering \includegraphics[width=\textwidth]{figures/hodge_xcut_front} \caption{Surface temperature profiles for AC and HI along laser path (i.e. $y=\unit[0.0]{mm}$) for different spatial discretizations: Zoomed in to melting front of melt pool.} \label{fig:results_xcut_front} \end{figure*} \begin{figure*} \centering \includegraphics[width=\textwidth]{figures/hodge_xcut_back} \caption{Surface temperature profiles for AC and HI along laser path (i.e. $y=\unit[0.0]{mm}$) for different spatial discretizations. Zoomed in to solidification region in melt pool tail.} \label{fig:results_xcut_back} \end{figure*} \begin{figure*} \centering \includegraphics[width=\textwidth]{figures/hodge_ycut_melt} \caption{Surface temperature profiles for AC and HI transverse to laser path at $x=\unit[0.4]{mm}$ showing transition from melt pool to powder.} \label{fig:results_ycut_melt} \end{figure*} \begin{figure*} \centering \includegraphics[width=\textwidth]{figures/hodge_ycut_solid} \caption{Surface temperature profiles for AC and HI transverse to laser path at $x=\unit[0.2]{mm}$ showing transition from solid to powder.} \label{fig:results_ycut_solid} \end{figure*} In prior simulations of this example, latent heat effects have been taken into account via an enthalpy method \cite{Gusarov2009} and an isothermal HI method \cite{Hodge2014}. Here, we will use an AC method and subsequently the newly proposed tolerance-based isothermal HI scheme to simulate the process. An artificial melting interval is introduced for the AC method. As a baseline we chose $T_s = \unit[1600]{K}$ and $T_l = \unit[1800]{K}$, i.e., $d=\unit[100]{K}$. Isothermal HI is applied with a tolerance of $\varepsilon_\text{tol}=0.001$. The isothermal HI scheme is used in combination with enthalpy-based parameter interpolation, while the AC method is used with temperature-based interpolation. In a first step, qualitative characteristics of the solution shall be discussed. After a short period of time the melt pool shape reaches a steady-state. Its geometry can be visualized by the isotherm $T=T_m$. Fig.~\ref{fig:results_hodge_BACI_meltpool} compares the results obtained with the AC and tolerance-based HI method to the results reported in~\cite{Gusarov2009} and~\cite{Hodge2014}. Both the AC and HI solution show good agreement with the reference. The melt pool dimensions and peak temperatures are compared quantitatively to the reference solutions in Tab.~\ref{tab:results_comparison_meltpool}. All compared quantities show good agreement. Since no more quantitative data is provided by the reference papers, we compare AC and HI method with each other. In the preliminary examples in Section~\ref{sec:results_solidifcation_front} and \ref{sec:results_melting_vol} a strong dependency on spatial discretization was recognized. Three additional, coarser spatial discretizations with elements of size $2h_0$, $4h_0$ and $\frac{20}{3}h_0$ (which results in $n_\text{ele}^z \in \{10,5,3\}$ elements over the powder layer height) are introduced to investigate this phenomenon for the single track scan. The accuracy of both methods can be judged by looking at characteristic temperature profiles in the steady-state. All results presented in the following are shown for (approximately) $t=\unit[4.6]{\mu s}$, which is the same point in time for which the melt pool shape has been illustrated in Fig.~\ref{fig:results_hodge_BACI_meltpool}. First, Fig.~\ref{fig:results_xcut_front} shows the surface temperature profiles for all discretizations plotted along the laser path (i.e. $y=0$) in the vicinity of the melting front. This front is characterized by high temperature gradients and rates. With increasing element size, larger nonphysical oscillations in the temperature profile are observed for the AC scheme. These oscillations can be traced back to the limitation of the employed first-order finite elements in representing strong gradients and material nonlinearities, here mainly caused by the extreme gradients of the thermal conductivity across the phase interface. No such oscillations occur with the HI scheme, which enforces the temperature in the phase transition region to lie within a temperature interval (implicitly) prescribed through the tolerance $\varepsilon_\text{tol}$. Although the shape functions used with the HI scheme are still first-order, the reset of temperature to a consistent melt temperature as described in \eqref{eq:mm_heatint_tempreset} seems to prohibit temperature oscillations in the phase interface region as observed for AC, even though the HI scheme performs phase change and parameter interpolation within a considerably smaller temperature interval. It is important to note that so far the oscillations have not been observed to cause stability issues (e.g. a significant energy increase in the discrete system) and they remain small compared to the overall temperature range. A second phase change happens along the laser path (i.e. $y=\unit[0.0]{mm}$) when material cools down again at the tail of the melt pool. Fig.~\ref{fig:results_xcut_back} gives a detailed view of the temperature profile in this region. The HI method produces a kink in the temperature profile at $T_m$, which is to be expected for a phase interface. The AC method produces a mushy phase change region and no kink is observed. However, further away both temperature profiles are in good agreement again. Another aspect to investigate is the resulting temperature profile transverse to the laser scanning direction. Change from melt to powder can be investigated with a cut in $y$-direction at $x=\unit[0.4]{mm}$ as shown in Fig.~\ref{fig:results_ycut_melt}. Again oscillations appear in the AC solution for coarser meshes but not in the HI solution. A similar picture emerges for a cut in $y$-direction through solid and powder, e.g. at $x=\unit[0.2]{mm}$ as illustrated in Fig.~\ref{fig:results_ycut_solid}. In both transverse cuts temperature profiles differ for AC and HI method in proximity to $T_m$ and agree well in some distance to the phase interface. As suspected, in PBFAM applications the chosen method for latent heat only has a very local influence on the resulting temperature field, but does not significantly affect the global temperature characteristics from a rather macroscopic point of view. Another aspect of importance for PBFAM process simulations is numerical efficiency, here assessed in terms of nonlinear solver performance. Fig.~\ref{fig:results_hodge_totaliter} depicts the total number of Newton iterations accumulated over the whole simulation time for the different spatial discretizations. The results of the preliminary numerical examples in the previous sections seem to transfer to a larger example: the HI method shows a strong dependency on the spatial resolution, but in the practically relevant range of discretizations (e.g. 3 elements across the powder layer thickness), the difference becomes negligible. In a next step, it shall be investigated how the accuracy and numerical efficiency of the two considered phase change schemes can be influenced by the respective numerical parameters $d$ (phase change interval of the AC scheme) and $\varepsilon$ (tolerance of the HI scheme). In a first step, the phase change interval for the AC method is varied for the two coarsest spatial discretizations to see how it affects the temperature oscillation. It has to be noted that this also changes the temperature interval for temperature-based parameter interpolation. The intervals are given by $T_s = T_m - d$ and $T_l = T_m +d$, where $d \in \{100,250,500\} \unit{[K]}$. Moreover, two additional versions of HI with relaxed tolerances of $\varepsilon_\text{tol}=0.01$ and $\varepsilon_\text{tol}=0.1$ are simulated. The resulting surface temperatures are plotted in Fig.~\ref{fig:hodge_xcut_front_appcapa_d}, \ref{fig:hodge_ycut_melt_appcapa_d} and \ref{fig:hodge_ycut_solid_appcapa_d} in the regions that showed oscillations in the previous plots. While the increased phase change interval for the AC decreases the amplitude of these oscillations by a certain amount, the overall accuracy of the temperature profiles decreases as well. Thus, it has to be concluded that for a given spatial discretization the width $d$ of the phase change interval is not a suitable parameter to control the accuracy of AC schemes. The solutions obtained with different tolerances for the HI method show no oscillation. The solution from HI with tolerance $\varepsilon_\text{tol}=0.01$ is indistinguishable from the one with stricter tolerance $\varepsilon_\text{tol}=0.001$. The solution from HI with tolerance $\varepsilon_\text{tol}=0.1$ deviates slightly from the ones with stricter tolerances in the solid-powder transition region, see Fig.~\ref{fig:hodge_ycut_solid_appcapa_d}. However, it still seems to be considerably more accurate than the solution from AC with $d=\unit[500]{K}$. Finally, the initial time step size $\Delta t^0$ for the three considered HI and AC variants is increased up to 64 times of the original value. The total number of Newton iterations that is now required is depicted in~Fig.~\ref{fig:hodge_timeadapt_iterations}. It is emphasized that the time step halving scheme is still employed. It was optimized individually for each method to yield low iteration counts. Moreover, it has been checked that the time discretization error is still sufficiently small, i.e. there is no visible difference in the results for base time step sizes up to 16 times $\Delta t^0$ for all variants. Higher step sizes lead to visible albeit small deviations in the temperature profiles, which are smaller, however, than the deviations resulting from the different HI and AC variants. According to~Fig.~\ref{fig:hodge_timeadapt_iterations}, an increased phase change interval $d$ in AC allows for larger step sizes and thus less iterations. Especially on the coarsest mesh, HI with a high tolerance ($\varepsilon=0.1$) yields a comparable number of accumulated Newton iterations, but at a considerably increased accuracy, as compared to the AC method with the (unphysically) large phase change interval $d=\unit[500]{K}$. All in all, for a given spatial discretization, the proposed HI scheme allows to directly control numerical efficiency and accuracy by means of a user-defined tolerance. Within the considered scope of numerical examples and practically relevant spatial and temporal discretizations, this property made the novel tolerance-based HI scheme preferable as compared to the original HI scheme and the investigated AC method. \begin{figure} \centering \includegraphics[width=.8\linewidth]{figures/hodge_totaliter} \caption{Numerical efficiency of AC and HI in terms of total Newton iterations required.} \label{fig:results_hodge_totaliter} \end{figure} \begin{figure} \centering \includegraphics[width=\linewidth]{figures/hodge_xcut_front_appcapa_d} \caption{Surface temperature profiles for AC with different phase change intervals along laser path (i.e. $y=\unit[0.0]{mm}$): Zoomed in to melting front.} \label{fig:hodge_xcut_front_appcapa_d} \end{figure} \begin{figure} \centering \includegraphics[width=\linewidth]{figures/hodge_ycut_melt_appcapa_d} \caption{Surface temperature profiles for AC with different phase change intervals transverse to laser path at $x=\unit[0.4]{mm}$ showing transition from melt pool to powder.} \label{fig:hodge_ycut_melt_appcapa_d} \end{figure} \begin{figure} \centering \includegraphics[width=\linewidth]{figures/hodge_ycut_solid_appcapa_d} \caption{Surface temperature profiles for AC with different phase change intervals transverse to laser path at $x=\unit[0.2]{mm}$ showing transition from solid to powder.} \label{fig:hodge_ycut_solid_appcapa_d} \end{figure} \begin{figure} \centering \includegraphics[width=\linewidth]{figures/hodge_timeadapt_iterations} \caption{Total number of Newton iterations required for different initial time step sizes $\Delta t^0$ in the time step halving scheme.} \label{fig:hodge_timeadapt_iterations} \end{figure} \section{Conclusion} \label{sec:conclusion} In this work, an extension of phase change and latent heat models for the simulation of metal powder bed fusion additive manufacturing processes on the macroscale has been proposed and different models have been compared with respect to accuracy and numerical efficiency. In this context, a systematic formulation of phase fraction variables has been proposed relying either on temperature- or enthalpy-based interpolation schemes. Moreover, latent heat has been considered either by means of an apparent capacity (AC) or heat integration (HI) method. For the latter, a novel phase change criterion has been proposed, which combines superior accuracy and numerical efficiency (in terms of an improved nonlinear solver performance allowing for larger time step sizes and fewer iterations per time step) as compared to the original HI scheme. Compared to the AC approach, the numerical efficiency of the proposed tolerance-based HI scheme is comparable while offering an increased level of accuracy. Numerical results from the literature have been reproduced, which shows the validity of the proposed scheme. In summary, both the AC and the proposed tolerance-based HI scheme perform well when considering the accuracy requirements as well as practically relevant spatial and temporal discretization resolutions for PBFAM process simulation. Still, the authors believe that the new tolerance-based HI method is advantageous over AC schemes due to the user-controllable tolerance, which allows to directly control numerical efficiency and accuracy of the scheme, and which can directly be interpreted as the error in latent heat made during a phase change process. For part-scale PBFAM models thermo-mechanical interaction is one of the primary interests. Structural parameters such as Young's modulus or the thermal expansion coefficient may depend upon the temperature history in a similar fashion as proposed in the current work for the thermal parameters. Future research work will focus on the question of how the proposed methods for latent heat and parameter interpolation will behave in the thermo-mechanically coupled scenario. \bibliographystyle{spmpsci}
{'timestamp': '2019-07-24T02:12:37', 'yymm': '1906', 'arxiv_id': '1906.06238', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06238'}
arxiv
\section{Introduction} Recent studies have uncovered systematic biases in a variety of computer vision systems. For example, an analysis of commercial gender classification systems demonstrated disparities with respect to perceived gender and skin type, with darker-skinned females exhibiting the highest error rates \cite{gendershades, Raji2019}. An analysis of state-of-the-art object detection systems found decreased pedestrian detection accuracy on darker skin tones \cite{Wilson2019}. Gender-based bias has also been observed in image captioning \cite{10.1007/978-3-030-01219-9_47} and image classification \cite{Zhao2017}. In light of this research, there is a growing need for methods that facilitate auditing and explaining undesirable skews/stereotypes in computer vision models. We propose a novel framework for identifying biases of a face attribute classifier. Specifically, we consider a classifier trained to predict the presence or absence of a smile on a face image. However, our approach generalizes to a broad range of face-centric classification problems. Our method, which we refer to as \textit{counterfactual face attribute manipulation}, tests how the prediction of a trained classifier would change if a characteristic of the face were different. For example, this approach allows us to ask "Would the smiling prediction change if this person's hair had been longer?" Our method leverages recent advances in generative models and post-hoc interepretability to facilitate an ethics-informed audit exploring normative constraints on what \textit{should} be independent of the smiling attribute. First, we build a directed generative model of faces that maps latent codes, sampled from a fixed prior distribution, to images. Next, we infer direction in latent code space that correspond to manipulations of a particular image attribute in pixel space. We refer to these vectors as \textit{attribute vectors}. Traversing these directions in latent space provides a straightforward method of generating images that smoothly vary one characteristic of a face, while preserving others. We propose several metrics that measure the sensitivity of a trained classifier to manipulations imposed by attribute vectors. We test our method on a classifier trained to predict the smiling attribute from faces in the CelebA dataset \cite{celeba} and find our approach reveals several biases in the smiling classifier. \section{Ethical Considerations}\label{secc:ethical} \textbf{Intended use and limitations:} The techniques proposed in this paper can be applied to detect and analyze unintended and undesirable bias in a wide variety of face-centric computer vision systems. While this type of analysis is an important part of designing fair and inclusive technology, it is not sufficient. Rather, it must be part of a larger, socially contextualized project to critically assess ethical concerns relating to facial analysis technology. In this work, we focus our attention on smiling detection because we believe it has a range of beneficial applications and limited harmful applications, from aiding in the selection of images from a stream of images to augmented reality applications where a smile triggers added features. On the other hand, there are many facial analysis systems that do have harmful applications where foreseeable risk outweighs foreseeable benefit, e.g., where the facial analysis task itself has the potential to perpetuate, reinforce and amplify societal injustices, regardless of how balanced the classification performance is with respect to different demographics. For example, face recognition and gender classification technology represent two facial analysis domains with a great potential for abuse, with the highest risks often falling on already marginalized populations \cite{Keyes2018, annon, msrfacerec}. \textbf{CelebA attributes:} We utilize CelebA attribute annotations to infer directions in latent space that correspond to different factors of variation in the face images. All of the attributes within the dataset are operationalized as binary categories (i.e. the attribute is present or it is absent). We note that in many cases this binary scheme does not reflect the full diversity of real attributes and so the interpretation of category boundaries is contingent on the annotators and annotation scheme. The inherent subjectivity in the attribute annotations means that the factors of variation we manipulate in our experiments are tied to the ways the attributes have been operationalized and annotated within the CelebA dataset. After careful consideration, we have chosen not to manipulate images based on the \texttt{Male} attribute. While this attribute may, on the surface, appear relevant to fairness evaluations, the risk and potential for negative impact outweighs the perceived benefit of examining this attribute in particular. First, the CelebA annotation scheme conceptualizes the \texttt{Male} attribute as both binary and perceptually obvious and discernible. Using a gender\footnote{We note that it is unclear if the CelebA \texttt{Male} annotations are meant to reflect gender or sex (neither of which are binary). Since the annotations are based on face images, we assume the dataset curators were attempting to measure gender.} binary in reporting results implicitly condones the classification of gender into two distinct and opposite categories, which perpetuates harm against individuals who exist outside the bounds of this categorization scheme and reinforces rigid social norms of gender expression. Second, due to the Hollywood skew of the dataset, a very narrow range of gender expression is reflected in the images. Consequently, applying our methodology to the \texttt{Male} attribute would result in manipulations that alter a specific set of correlated image features that, through a largely cisnormative and heteronormative cultural lens, are commonly interpreted as gender signifiers. Even with a nuanced discussion of what the \texttt{Male} attribute vector is (and is not) encoding, presenting these results risks reinforcing and implicitly condoning the views that individuals of different genders \textit{do} and \textit{should} present a certain way. Generally speaking, we recommend researchers avoid attempts to manipulate images based on unstable social constructs like gender. Instead, we suggest limiting manipulations to attributes defined by (mostly) objective facial characteristics. \begin{figure}[t!] \centering \includegraphics[width=\linewidth]{example_smaller.pdf} \caption{Counterfactual attribute sensitivity measures the effect of manipulating a specific property of an image on the output of a trained classifier. In this example, we consider the effect of adding facial hair on the output of a smiling classifier. If the classifier's output systematically changes as a result of adding or removing facial hair then a potentially undesirable bias has been detected since, all else being equal, facial hair should be irrelevant to the classification task. } \end{figure} \label{fig:example} \section{Related work} Several works have focused on evaluating fairness of human-centric vision classifiers. \cite{gendershades, Raji2019} compare error statistics of facial analysis systems across groups defined by Fitzpatrick skin type \cite{Fitzpatrick} and gender. \cite{Mitchell2019ModelCF} propose standardized model reporting guidelines that include evaluations disaggregated by groups defined along cultural, demographic, and phenotypic lines. Our work is complementary to disaggregated evaluations based on real images, while incorporating recent work in post-hoc interpretability for understanding biases. Specifically, the generative techniques we propose allow new types of evaluation not easily afforded by real image datasets: (i) We can assess how a prediction might change if characteristics of an image \textit{that we believe should be irrelevant to classification} are altered in a specific targeted manner. This means we can identify a causal relationship between features in an image and the classifier's output; (ii) Our approach facilitates testing on faces with combinations of characteristics that may be underrepresented in the testing set. There has been significant research effort devoted to developing post-hoc approaches for interpreting and explaining neural networks (e.g. see \cite{Gilpin2018} for a review). The most common framework involves computing saliency maps to visualize the importance of individual pixels to a classifier's prediction. Gradient-based saliency approaches \cite{Simonyan2013DeepIC, Sundararajan2017, Selvaraju} attribute importance based on first-order derivatives of the input. Another set of approaches determine importance based on perturbing individual or groups of pixels and observing the change in classifier output \cite{Chang2018ExplainingIC,Fong2017InterpretableEO, Dabkowski2017RealTI}. The perturbation methods relate to our approach in that counterfactual-style inputs drive the search for regions that most affect the classifiers output. Our method is different in that, instead of searching over perturbations that maximally influence the classifiers output, we perturb the input along known and meaningful factors of variation to test the classifiers response. Testing with Concept Activation Vectors (TCAV) \cite{tcav} is an alternative interpretability framework that poses explanations at the level of high level concepts rather than pixels. TCAV defines a concept via a set of data instances (e.g., images) sharing a common characteristic. Similarly, our method infers attribute vectors based on two sets of images: (i) images with the attribute and (ii) images without the attribute. TCAV uses directional derivatives to reveal the `conceptual sensitivity' of a model's prediction of a class (e.g \texttt{Smiling}) to a concept by the two sets of images). Our approach extends this technique to measure the effect of an attribute vector \textit{directly on the model predictions}. TCAV provides a general framework for model interpretability, and our approach narrows in on cases where generative techniques produce high quality and perceptually realistic images. In the settings where our method is applicable, it provides direct and actionable information about a model's decisions. We believe the two approaches are complementary and can work in combination: TCAV can point to a potential bias, and our method can provide clear interpretable evidence of bias in classifier predictions. Our method is related to \cite{Kilbertus2017, Kusner2017}, who propose the notion of counterfactual fairness in the context of causal modeling. Here, the fairness of a model is determined by assessing the effect of counterfactual interventions on a sensitive attribute (e.g., race or gender) over a causal graph. Recently, \cite{Kohler-Hausmann, moss2019} have argued this framework is based on a misunderstanding of how race operates in our society and the flawed assumption that social groups like race and gender are entities that can have counterfactual causality. Crucially, our approach manipulates observable characteristics of a face, rather than conceptualizing the manipulation at the level of social groups. Of course, some of these attributes (e.g.,~presence of a beard) may be strongly correlated with a particular social group (e.g.~gender identities), but they neither constitute nor are determined by the group. \cite{Sahaj2019} consider counterfactual fairness in text classification. They propose both evaluation and training techniques based on counterfactual manipulation of terms referencing different identify groups in sentences. Our work can be understood as the image analog, with one key difference: rather than manually perturbing the input data, we utilize a generative model to manipulate face characteristics in the images. Our approach is most similar to \cite{Rodden}, which explores how the output of a gender classifier changes in response to the alteration of various characteristics of the same person (e.g.,~hair length, facial expression, etc.). Our approach differs in that we use generative techniques to systematically vary characteristics of a face image, rather than relying on a manually curated set of real images. \section{Methods} We now outline our \textit{counterfactual face attribute manipulation} framework, which is motivated by questions of the form: how would the prediction change if a single factor of variation in the image were altered? \subsection{Generative model} Generative adversarial networks (GANs) \cite{gans} are a framework for learning generative models whereby two networks are trained simultaneously in an adversarial manner. The generator $G$ takes as input a latent code vector $z \in \mathcal{Z}$ sampled from a fixed prior $p(z)$ and outputs an image $x \in \mathcal{X}$. The discriminator $D$ takes as input an image $x \in \mathcal{X}$ that is sampled from either the training set or the generative distribution defined by $G$. $D$ is trained to discriminate between images from these two distributions while $G$ is trained simultaneously to generate samples that fool $D$ into thinking they come from the data distribution. In this work, we utilize the architecture and progressive training procedure introduced in \cite{pggan} and train with the Wasserstein GAN loss \cite{wgan} with a gradient penalty \cite{Gulrajani2017}: \begin{equation} \begin{aligned} \min_G \max_D &\mathbb{E}_{x \sim p(x)} [D(x)] - \mathbb{E}_{z \sim p(z)} [D(G(z))] \\ & + \lambda \mathbb{E}_{x \sim p_I(x)}[(||\nabla_x D(x) ||_2-1)^2] \end{aligned} \end{equation} Here, $p(x)$ is the data distribution, $p(z)$ is the prior noise distribution and $p_I(x)$ is given by sampling uniformly along lines between points in the true and generative distributions. The basic GAN framework lacks an inference mechanism, i.e., a method of identifying the latent code $z$ that generated a particular image $x$. Inference is central to our method since we use annotated data to estimate directions in latent space that correspond to different factors of variation in the dataset. In order to obtain an approximate inference mechanism we train an encoder $E$ to map from images to latent codes. Specifically, for a fixed generative model, we train the encoder with an $\ell_2$ loss to predict the latent code $z$ that generated $x = G(z)$: \begin{align} \min_E \mathbb{E}_{z \sim p(z)} ||z - E(G(z))||_2 \end{align} \begin{figure}[t!] \centering \includegraphics[width=\linewidth]{linear_classifier.pdf} \caption{Attribute vectors are computed by training a linear classifier to discriminate between latent codes corresponding to images with and without a given attribute $a$. The attribute vector $d_a$ is taken to be the vector orthogonal to the decision boundary, normalized to have unit $\ell_2$ norm.} \end{figure} \label{fig:classifier} \begin{figure}[b!] \centering \begin{subfigure}[b]{0.9\linewidth} \includegraphics[width=\linewidth]{young_images.pdf} \caption{} \end{subfigure}\label{fig:young} \hspace{2mm} \begin{subfigure}[b]{0.9\linewidth} \includegraphics[width=\linewidth]{makeup_images.pdf} \caption{} \end{subfigure} \caption{Traversing in latent code space along the (a) \texttt{Young} and (b) \texttt{Heavy\_Makeup} attribute direction. The center row shows images generated from random $z \sim p(z)$. Rows moving down (up) show images generated by traversing the \texttt{Young}/\texttt{Heavy\_Makeup} attribute vector in a positive (negative) direction. We see age/makeup related facial characteristics being smoothly altered while the overall facial expression remains constant.} \label{fig:makeup_young_ex} \end{figure} \subsection{Face attribute vectors}\label{secc:attributes} Inspired by \cite{tcav}, we compute attribute vectors by training a linear classifier to separate the latent codes inferred from images annotated with the attribute from latent codes inferred from images annotated without the attribute. We take the attribute vector $d_a$ to be the vector orthogonal to the linear classifier's decision boundary. We normalize all attribute vectors to have unit $\ell_2$ norm. In our formulation, we examine the effect of a range of CelebA attributes (e.g. \texttt{Young}, \texttt{Heavy\_Makeup}, \texttt{No\_Beard}, etc.) on \texttt{Smiling} predictions. Since the \texttt{Smiling} attribute is highly correlated with several other attributes in CelebA (see \fig{celeba_attribute_correlation} in the Appendix for the full attribute correlation matrix), we ensure the \texttt{Smiling} attribute is equally represented in both the positive and negative classes of the other attributes we model to avoid inadvertently encoding it in the attribute vector. We also balance the \texttt{Male} attribute in an attempt to disentangle the set of attributes highly correlated with it. A face attribute vector $d_a$ can be traversed, positively or negatively, to generate images that smoothly vary along the factor of variation defined by the attribute. For example, given an image $x = G(z)$, we can synthesize new images that differ along the factor of variation defined by $d_a$ via $G(z + i*d_a)$. We consider $i \in [-1, 1]$ and note that as $i$ increases above 0, the attribute will be present in increasing amounts. Similarly, as $i$ decreases below 0, the attribute will be removed. Despite being operationalized as binary within the CelebA dataset, the vast majority of characteristics captured by the annotations are continuous. Thus, this continuous traversal of attribute vectors gives rise to perceptually meaningful alterations in the images. For example, \fig{makeup_young_ex}(a) demonstrates images synthesized by perturbing $z's$ along the $d_{\texttt{Young}}$ direction. We emphasize again that many of the annotations are subjective, and thus, these manipulations reflect how the particular attributes were operationalized and annotated within the CelebA dataset. \subsection{Measuring sensitivity to counterfactual face attribute manipulation}\label{secc:measure} We now describe our method of testing classifier sensitivity to counterfactual face attribute manipulation. Let $f$ denote a trained classifier that takes an image $x \in \mathcal{X}$ as input and outputs a continuous value representing the probability of a smile being present in the image: \begin{align} f(x) = P(Smile = 1 | x) \in [0, 1] \end{align} Given a threshold, $0 \leq c \leq 1$, binary classifications are obtained: \begin{align} y(x) = \mathbb{I}[P(Smile = 1 | x) \geq c] \in \{0, 1\} \end{align} We are interested in how both $f(x)$ and $y(x)$ are affected as the input $x$ changes in a controlled manner. We measure the sensitivity of the \textit{continuous valued output} of $f$ to image manipulations by attribute vector $d$ as: \begin{align} S_f(d) = \mathbb{E}_{z\sim p(z)} [f(G(z + d)) - f(G(z))] \end{align} In other words, $S_f(d)$ compares the classifiers output given an image $G(z)$ with the classifiers output given the image manipulated by an attribute vector $G(z+d)$. By comparing images generated from the same $z$, this metric isolates the effect of altering a specific set of characteristics (defined by attribute vector $d$) on the classifier's output. $S_f(d)$ will be close to 0 if the classifier is blind to the change resulting from attribute vector $d$. In contrast, a $S_f(d)$ of large magnitude indicates $f$ is sensitive to attribute $d$. If $d$ influences something relevant to the classification task (e.g., mouth shape in the context of smiling classification) a non-zero $S_f(d)$ is expected. However, if $d$ encodes characteristics that we believe should be irrelevant to classification (e.g., hair color in the context of smiling classification) then a large $|S_f(d)|$ indicates a potentially undesirable bias in the classifier. We define a function to indicate if the classifier's binary prediction changes as a result of manipulating an image with attribute vector $d$: \begin{align} I(z, d) = \mathbb{I}[y(G(z + d)) != y(G(z)) ] \end{align} Whereas $S_f(d)$ captures the change in probabilities predicted by the classifier, we now define two metrics that capture the frequency with which manipulating images with attribute vector $d$ changes the binary classification. We break this down into classifications that flip from `not smiling' to `smiling': \begin{align} S_y^{0 \rightarrow 1}(d) = \mathbb{E}_{z\sim p(z) | y(G(z)) == 0} I(z, d) \end{align} and classifications that flip from `smiling' to `not smiling': \begin{align}S_y^{1 \rightarrow 0}(d) = \mathbb{E}_{z\sim p(z)| y(G(z)) == 1} I(z, d) \end{align} \section{Results} CelebA \cite{celeba} is a dataset of celebrity faces annotated with the presence/absence of 40 face attributes. We train a convolutional neural network to predict the \texttt{Smiling} attribute on 128x128 images. We train with a cross-entropy objective and use a threshold of $c = 0.5$ for final predictions. Error statistics, disaggregated by a select set of attributes, are given in \tab{celeba} in the Appendix. We train a progressive GAN on 128x128 CelebA images with a 128-dimensional zero-mean Gaussian prior. For each attribute in the CelebA dataset, we estimate the directions in latent code space corresponding to these factors of variation via the procedure described in \secc{attributes}. We infer 800 latent codes for each of the positive (attribute is present) and negative (attribute is not present) classes. We select a random 80\% of the vectors for training and evaluate classification accuracy on the remaining 20\%. The classification accuracy of each linear classifier is shown in \fig{class_acc} in the Appendix. To illustrate the visual effect of the generative face attribute manipulation, \fig{makeup_young_ex} shows samples generated from the model by traversing the latent code space along the $d_{\texttt{Heavy\_Makeup}}$ and $d_{\texttt{Young}}$ directions respectively. We see age/makeup related facial characteristics being smoothly altered while the overall facial expression remains constant. Many of the CelebA attributes are highly correlated in the dataset (see \fig{celeba_attribute_correlation} in the Appendix for the full correlation matrix). The GAN learns to separate some factors (as evidenced, for example, by the consistent facial expressions in \fig{makeup_young_ex}), but does not cleanly disentangle all factors of variation in human faces. For example, there are many facial attributes that, through the societal production of the gender binary, have come to signify traditionally masculine or feminine characteristics. Social norms around gender expression lead these features to be highly correlated in society and the CelebA dataset reflects, if not amplifies, these correlations. Empirically, we observe these attributes remain entangled to differing degrees in the generative model. Consequently, traversing one attribute vector (e.g.~\texttt{Heavy\_Makeup}) sometimes changes a larger set of facial characteristics (e.g.~removing/adding a beard, altering hair length, etc.) that tend to be correlated with the attribute in question. Future work is aimed at further disentangling factors of variation that are highly correlated in the dataset. \begin{figure}[t!] \centering \includegraphics[width=\linewidth]{sf_nomale.pdf} \caption{Effect of traversing different attribute vectors on the continuous output of the smiling classifier. For each attribute, the y-axis denotes $i$ equally space within $[-1, 1]$, i.e. the degree to which the attribute has been added ($i > 0$) or removed ($i < 0$) in the image.} \label{fig:psmile_change} \end{figure} Our approach involves traversing directions in latent code space to generate images that vary smoothly along some factor of variation. We performed a simple sanity check to ensure that images generated from nearby latent codes are consistently classified by the smiling classifier. First, we construct a large set of generated images that are classified as smiling. Then we generate new images by sampling latent codes uniformly from lines connecting two different codes of the generated images. We find that 98\% of the new images are also classified as smiling. We similarly test this for images classified as not smiling and find the same results. Next, we assess the sensitivity of the smiling classifier to the counterfactual face attribute manipulation, using the measures proposed in \secc{measure}. Recall, we can use attribute vector $d_a$ to manipulate attribute $a$ in an image. For example, given image $x = G(z)$, we can lighten hair color by generating $$G(z + i*d_{\texttt{Blond\_Hair}}), i \in (0, 1].$$ Conversely, generating $$G(z + i*d_{\texttt{Blond\_Hair}}), i \in [-1, 0)$$ will darken hair color in the image. \fig{psmile_change} plots the sensitivity $S_f(i*d_a)$ for all attributes $a$ in the CelebA dataset and for $i \in [-1, 1]$. Interestingly, we observe that linear changes to $z$ result in linear changes in the output of the classifier. Next, we consider the actual change in classification that results from perturbing images in direction $d_a$. \fig{class_flips} in the Appendix plots these results for a large set of CelebA attributes. Blue bars plot $S_y^{1 \rightarrow 0}$, i.e., the frequency with which images originally classified as smiling are subsequently classified as not smiling after manipulating images with the attribute vector. Red bars indicate $S_y^{0 \rightarrow 1}$, i.e., the frequency with which images originally classified as not smiling are subsequently classified as smiling after manipulating images with the attribute vector. The left hand side of the plot indicates the effect of negatively shifting along $d_a$, i.e. $S_y(-d_a)$ and the right hand side indicates the effect of positively shifting along $d_a$, i.e. $S_y(d_a)$. Note that whereas \fig{psmile_change} plots classifier sensitivity for incremental shifts along $d_a$, here we plot the effects of a unit step in either the positive or negative direction. There are several attributes in the CelebA dataset that one might consider from a fairness perspective. We summarize these results in \tab{flips}. For example, the \texttt{Young} attribute captures something related to age. Again, we emphasize that the attribute vector $d_{\texttt{Young}}$ reflects how the young attribute was operationalized and measured within the CelebA dataset. Category boundaries of $\texttt{Young}=1$ and $\texttt{Young}=0$ are contingent on the annotators and the distribution of faces that fall into each category in dataset might not accurately represent faces of different ages in the real world. That said, our results indicate the smiling classifier is sensitive to the \texttt{Young} direction, with $7\%$ of images changing from a smiling to not smiling classification as a result of manipulating the images in this direction. In contrast, only $2.6\%$ of images flip from a not smiling to smiling classification. \begin{table}[t!] \small \centering \begin{tabular}{l|c|c} CelebA attribute defining $d_a$ & $S_y^{1 \rightarrow 0}(d_a)$ & $S_y^{0 \rightarrow 1}(d_a)$ \\ \hline \hline \texttt{Young} & \textbf{7.0\%} & 2.6\% \\ \texttt{5\_o\_Clock\_Shadow} & \textbf{11.8\%} & 2.2\% \\ \texttt{Goatee} & \textbf{12.4\%} & 0.9\% \\ \texttt{No\_Beard} & 0.8\% & \textbf{11.8\%} \\ \texttt{Heavy\_Makeup} & 1.6\% & \textbf{12.4\%} \\ \texttt{Wearing\_Lipstick} & 1.7\% & \textbf{16.3\%}\\ \end{tabular} \caption{Effect of manipulating images with CelebA attribute vectors on smiling classifier's predictions. Vectors for \texttt{Young}, \texttt{5\_o\_Clock\_Shadow}, and \texttt{Goatee} flip the classifier from `smiling' to `not smiling', while vectors for \texttt{No\_Beard}, \texttt{Heavy\_Makeup}, and \texttt{Wearing\_Lipstick} flip from 'not smiling' to 'smiling'}\label{tab:flips} \end{table} \begin{figure*}[t!] \centering \includegraphics[width=\textwidth]{young_flip.pdf} \includegraphics[width=\textwidth]{blond_flip.pdf} \includegraphics[width=\textwidth]{5_o_clock_flip.pdf} \includegraphics[width=\textwidth]{makeup_flip.pdf} \includegraphics[width=\textwidth]{cheekbones_flip.pdf} \caption{Examples where smiling classifier's prediction flips when traversing different attribute vectors. Green (red) boxes indicate a smiling (not smiling) prediction. } \label{fig:img_flips} \end{figure*} A fair smiling classifier should also perform consistently regardless of the gender or gender expression of the individual in the photo. The CelebA \texttt{Male} attribute captures something related to these concepts. However, as discussed in \secc{ethical}, we chose not to use the \texttt{Male} annotations. We emphasize that image manipulations based on the \texttt{Male} attribute would not alter anything inherent to gender identity or gender expression. Rather, these manipulations would simply reflect a specific set of correlated features that occur in different proportions in the images annotated $\texttt{Male}=0$ and $\texttt{Male}=1$. \tab{flips} highlights the effect of more objective attributes, such as facial hair and makeup on smiling classification. We observe that adding facial hair flips classifications from smiling to not smiling. In contrast, adding makeup flips classifications from to smiling to smiling. Both \fig{psmile_change} and \fig{class_flips} suggest the smiling classifier is sensitive to different attributes. We now turn to visual inspection to (i) assess the perceptual effect of traversing the attribute vectors and (ii) ensure the basic mouth/facial expression that signifies the presence/absence of a smile does not change when traversing the attribute vectors. \fig{img_flips} shows several examples of images generated by traversing different attribute vectors. Green or red boxes outline each image to indicate the smiling classifier's prediction for the image. Red boxes indicate a not smiling prediction and green boxes indicate a smiling prediction. We observe the basic facial expression remains constant when traversing many of the attribute vectors (e.g., \texttt{Young}, \texttt{Blond\_Hair}, \texttt{5\_o\_Clock\_Shadow}, \texttt{Heavy\_Makeup}), despite other characteristics of the face changing. This indicates the generative model has sufficiently disentangled the factor of variation defined by the CelebA attribute from the features of a smile. However, despite the faces (perceptually) having nearly identical mouth expressions, the classifier is nonetheless sensitive to the changes. Visual inspection also identifies some attribute vectors that have encoded something about the mouth shape. For example, we observe that the mouth/facial expression changes significantly when traversing the \texttt{High\_Cheekbones} attribute vector. Subsequently, manipulating faces according to the \texttt{High\_Cheekbones} attribute vector does not convey anything meaningful about the classifier's bias. \section{Conclusion} We have proposed a technique that leverages the power of generative models to evaluate and reveal biases in a face attribute classifier. This work represents the first step of a larger research agenda focused on auditing algorithms and post-hoc interpretability and is introduced here as a proof-of-concept. We now highlight several future research directions: \begin{itemize} \item Leverage human raters to further understand potential bias embedded in the attribute vectors. This is important to help distinguish the classifier bias from potential bias in the generator / attribute annotations. \item Leveraging the same generative techniques to visualize dataset bias. \item Training the generative model on a larger and more diverse set of faces than is available for the classifier. \end{itemize} {\small \bibliographystyle{ieee_fullname}
{'timestamp': '2019-06-20T02:01:26', 'yymm': '1906', 'arxiv_id': '1906.06439', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06439'}
arxiv
\subsection{Dynamic instrumentation} \label{sec:instrumentation} \input{sections/architecture/instrumentation} \subsection{Profiling and Partitions} \label{sec:profiling} \input{sections/architecture/profiling} \subsection{Offloading Functionality} \label{sec:offloading} \input{sections/architecture/offloading} \subsection{Network Subsystem} \label{sec:network} \input{sections/architecture/network} \input{sections/evaluation} \input{sections/deployment} \input{sections/discussion} \bibliographystyle{abbrvnat} \subsubsection{Basic Control Strategies} The network subsystem abstracts the communication between mobile devices and the executing backend. It can be deployed on ISP's RANs where the latency to the User Equipment (UE) is minimal (15-45ms~\cite{laner_comparison_2012}). Offloading requests share a common end-point IP, which can be intercepted directly at the base station~\cite{mec,lipa}, where INFv terminates the traffic and performs further routing. INFv uses a pub-sub MQ system (as proposed by MEC) to store the processed requests while the routing decisions take place and to perform in-network communication. Because nodes cache functions, there will be multiple copies in the network. The first job of the network subsystem is to route user requests to the closest copy. Functionality execution consumes both CPU and memory as well as other resources (e.g., bandwidth). INFv focuses on the first two since they are usually the most dominant resources. The second job of the network subsystem is to balance the load of executing functions. The goal of load balancing is achieved by strategically dropping or forwarding computation tasks to other nodes to avoid being overloaded. However, instead of distributing load uniformly over all available nodes, a service is better executed as close to a client as possible to minimize latency. \rone{My general feeling is that load balancing may not be the first order concern for mobile code offloading. We have many examples of working systems that are being load balanced. Most of the work in this area assume a small cloud (e.g., single rack) in the access network. It would be good to justify the problem a bit more. The approach also has drawbacks---passing application data between docker instances (applications) incurs latency overhead. - What is the impact of dropping a offload request? } \manote{Package drops will increase the method invocation \"latency\" in the sense that there will be retrials.} Centralized coordination is not ideal for practical deployment due to three reasons: 1)~A central solver needs global knowledge of a network and maintaining such knowledge up-to-date is costly, 2)~the optimal strategy needs to be calculated periodically given the dynamic nature of network and traffic, and 3)~there is a single point failure. Therefore, we study and implement two basic heuristic strategies -- passive \& proactive in INFv. Both strategies have rather straightforward implementations and try to minimize latency. For the proactive one, we apply a simple $M/M/1$-Processor Sharing (i.e., $M/M/1-PS$) queuing model to estimate the future queue length. The workload on each node can be further estimated based on the predicated queue length and periodically measured CPU and memory consumption of each function. Next we sketch the core idea behind each heuristic; please refer to~\cite{wang_c3po:_2016} for further algorithmic details. \rthree{The truly novel part should be the one related to operator deployment - however there you design a bunch of algorithms which you don't implement in practice, and you only simulate in completely unrealistic networks (e.g. grid). This leaves many questions open, like: how do I discover my operator's offloading points? What happens when I am roaming? How do the different offloading VMs change stats (required by your protocol)? etc.} \manote{Is there any study on the mobility of users that shows that users are less likely to use the phone while moving? I mean if you put the phone in your pocket the app is gonna be stopped anyways, you move and when you reconnect all your state will be recreated. Apps are short-lived. Nonetheless, we can probably defend state migration as app state is quite small, we would just need to replicate requests to both machines until we shut the furthest away down.} \liang{yep, you can add a couple of sentences in this section to make the motivation a bit stronger, and discuss a bit about the state migration cost.} \textbf{Passive Control}: Nodes execute as many requests as possible before being overloaded. If the node is overloaded, the requests are passed to the next hop along the path to a server, or dropped if the current node is already the last hop in the ISP network. \liang{Or sending it to the server, which is probably more expensive?} \textbf{Proactive Control}: Nodes execute requests conservatively to avoid being overloaded. To do so, a node estimates the request arrival rate to further estimate the potential consumption. If the estimate shows that the node may be overloaded, it executes some and forwards the rest to the next hop neighbor with the lightest load. NB: This strategy requires exchanging state information within a node's one-hop neighborhood. \subsubsection{Functionality Offloading} The INFv end device system (Fig.\ref{fig:mobile}) is composed by one or more monitors and one standalone process that provides a network stub and a resource monitoring (RM) system. Each app process transparently loads and executes an INFv monitor on start. The App Manager intercepts the app entry points declared in the manifest and binds to the per-device Network Stub. The Partition Manager (PM) loads the partitions and instructs the Hook Manager to hook their entry and exit points, enabling the interception of their respective members (methods \& constructors). Once a target invocation is intercepted, the PM retrieves the current environment-dependent metrics from the RM and decides whether to offload it or not. If so, a message is created and sent by the AppConnector to the Network Stub service (via IPC) that transparently interacts with the closer network node to execute it. Network nodes abstract the network topology by providing a message queue (MQ) between the stub and the execution backend. Within the MQ abstraction, routing is done using the user, device, app and version IDs, along with the fully qualified member name and its arguments. The Thread Manager keeps a per-thread queue of the offloaded requests and suspends the threads until the invocation result is received or there is an intermediate invocation of a member in the same thread. The INFv backend subsystem runs the same monitor functionality over a light-weight app process. It loads only the required functionality and listens for incoming requests (Request Manager) from the mobile device. On request it creates class instances and executes their respective methods while managing their state. Although mobile apps are expected to be short-lived (imposed by screen off events and CPU sleep mode), state has to be kept while there are references to it. In INFv, remote class instances are replaced locally with ``light-weight'' instances of the same class (bypassing their constructors~\cite{objenesis}), which, on interception, work as proxy objects. These objects are tracked using a custom weak identity hash map that allows the detection of de-referenced or garbage collected objects, which results in a state invalidation message being sent through the INFv network stub. App crashes or force quit also trigger state invalidation. If the crash is INFv's specific, as apps are isolated, the instrumentation can be disabled for the specific app. Finally, when there are no requests or remaining references the VM can be paused after a certain period. More advanced distributed garbage collection mechanisms can be implemented that address some of aforementioned challenges~\cite{abdullahi_garbage_1998}. While INFv's offloading model resembles Java RMI, not only does Android's Java not support RMI by default, but it generally requires a remote interface (e.g., extending \textit{java.rmi.Remote}). Refactoring classes is possible at runtime using bytecode manipulation but is either expensive if done at launch time or significantly increases the app size by up to 40\%~\cite{zhang_refactoring_2012} when stored \subsubsection{Runtime Decisions} \label{sec:decisions} \rone{Also there is a risk that the app might behave incorrectly. How are these handled in INFv? The paper can describe these challenges to highlight its contribution.} \manote{All INFv related Exceptions extend our own custom Exception. If a non-INFv exception occurs it is passed to the application itself as it should. If the exception is related to INFv (e.g., sudden disconnection), if it occurs on a remote object creation, the object is created locally and it will work as expected using the local resources. If a method invocation over a remote resource fails, in the case of connectivity the invoking thread is paused until it is re-established and, if over a threshold, the user is notified. Other exceptions can drive the classes to be marked as not-to-offload to avoid crashes in future executions. Additionally we describe in the end of this section how the errors in energy measurements can be overcome.} \rone{After reading 4.2.1 I didn't get how it actually works and how involved the system is. So I'll list some questions I had. What's the underlying technology? Which method calls need to be intercepted? What happens when the partitioning (what to offload) is decided at run time?} \manote{We had more details in previous submissions, dunno if we should bring them in.} At runtime the PM decides which of the (offline) pre-calculated partitions should be offloaded. This decision is based on the partition's (offline) estimated execution parameters (Section~\ref{sec:profiling}) and the periodic device measurements and state monitored by the RM -- network type, bandwidth and latency. In previous class offloading research~\cite{zhang_refactoring_2012}, a partition would only be valid for offloading if, for each of its classes, all methods perform faster when offloaded. Unfortunately from our experience this rarely holds, even for CPU intensive classes. For example, simple methods such as an overridden \textit{toString()} or \textit{equals()}, will in most situations perform worse than local when offloaded due to the RTT. In INFv, instead of considering methods individually, for each class we aggregate its method's execution and energy consumption based on their observed method invocation frequency ($f_i$). Therefore, methods that perform better when offloaded can compensate for the least performing methods \emph{if these do not occur too often}. A class $c$ is valid if: $\sum_{m=1}^{M} f_{m}*t_{m\_local} > \sum_{m=1}^{M} f_{m}*(RTT + (i_{m}+o_{m})/r+t_{m\_offload})$, where $M$ represents the number of class methods and $f_{m}$ the method's invocation count normalized by the total number of invocations observed for all the class methods. The size of the method's input and output parameters are represented respectively as $i_{m}$ and $o_{m}$. These are divided by the transmission rate ($r$) and, along with the RTT, are only counted for methods interfacing between the local and remote partitions (partition boundary). Finally the local ($t_{m\_local}$) and remote ($t_{m\_offload}$) execution times are a function of the CPU frequency difference between the mobile device and the node. Classes are similarly validated based on the energy consumption of their edges, except that a method's energy consumption is only considered for edges that bridge partitions. For these methods (technically the edges between such classes), only the state transmission costs and the normalized invocation frequency are used when calculating the class's energy consumption. INFv validates the pre-calculated partitions by increasing the number of partitions ($N$) until it finds a valid partition. In the worst case scenario $N$ is equal to the number of classes and valid classes are offloaded individually\footnote{In practice, a threshold is selected via modularity optimization~\cite{blondel2008fast} to avoid high link density classes to be executed separately.}. Finally, the existing Android diagnosis resources \linebreak(\texttt{dumpsys}) are used to report potential anomalies (e.g., high energy consumption) and processed (offline) by a negative feedback loop to reduce the deviations between estimated and observed values. An advantage of INFv over app repackaging systems is that it is able to dynamically load new partitions and metadata to handle such cases. \subsubsection{App Analysis \& Profiling} \label{sec:analysis} Designing functionality partitions requires app knowledge. In INFv most of app analysis is done offline (left-most system in Fig~\ref{fig:architecture}) and is composed of two steps. The first consists of performing static analysis of the app, i.e., the app analysis platform retrieves an app from the Google Play (GP) store, decompiles it (using \textit{apktool}\cite{apktool}) and parses both the manifest and \textit{smali} files (i.e., disassembled Dalvik bytecode). From the first we retrieve the app properties, such as package name, version and app starting points (e.g., activities, broadcast receivers, etc). From the second we build a call graph where the vertexes represent classes and the edges method calls. This call graph is used to detect accesses to methods/classes that should execute locally, such as access to local hardware~\footnote{Android's bluetooth, hardware, MTP, NFC and telephony packages.} and UI~\footnote{Android's Activity, View, Widget, Gesture, Text, Transition, Animation and Graphics packages.}. Our static analysis tool~\footnote{We made our static analysis tools open-source~\cite{broker,droidsmali}.} includes a DSL to tag packages which we used to manually pre-tag most of the Android packages depending on their requirements. The second step consists of attributing weights to the call graph edges based on their runtime invocation counts as well as metadata regarding vertices' energy consumptions and execution times. Apps are executed in instrumented VMs and exercised using UI automation (reproducible pseudo-random input~\cite{monkey}). These VMs use the aforementioned instrumentation mechanisms to load the call graph on app start and intercept method invocations. We had to perform some optimizations to reduce the tracing overhead, such as increasing the VM heap size and restricting the tracing to app methods. The average of the intercepted methods parameters are registered in the call graph metadata -- state size, thread, execution time, invocation counts -- along with the predicted energy consumption based on the PowerTutor model~\cite{zhang_accurate_2010}. This model uses the device states (CPU, screen, GPS, connectivity) to predict energy consumption. It can derive a per device power model (with a low error of up to 2.5\%) by performing regression over the energy discharge patterns observed while looping through different device power states. The INFv dynamic analysis platform can accommodate physical devices to automate this process, or a one time power discharge execution can be run in users devices to retrieve the specific device model. We report that the minimal information needed by our offloading mechanisms requires on average 3MB per app when uncompressed (based on the top 30 market apps), which is reasonable even considering Android's memory constraints (i.e., small heap size -- 48MB in Galaxy S2). While INFv's approach saves the profiling energy on mobile devices as well as the overhead of method tracing, we do acknowledge some limitations. Some of the power model metrics (e.g., screen, GPS) are not accurate or observable in a VM. The VM screen is always on and some networks/sensors are emulated. While the second is unimportant as these should execute locally anyway, the first may overestimate energy consumption which later prevents some functionality from being offloaded. We discuss some of these limitations in Section~\ref{sec:discussion}. \subsubsection{App Partitions} \label{sec:partitions} Partitions define which subsets of functionality should be offloaded. In MCO, partitions are generally static and their outcome is a rebuilt app (potentially two disjoint apps) with some functionality re-purposed for offloading. In INFv's client, partitions are just information regarding the offloading subset, i.e., class names and execution properties (e.g., execution time, energy consumption, network conditions). These sets are pushed to the device, loaded on app launch and drive app's execution. Partitions can be devised on method and thread granularity. The latter incurs an extra cost of synchronization (e.g., thread state, virtual state, program counters, registers, stack), and is often restricted to method boundaries~\cite{chun_clonecloud:_2011}. In order to better integrate with the NFV abstraction, our solution \emph{is} able to provide the granularity of method offloading. However, since most mobile architectures apps are developed in class-based object-oriented languages, in practice we use a class offloading granularity as methods often invoke methods of the same class and share class state (e.g., class fields). Furthermore, there is a large overlap of classes and packages across apps, which minimizes the impact of storing app functionality in the network (Section~\ref{sec:cache}). One of the main concerns in MCO is the balance between offloading computation and its communication overhead due to remote method invocations. To reduce this overhead, we use the app call graph (Section~\ref{sec:analysis}), i.e., $G=(V,E)$ where $V$ is the set of app classes and $E$ the invocations between classes, to detect communities/clusters (sub-graphs of $G$) of $V$ based on their invocation counts. INFv uses a community detection algorithm -- Girvan and Newman (GN) \cite{girvan_community_2002} to detect edges that are likely between communities. To do so it recursively detects the edge with highest number of shortest paths between pairs of nodes passing through it (i.e., the edge with highest betweenness) and removes it. By removing edges with high betweenness, the communities get separated and we end up with distinct functionality clusters. Community detection was firstly proposed by Zhang et al.~\cite{zhang_refactoring_2012} which used static analysis invocations as edge weights. The problem is that these do not reflect the actual runtime invocation counts between classes, and so the study relies on a weight heuristic based on class semantic similarity, i.e., class names and their textual contents. Unfortunately, our app study in Section~\ref{sec:cache} indicates that 82\% of the apps perform class name obfuscation and in some cases even the strings within classes can be obfuscated~\cite{dexguard}. As INFv executes apps, it registers the method's runtime invocation counts, bypassing such limitations. The GN algorithm receives the number of clusters as a parameter which we iterate from two to the optimal number of clusters as calculated via louvain's~\cite{blondel2008fast} modularity (density of links within clusters) optimization. Any partition with classes tagged during static analysis as non offloadable is discarded. In Section~\ref{sec:decisions} we discuss how these pre-calculated partition sets are picked for offloading at runtime. \rone{When it comes to partitioning apps, it only states that it avoids offloading functionality that should execute on the device. It does not describe what the system actually decides to partition. Automated partitioning is one of the contributions of the paper and motivation suggests this can be done in adaptive fashion considering the app and the network. The paper would greatly improve if it contained an adaptive algorithm that intelligently partitions apps. One key challenge in partitioning is that often objects have shared data structure and complex dependencies. For example, parameter settings, environment variables, references are hard to track. So it is non-trivial to capture the whole execution context (but doable).} \subsection{Investigate Realistic App Market} \rone{Although, the technique in identifying functionality overlap is rough and not very exact, it provides a ball park number. However, I had hard time linking the result/motivation to the rest of the paper. The evaluation does not show that popular classes can be offloaded. Instead, it uses two non-representative workloads. I wasn't sure how the benefit extends to many apps, as implied by the motivation in Section 3.} \manote{We discussed doing a new plot with X-Axis number of popular apps and Y-axis cache size.} \manote{Well there should be apps using the face detect apis, so it kind of does offload a common functionality. Perhaps we dont explicitly say its the Android official Face Detect API.} \manote{Additionally we can try to add a new opensource app.} \manote{Ack different versions of the libraries can affect caching.} In this section we give some intuition behind the idea of network functionality caching and empirically show its feasibility via a study of over 20K of the most popular apps on the Google Play Store in February 2016. As Fig.~\ref{fig:dex} shows, the market app packages (\textit{apk}) are quite small ($\mu \approx 15.3MB$) even considering the actual install size ($\mu \approx 23.9MB$). Only a fraction of the apk is actually app functionality -- dalvik executable (\textit{dex}) --, which contains the app classes. For medium/big sized apps (78\% of the apps), when extracted from the \textit{apk}, the \textit{dex} size is on average 34.1\% of the \textit{apk} size ($\tilde{x} \approx 25.3$\%). Our dataset accounts for over 81\% ($\approx 15,000$ apps \cite{Viennot:2014}) of all Google Play downloads and in total these apps require an aggregated storage of 307~GB (\textit{apk} size), which is a manageable size. The large overlap in app functionality can be exploited to intelligently cache functionality in the network. To understand why and how this is possible, a brief overview of Android app organization and packaging is necessary. Android apps organize functions into packages which are further identified with a hierarchical naming scheme similar to domain names. Intuitively, the hierarchical naming could facilitate us in identifying shared functionality across apps. Unfortunately, naming in Android can be affected by obfuscation, a security mechanism that remaps functionality and package names. It makes it hard, if not impossible, to detect similarities based on simple name comparisons. E.g., a package ``\texttt{com.apple}'' from app A and a package ``\texttt{com.google}'' from app B can both be renamed to ``\texttt{a.a}''. But, since in Android obfuscation (i.e., Proguard) names are attributed alphabetically, we found that it is possible to detect if a package name is obfuscated or not based simply on name length. We found that 37.5\% of apps have potentially obfuscated packages with name ``a'' (at any given depth), while 82\% of the apps have at least one class named ``a''. By studying the name distribution with a single character at any given depth, we have found that the majority of obfuscated package names have names between ``\texttt{a}'' and ``\texttt{p}'' (8\% of all packages). Thus, we \emph{filtered all package names including names with just one character, at any given level.} Unfortunately obfuscated class names do not follow a similar distribution and such filter would exclude an high number of non-obfuscated classes. The remaining package names were used to estimate functionality similarity. If the same package name exists in two different apps we consider the functionality within this packages to be similar. Obviously, looking at low depth names ($N < 3$), such as the first depth packages (e.g., ``\texttt{a}'' in ``\texttt{a.b.c}'') which contain all other packages and functionality, many apps are likely to share the same name and therefore, most of the functionality will be considered similar (false positives). Looking deeper into the package hierarchy, however, can greatly reduce the rate of false positives. Fig.~\ref{fig:uniqueclasses} shows the percentage of unique classes per app based on a comparison on their first N package names. The number of unique classes are calculated as the \emph{total number of classes} in the app minus the number of classes belonging to \emph{non-obfuscated} package names that also exist in at least one other app. Considering that the package name distribution has $\mu \approx 4.7$, $\tilde{x} \approx 5.0$ and $\sigma \approx 1.6$, and that most package names have a depth between 4 (Q1) and 6 (Q3), even if we do a conservative comparison of packages based on their first 5 name depths (50th percentile), we can see that \emph{only 47\% (mean) of apps' classes are unique}. Note that while higher values ($N \geq 8$) reduce false positives, they also increase the number of false negatives as classes within packages with smaller depths are considered as unique. For a depth of 4, which is likely to include the name of the app and respective developer (e.g., ``\texttt{com.facebook.katana.app}''), 75\% (median) of apps' functionality is common with at least one other app. The analysis thus indicates that there is a substantial app's functionality overlap in the Android ecosystem. Extracting the app classes (\textit{classes.dex}), the storage requirements to host over 81\% of the most downloaded apps, are already reduced by 74\% ($\approx 80$GB). If common functionality is co-located, the total reduction can be up to 93.5\% ($<20$GB, based on the 4th depth median overlap). While our app analysis platform requires at least the full \textit{apk} files for analysis, the class overlap provides a unique opportunity for deployment in a modern ISP network, allowing INFv to exploit the network topology and ensure that functionality is available as close to users as possible. \section{Deployment considerations} \label{sec:deploy} \begin{figure*}[!htb] \centering \subfloat[CDF of package (apk), dalvik executable (dex), and disassembled dex (smali) sizes.]{% \includegraphics[width=0.3\textwidth]{figures/caching/dex_sizes} \label{fig:dex}% }\hfil \subfloat[Percentage of unique classes per app as a function of name depth used for comparison.]{% \includegraphics[width=0.3\textwidth]{figures/caching/ClassespbpackageSimilarity} \label{fig:uniqueclasses}% }\hfil \subfloat[Number of classes per app as a function of app popularity.]{% \includegraphics[width=0.3\textwidth]{figures/caching/classesPerPopularity}% \label{fig:popularity}% }\hfil \caption{Study of over 20K Google Play apps regarding their size, structure and uniqueness.} \label{fig:structure} \vspace{-5mm} \end{figure*} \tyson{ is it so important to have heavy overlap of libraries? Presumably, you're going to have classes for each app instance running separately (because each class will likely have different state). Unless you're doing some fancy stateless execution in one JVM, you're gonna have to have multiple processes running - one for each user. This means there is no runtime memory savings from people using the same classes. Obviously, the main benefit is therefore that you you already have the class sitting on the node when a request comes in. Perhaps worth highlighting the point very explicitly. } To achieve low latency when serving an offloading request, functionality should optimally be already present in nodes and it should perform well under varying load. This raises two questions: what is the storage cost of hosting the most popular apps? How well does the network subsystem perform under high-load while reducing the offloading latency? \subsection{Storage requirements} \label{sec:cache} \input{sections/cache} \subsection{Scalability to Workload} \label{sec:workload} In this section we perform a large network simulation using a realistic ISP topology (Exodus~\cite{spring_measuring_2002}) with Icarus~\cite{icarus-simutools14}. We use a Poisson request stream with $\lambda = 1000/s$ for the arrival rate; increasing the request rate introduces more load to the network. To simplify the presentation, we assume CPU is the first bottleneck in the system for computationally intensive apps and all experiments are performed $>$50 times to ensure the reported results are representative. \begin{figure} [t!] \includegraphics[width=8cm]{figures/isp_exodus_load} \caption{Comparison of three strategies (rows) with increasing load (columns). $x$-axis is node index and $y$-axis is load. Top $50$ nodes of the heaviest load are sorted in decreasing order and presented. Notations: $\tau$: average load; $\phi$: average latency (in $ms$); $\psi$: ratio of dropped requests.} \label{fig:2} \vspace{-5mm} \end{figure} Fig.~\ref{fig:2} shows the results of using three strategies (one for each row) with three workloads (one for each column). There are 375 nodes in the network and we randomly select 100 nodes of degree one as access points to receive user requests. The average load of each node is normalized by its CPU capacity and only the top 50 heaviest loads are presented in a decreasing order. By examining the first column, we can see all three strategies have identical behaviors when the network is underutilized with a workload of $\lambda$. The heaviest loaded node uses only about 60\% of its total capacity. However, as we increase the load to $4 \lambda$ and $8 \lambda$, the three strategies exhibit quite different behavior. The experiment without a control strategy (``none'') at the first row, the figures remain the similar shape. Since no load is distributed and a node simply drops all requests when being overloaded, it leads to over 54\% drop rate with load of $8 \lambda$. For passive control (second row), we can see both the heads and tails are fatter than ``none'' control, indicating that more load is absorbed by the network and distributed on different routers. This can also be verified by checking the average load in the figure: given a load of $8 \lambda$, passive control increases the average load of the network from $0.2305$ to $0.3202$ compared to using ``none'' control. However, there is still over $36\%$ requests dropped at the last hop router. This can be explained by the well-known small-world effect which makes the network diameter short, so there are only limited resources along a random path. Among all the experiments, a network with proactive control always absorbs all the load, leading to the highest average load in the network which further indicates the highest utilization rate. As the workload increases from $\lambda$ to $8 \lambda$, average load also increases accordingly with the same factor. One very distinct characteristic that can be easily noticed in the last two figures on the third row is that the load distribution has a very heavy tail. This is attributed to the proactive strategy's capability of offloading to its neighbors. It is also worth pointing out that we only measured the latency of those successfully executed functions, which further explains why ``none'' control has the smallest latency, since offloaded functionality gets executed immediately at an edge router connected to a client, but \emph{more than half the requests are simply dropped and not counted at all}. Comparing to the passive strategy, the proactive strategy achieves lower latency. Further investigation on other ISP topologies shows that latency reduction improves with larger networks. \subsection{Investigate Realistic App Market} \section{In-Network Function Caching} \label{sec:cache} \rone{Although, the technique in identifying functionality overlap is rough and not very exact, it provides a ball park number. However, I had hard time linking the result/motivation to the rest of the paper. The evaluation does not show that popular classes can be offloaded. Instead, it uses two non-representative workloads. I wasn't sure how the benefit extends to many apps, as implied by the motivation in Section 3.} \manote{We discussed doing a new plot with X-Axis number of popular apps and Y-axis cache size.} \manote{Well there should be apps using the face detect apis, so it kind of does offload a common functionality. Perhaps we dont explicitly say its the Android official Face Detect API.} \manote{Additionally we can try to add a new opensource app.} \begin{figure*}[!htb] \centering \subfloat[Installation size of apps as a function of app popularity.]{% \includegraphics[width=0.3\textwidth]{figures/caching/sizePerPopularity}% \label{fig:install}% }\hfil \subfloat[Percentage of unique classes per app as a function of name depth used for comparison.]{% \includegraphics[width=0.3\textwidth]{figures/caching/ClassespbpackageSimilarity} \label{fig:uniqueclasses}% }\hfil \subfloat[Number of classes per app as a function of app popularity.]{% \includegraphics[width=0.3\textwidth]{figures/caching/classesPerPopularity}% \label{fig:popularity}% }\hfil \caption{Study of over 20K Google Play apps regarding their size, structure and uniqueness.} \label{fig:structure} \end{figure*} A key insight that informs the design of INFv is the potential of network functionality caching. In this section we give some intuition behind the idea and empirically show its feasibility via a study of over 20K of the most popular apps on the Google Play Store in February 2016. In summary, our investigation reveals two important facts: 1) a very small amount of apps account for most of the downloads; 2) there is a significant code overlap due to commonly used libraries. Two facts together indicate a medium storage requirement on INFv as the detailed analysis shows in the following. Fig.~\ref{fig:install} shows that the distribution of the installation size of mobile apps has a $\mu \approx 23.9MB$ (mean), $\tilde{x} \approx 10.2MB$ (median) and $\sigma \approx 66.9MB$ (standard deviation). By comparing to the numbers reported in \cite{Viennot:2014}, we also confirm that $\approx 15,000$ apps are responsible for 81\% of all Google Play downloads and in total they require an aggregated storage of 409~GB. This is apparently a manageable size even without excluding a few outliers which are up to 2.1~GB. INFv exploits the large overlap in app functionality to intelligently cache functionality in the network \manote{we do not mention how}. To understand why and how this is possible, a brief overview of Android app organization and packaging is necessary. Android apps organize functions into packages which are further identified with a hierarchical naming scheme similar to domain names. Intuitively, the hierarchical naming could facilitate us in identifying shared functionality across apps. Unfortunately, naming in Android can be affected by obfuscation, a security mechanism that remaps functionality and package names. It makes it hard, if not impossible, to detect similarities based on simple name comparisons. E.g., a package ``\texttt{com.apple}'' from app A and a package ``\texttt{com.google}'' from app B can both be renamed to ``\texttt{a.a}''. But, since in Android obfuscation (i.e., Proguard) names are attributed alphabetically, we found that it is possible to detect if a package name is obfuscated or not based simply on name length. We found that 37.5\% of apps have potentially obfuscated packages with name ``a'' (at any given depth), while 82\% of the apps have at least one class named ``a''. By studying the name distribution with a single character at any given depth, we have found that the majority of obfuscated package names tend to have names between ``\texttt{a}'' and ``\texttt{p}''. This means that, for the apps in our dataset, \emph{a simple filter to find packages names which have, at any given depth, a name with just one character is enough to ignore the majority of obfuscated packages (8\% of all packages). We have used the package names to estimate functionality similarity. If the same package name exists in two different apps we consider the functionality within this packages to be similar. Obviously, if we look at low depth names ($N < 3$), such as the first depth packages (e.g., ``\texttt{a}'' in ``\texttt{a.b.c}'') which contain all other packages and functionality, many apps are likely to share the same name and therefore, most of the functionality will be considered similar (false positives). If we look deeper into the package hierarchy, however, we can greatly reduce the rate of false positives. Fig.~\ref{fig:uniqueclasses} shows the percentage of unique classes per app based on a comparison on their first N package names. The number of unique classes are calculated as the \emph{total number of classes} in the app minus the number of classes belonging to \emph{non-obfuscated} package names that also exist in at least one other app. Considering that the package name distribution has $\mu \approx 4.7$, $\tilde{x} \approx 5.0$ and $\sigma \approx 1.6$, and that most package names have a depth between 4 (Q1) and 6 (Q3), even if we do a conservative comparison of packages based on their first 5 name depths (50th percentile), we can see that \emph{only 47\% (mean) of apps' classes are unique}. Note that while higher values ($N \geq 8$) reduce false positives, they also increase the number of false negatives as classes within packages with smaller depths are considered as unique. If we consider a depth of 4, which is likely to include the name of the app and respective developer (e.g., ``\texttt{com.facebook.katana.app}''), we see that 75\% (median) of apps' functionality is common with at least one other app. The analysis thus indicates that it is safe to conclude that there is a substantial overlap between app functionality in the Android ecosystem. This significant overlap in functionality provides a unique opportunity for deployment in a modern ISP network. By co-locating common functionality, we can reduce the storage requirements while at the same time allowing us to exploit the network topology to ensure that functionality is available as close to users as possible. The design and architecture of INFv is informed in large part by this insight. \section{Motivation} \label{sec:motivation} \liang{section need to rewrite} INFV is motivated by two aforementioned observations. The first one (on abundant in-network resources) can be easily validated by noticing the strategic moves of big telecommunication companies. Namely, the current ISP infrastructure is transforming into NFV-enable network step by step quickly to improve utilisation rate\cite{telefonica:nfv,telefonica:cartablanco,telefonica:unica}. In this section, we validate the second observation by performing a deep investigation in current mobile application market. We focus on Android platform in this paper, how to generalise to other platforms like Apple's iOS will be discussed in Section \ref{sec:discussion}. \begin{figure*}[htp] \centering \subfloat[Packages per app]{% \includegraphics[width=0.3\textwidth]{figures/caching/PackageLevelDistribution.pdf}% \label{fig:packagesperapp}% }\hfil \subfloat[Unique classes (\%) per app]{% \includegraphics[width=0.3\textwidth]{figures/caching/PercentageOfNonUniqueClasses.pdf}% \label{fig:uniqueclasses}% }\hfil \subfloat[CDF of the jaccard indexes for pairs of apps based on their packages. Each line represents a different package depth.]{% \includegraphics[width=0.3\textwidth]{figures/caching/JaccardCDF.pdf}% \label{fig:classespopularity}% } \caption{Study of the number packages and number/uniqueness of classes per application.} \end{figure*} 3) Diffusing and hosting functionality on the network raises multiple challenges and these are exacerbated if we consider that this functionality is transparently transfered to the network. One of these challenges relies on the multitude of different applications present in mobile app markets (e.g., 1.5M apps in the Google Play store\footnote{1st quarter of 2015 - http://www.appbrain.com/stats/number-of-android-apps}), each possibly composed by thousands of classes with variable number of methods\footnote{As both iOS and Android are object-oriented, we consider methods to be the closest match to the NFV function abstraction.}. Concerns are therefore raised regarding the caching capabilities of such system: \begin{itemize} \item How big are applications? \manote{no numbers on this yet, but should be extremely fast!} \item What to partition app functionality? How to to version and update this functionality? \item Can caching cost be reduced? Is there an overlap of functionality across apps? \end{itemize} To answer these questions we have crawled the Google Play Market to download over 18K of the most popular free apps and decompiled them in order to perform static analysis. We found (Figure~\ref{fig:classespopularity}) that, although applications can have considerable high number of classes (up to 25K), the 25th-75th percentile of apps have less than 10K classes. This holds true independently of the number of downloads of the app, as we have also observed that apps with more downloads tend to have more classes. In order to diffuse methods in the network and maintain some mechanism for updating these methods we require some sort of versioning. When a client wants to execute a function in the network, he would provide the name schema for the function (e.g., function name) and a version identifier. Tracking identifiers on a per method basis could be costly due to the high number of methods per application. A reasonable solution consists on devising a grouping schema to functions. Keeping the OO abstraction this grouping could potentially be done on a per class, package or application basis. We argue that a per package basis can already be too coarse granularity as the number of classes can be orders of magnitude bigger than the number of packages, meaning that a single class update would require a whole package update. In OO languages methods typically operate over some state, not only input variables and static state, but also their respective class state. Class methods are also likely to share the same state and make intra-class method invocations. Therefore, while different granularities might also have some advantages, we will consider class granularity as it can have a positive impact on state shattering, cost of communication between methods and a smaller impact on the cost of version tracking and respective delta updates. Hosting an arbitrary number of app functions in the network can be costly, therefore it would be interesting to detect if there is an overlap of app functionality that could amortize this cost. To do so, we collected all app's packages and respective class count. Packages were grouped based on their depth, for example \texttt{a.b.c} has a depth of 3, while \texttt{a.b} has a depth of 2. We note that the number of classes of the second includes the classes of the first. \begin{figure*}[htp] \centering \subfloat[Popularity distribution of common packages (e.g., ads, rendering, networking)]{% \includegraphics[width=0.3\textwidth]{figures/caching/packagesPerApp.pdf}% \label{fig:packagesperapp}% }\hfil \subfloat[Another figure for "Similarity vs. popularity"?]{% \includegraphics[width=0.3\textwidth]{figures/Placeholder.png}% \label{fig:uniqueclasses}% }\hfil \subfloat[\# of classes vs. popularity]{% \includegraphics[width=0.3\textwidth]{figures/caching/classesPerPopularity.pdf}% \label{fig:2}% } \caption{Study of the number packages and number/uniqueness of classes per application.} \end{figure*} The plots in Figures~\ref{fig:packagesperapp} and \ref{fig:uniqueclasses} depict, respectively, the distribution of packages and the percentage of unique classes per application, depending on the considered package depth. Considering a depth of 1 means that packages such as \texttt{a.b} and \text{a.c} will be ignored and only their aggregated class count is considered (i.e., package \texttt{a}). For the sake of simplicity, we assume that classes within a similarly named package across two applications are similar. We consider this to be a reasonable assumption since most libraries/apps tend to have custom package naming related to their app, developer and company names. Since for lower package depth these names will have more collisions, the higher the package depth considered, the most likely the class similarity assumption is to be held true. To make our assumption more conservative, the total number of unique classes is calculated as the total number of classes in the app (independently of package depths) minus the number of classes belonging to packages which the N-depth package name is shared by at least one more app. As shown in Figure~\ref{fig:uniqueclasses}, as expected, for a depth of 1, apps are likely to have no unique classes as most tend to share the 1-depth package name (e.g., \texttt{com}). If we look at rather deep package name depth of 5, which will be less likely to collide (e.g., \texttt{a.b.c.d.e} and \texttt{a.b.c.d.f} would be considered different packages), it not only possesses an higher median and average number of package counts (Figure \ref{fig:packagesperapp}), but we have also found that the median and average count of unique classes are around 40\% (Figure \ref{fig:uniqueclasses})\manote{check the exact number}. This is a very clear indicator that \emph{apps tend to have an high number of shared classes which are not app specific}. In figure \ref{fig:packages} we show an example of the packages (we ignored compatibility/OS packages such as android support) present in the most number of apps. We can see that there are 3rd-party library packages that are present across high percentage of apps. While the two first are Google technologies, such as google play services and ads, we see that Facebook libraries are present in more than 30\% of the apps. These libraries also include rendering and animation packages (e.g., unity3d and nineoldandroids). \manote{Note to self: check obfuscation and package depth for upcoming plot} 5) Server-assisted mobile application execution can provide support for computation intensive applications/services (e.g., aggregation of sensor data flows, voice processing, 3D rendering, etc), for which, executing the computation remotely can greatly reduce its energy costs even in the presence of extra communication. Mobile remote execution has been the topic of multiple research works~\cite{chun_clonecloud:_2011,chen_coca:_2012,gordon_comet:_2012,kemp_cuckoo:_2010,cuervo_maui:_2010,zhang_refactoring_2012,kosta_thinkair:_2012}. For example, CloneCloud~\cite{chun_clonecloud:_2011} performed experiments with a virus scanner, face detection and web page categorization, achieving up to 20x execution speed-up and a 20-fold decrease of energy spent. Aggregation of data and remote storage are also possible use cases as these devices often have limited storage capacity. When providing remote resources, there needs to be a balance between the energy cost of the extra communication induced by the remote execution and the benefits of providing these remote resources. Therefore, proximity and latency have a relevant impact on such architectures and can reduce the scope of applications/services they can provide, for example, delay-sensitive and interactive applications. Latency also increases the energy consumption in mobile devices as having a longer established communication channel in mobile networks is expensive \manote{trinity refs here}. Having higher communication energy costs can often become a no-go even for non-interactive or delay-sensitive computation intensive applications. Therefore, by adopting the NFV paradigm, not only these architectures could be applied to more apps but also perform better. \manote{would it be possible to show: other architectures if the user moves to somewhere with higher latency the code is no longer offloaded, while our functionality moves closer to the user, eventually offloading methods again?} \section{Motivation} \label{sec:motivation} INFV is motivated by two aforementioned observations: there is a clear gap between battery capacity and the growing energy consumption of modern mobile applications~\cite{oliner_carat:_2013, Aucinas:2013:SOW:2535372.2535408}; and ISP networks are shifting towards the deployment of in-network multi-core general purpose machines following the NFV paradigm. While Cloudlets~\cite{satyanarayanan_case_2009} discussed the impact of low latency in mobile code offloading and proposed the deployment of physically proximate decentralized clusters, similar to the abstraction of NFV, most of the more recent mobile code offloading architectures still rely on a mobile-to-cloud paradigm~\cite{cuervo_maui:_2010, kemp_cuckoo:_2010, kosta_thinkair:_2012,chen_coca:_2012, zhang_refactoring_2012, gordon_comet:_2012, chun_clonecloud:_2011}. Furthermore, they cannot be directly applied in an ISP network since none has been designed to exploit network topologies let alone inherent load-balancing functionality. Additionally, they tend to propose intrusive models that require either custom OS distributions~\cite{chun_clonecloud:_2011,gordon_comet:_2012}, app repackaging~\cite{zhang_refactoring_2012} and/or custom app distribution stores, greatly reducing their possible device adoption. These observations naturally lead to an attempt on leveraging \emph{existing} in-network resources for dynamic offloading functionality from stock mobile devices to a network in order to improve both battery life and latency. However, considering there is a huge amount of mobile apps on the market, an important question remains unanswered -- is it possible to accommodate all the offloaded functionality in an ISP network? Answering such questions requires investigation of real app markets and, while this has been mostly overlooked in previous research, we aim to shed light to these questions in this paper. \section{Partition and Profiling} \label{sec:profiling} \jbnote{There is so much crap in this and the previous section.. I'm not sure if it's really necessary. It gets cumbersome to read..} In this section, we discuss the implementation details of the architecture presented in Section~\ref{WHATEVER}, focusing specifically on how we addressed the outlined design challenges. In mobile code offloading, apps are typically partitioned into a set of functionality to execute locally and another to execute remotely. Such system needs to detect good candidates to offload, e.g., based on energy consumption and execution time. The selection is done via static and dynamic analysis on apps' behaviors (a.k.a., profiling apps). Since profiling per se is energy consuming and can degrade devices' performance, we devise our first requirement: \textbf{Req1)} \emph{App profiling should have minimal impact mobile device energy consumption and performance.} In our design most of the profiled metrics and estimations are performed remotely (INFv servers) for a given mobile device. INFvs profiling subsystem consists of an app analysis cluster and repository containing these apps' partition functionality as well as their respective metadata. This metadata includes the app representation (e.g., information regarding app structure and method invocations) and estimated resource usage (e.g., energy, execution time). The app analysis cluster has a set of schedulers that launch VM instances to analyze apps then stores the respective results in the repository. App analysis is done through static (i.e. parsing decompiled bytecode) and dynamic analysis of the apps. The first is used to retrieve the metadata app representation and do an initial prediction of possible partitions (e.g., pinning to execute locally functionality that uses devices hardware). The second is used to benchmark app partitions and to retrieve functionality execution time, parameter state and energy consumption (i.e., partition's metadata), which is used for performing informed offloading decisions. \subsection{App Partitions} \label{sec:partitions} App partitions describe sets of functionality to be executed locally or remotely. In INFv we differentiate between partition functionality and metadata. The latter including a representation of the app and the resource estimates for performing informed offloading decisions. Offloading can occur at multiple granularities (i.e., units of functionality to be offloaded). The most common are method~\cite{cuervo_maui:_2010,kemp_cuckoo:_2010,kosta_thinkair:_2012,chen_coca:_2012} and thread~\cite{chun_clonecloud:_2011,gordon_comet:_2012} granularity. The latter often incurs an extra cost of synchronization (e.g., thread state, virtual state, program counters, registers, stack, locks, etc), while still being restricted to method entry and exit points~\cite{chun_clonecloud:_2011}. In order to better integrate with the NFV abstraction, our solution is based on method offloading. Since most mobile architectures (e.g., iOS and Android) apps are developed in class-based object-oriented languages\jbnote{is this true for Objective-C?}, when possible we try to use a class offloading granularity. Although each granularity has pros and cons, class granularity has some clear benefits regarding both number of invocations and state synchronization. First, class methods are likely to invoke other methods of the same class, and secondly, these methods also likely to share common class state (e.g., class fields)\jbnote{Do we have any justification for statement?}. \manote{some stats here: number of classes per app, probability of a class method calling a method of the same class, probability of accessing class fields} Typically, due to the object-oriented design, there are also better chances that class granularity will provide better semantic separation between application methods, and as we have seen in Figure~\ref{fig:uniqueclasses}, there is a large overlap of common classes and packages across apps, which minimizes the impact of storing app functionality in the network. \subsubsection{Opensource App representation \& analysis} Our app representation (and its static analysis tool) is open-source\footnote{https://bitbucket.org/aknahs/droidbroker}. It includes the information required to instrument the app, such as app starting points (as described in the manifest, e.g., activities, broadcast receivers, etc), the class methods and their inner invocations (represented through a graph). Similarly to DPartner~\cite{zhang_refactoring_2012}, it is also able to tag functionality based on the APIs they use. This becomes particularly useful when we try to avoid offloading functionality that should execute on the device (e.g., sensors). It also contains structures for static and dynamic analysis information (e.g., occurrences and execution time), as well as graph visualization support (e.g., Gephi) to provide visual information regarding the clustering of functionality. Using the representation of the app, INFv is able to check what are the entry and exit points of each of the classes/methods (e.g., graph edges for method invocations) of the partition in order to intercept their execution. As Android applications have restrictive heap sizes (e.g., 48MB in Samsung Galaxy S2), our application representation has to be as small as possible. With the minimal information needed by the offloading mechanisms (e.g., how do classes interact), our uncompressed representation requires on average 3MB per app (based on the top 30 apps of our dataset). \subsection{Partitioning} In systems with class or method granularity, app partitions are typically done offline and require repackaging of the app. In such cases, although some support multiple partitions for the same app, the partitioning cannot be done dynamically after app installation. This means that if the app behavior (dependent on user interaction) differs from the behavior observed during the partitioning process and there is no partition that satisfies the new use case, the system cannot adapt properly.\liang{I guess you mean the consumption model within an app has changed ... so needs repartition?}\manote{Functions receive arguments that are sometimes defined by users. Imagine that the app is tested with an automated input generator. What if this input is not representative of the user. What if users have different patterns. We dont know if there will be significantly different energy patterns} App-repackaging can also be a barrier to implementing automated profiling through UI instrumentation (such as the one used in~\cite{chun_clonecloud:_2011}). \emph{In INFv apps are not repackaged and new partitions can be defined/loaded at any point in time} using a custom class loader, details of which appear in Section \ref{sec:instrumentation}. Partitions in INFv are represented by the partition functionality, which is hosted at the network nodes, and partition metadata which is fetched by the mobile devices. Partition metadata includes lists of classes and a set of parameters used for performing offloading decisions (e.g., estimated energy, execution time, state, etc). The INFv monitor (Figure~\ref{fig:architecture}) will use the partition's metadata to decide which methods to intercept (exit and entry points of the partition) and potentially offload. Previous research has focused on the challenges of performing app partitioning with class granularity and it should be fairly simple to map existing partitioners, such as DPartner~\cite{zhang_refactoring_2012}, to our system. That said, some of the limitations of the existing partitioners and the security/overhead of the interception mechanisms are discussed in Section~\ref{sec:discussion}, while in Section~\ref{sec:evaluation:linpack} we will discuss the impact of different partitioning choices in the energy consumption and execution time of our offloading architecture. \subsection{Profiling} The energy and execution time of apps is dependent of many variables (e.g., connectivity type, screen state, idle) and offloading can often increase energy consumption and execution time depending on these variables. To prevent such cases, mobile code offloading architectures need to be able to defer offloading functionality when it is estimated to perform worse than executing locally. App profiling can aid in such decisions, but it also incurs a significant overhead in energy and execution time. Mobile devices have limited heap sizes and tracing app functionality can often make apps unresponsive. While monitoring subsets of likely ``heavy'' functionality based on static analysis~\cite{zhang_refactoring_2012} (e.g., code loops, similarity clustering) could reduce this cost, these partitions still need to be profiled over time. Furthermore, many of the class/method relations used for selecting subsets (e.g., semantic similarity \cite{zhang_refactoring_2012}) are affected by the obfuscation patterns of apps (discussion in Section \ref{sec:obfuscation}). Instead of profiling functionality on the mobile device, INFv provides an app analysis backend (depicted in Figure \ref{fig:architecture}), in which apps are instrumented using UI automation mechanisms (pseudo-random input events \cite{monkey}). For each application an execution time and power model is derived depending on different metrics (e.g., network, cpu frequency). The backend is heterogeneous and composed by x86 and physical mobile devices, which we use to derive energy models. We rely on a similar model to the one proposed by PowerTutor \cite{zhang_accurate_2010} to predict energy consumption, which loops through different device power states separately to derive a power model through regression. It can accurately (0.8\% on average) estimate energy consumption with a low error (at most 2.5\%). While automated input generation might not cover all app code, there has been a significant amount of research towards providing better code coverage \cite{machiry_dynodroid:_2013,mahmood_evodroid:_2014}. \section{Transparent Offloading} \label{sec:offloading} \subsection{Runtime instrumentation} \label{sec:instrumentation} Once INFv fetches the partition metadata, it requires mechanisms to extend applications' functionality in order to support the offloading of the partition classes. In previous literature these mechanisms were based on specialized programming frameworks and annotations \cite{kemp_cuckoo:_2010,chen_coca:_2012,kosta_thinkair:_2012,cuervo_maui:_2010}, app repackaging or by extending OS capabilities. In many OO languages, adding additional behavior without altering the original application code can be accomplished with Aspect Oriented Programming (AOP), which has been explored in recent work \cite{zhang_refactoring_2012}. Unfortunately this solution requires a specialized compiler (e.g., AspectJ compiler) and application repackaging. This raises a challenge of distributing these repackaged apps, potentially requiring custom app stores or repositories. Another solution is to provide a custom firmware \cite{gordon_comet:_2012}, which we want to avoid in order to support more devices. Therefore, to address \textbf{Req1}, INFv needs to be able to provide a mechanism to replace or extend application functionality with minimal impact and high coverage of devices. In the literature such mechanisms have been provided by runtime patching techniques~\cite{mulliner_patchdroid:_2013} but targeted security patching in Android. Inspired by the patching literature, in INFv we use binary patching techniques to provide functionality extension mechanisms similar to those of AOP. More specifically, \emph{INFv applies a reversible patch to the OS (in this case Android) binaries in order to use a customized class loader and intercept method invocations}. The binary patch is applied only once, when installing INFv. In the case of Android, it targets the (\texttt{app\_process}), from which all launched app processes are forked (in a similar way to the Xposed framework~\cite{xposed}). By redirecting invocations and using a custom class loader we are \emph{able to provide offloading capabilities in a transparent manner that does not require app developer intervention or repackaging the app}. That said, as long as there are some common interfaces for defining hooks to intercept methods, our offloading solution should be agnostic of the OS in question or the app functionality extension mechanisms (e.g., Cydia for iOS~\cite{cydia}). \subsection{Functionality Offloading} INFv receives the partition metadata (Sec. \ref{sec:partitions}) including a representation of the app and a description of the offloadable functionality. For each partition's entry and exit points, INFv will allow the interception of its respective methods and offloading can occur depending on the current connectivity parameters (Sec. \ref{sec:decisions}). Once a target invocation is intercepted, our architecture is responsible of constructing and sending a message to the InfV network subsystem which executes it in the network in a transparent manner. Offloading routing is done using the user, device, and app ids, along with the fully qualified method name and its arguments. Additionally a version identifier is required to identify different versions of the same apps' functionality. Likewise thread granularity approaches, our thread is suspended until it receives the method invocation result, although it can also resume if there is an incoming remote invocation that is supposed to execute on the same thread. The InfV router subsystem will create and execute the class instance and respective methods in the network while also managing the instance state. Even though most mobile applications are expected to be short-lived (often imposed by screen off events and CPU sleep mode), instance state maintenance is not trivial as state has to be kept while there are still references to the instance. OO languages often provide mechanisms to deal/detect the garbage collection of objects~(e.g., Java's phantom/weak references and Objective C \texttt{dealloc} method), and so, network state can be invalidated upon such event. In our solution, classes to be offloaded are replaced with lightweight mock objects \cite{objenesis}, which, on interception, work as proxy objects. These objects are tracked using a custom weak identity hash map that allows the detection of de-referenced or garbage collected objects, which results in a state invalidation message being sent through the InfV network subsystem. Additionally, application crashes or force quit also trigger state invalidation. For simplicity, since the mobile devices can also go out of battery, state might be temporarily kept (e.g., saving VM state in non-volatile memory) in the network to provide better warranties for long lasting functionality. More advanced mechanisms for distributed collection have been proposed in the past that target some of the aforementioned challenges \cite{abdullahi_garbage_1998}. \subsection{Runtime Decisions} When a mobile device with INFv installs an app, it retrieves from a repository the app partition's metadata (classes, execution and energy predictions) and app representation for each installed app. The predicted metrics for the specific mobile device are then used as a function of the observed bandwidth, latency and device state (e.g., network type, screen state) for each remote execution call. A partition can be offloaded if the consumed energy and execution time are reduced when offloading. When offloaded, energy consumption is composed mostly by the energy per transmitted bit for outgoing and ingoing state and most of the network monitoring and decisions occur within the network itself, which measures the latency in between nodes. The Android platform already provides detailed diagnosis tools (i.e., android dumpsys) that provide many of the used metrics (e.g., CPU, screen state, foreground app, idle state, sensors, connectivity, battery state, etc) for each process. Such reports can be collected daily and reported (when idle and on wifi) to our servers on two occasions, when the app is repeatadly performing worse than expected or randomly with a low probability of sending a daily report. These metrics can be used to design a negative feedback loop and reduce the fluctuations between our estimations per device hardware and the observed values. \subsection{Network Execution} In our current prototype the network INFv subsystem executes Java processes that use a custom class loader to load the apps' classes and reflection to invoke the requested methods. Native execution is supported, provided that the class performing the Java Native Interfaces and the native binaries are offloaded as well (Sec. \ref{sec:limitations}). Similarly to the app profiling, in our experimental setup, functionality was run within an Android x86 VM to provide better support for app functionality with dependencies on the Android framework. Once launched the process remains mostly idle, listening for incoming requests from the mobile device and consuming few resources. After executing the requests and if there are no remaining references to the offloaded instances and no interaction with the mobile device for a threshold period of time, the VM can be stopped. Although our solution has some dependencies on Android, as the offloading system is mostly Java it could be easily ported to run on a pure Java Virtual Machine (JVM). In the future we would like to explore the possibility of creating a lighter Android Dalvik/ART VM capable of running over Linux containers/unikernels to reduce the resource footprint. \section{Network Subsystem} \label{sec:network} \jbnote{Again, there is massive redundant text with this and the previous 2 sections now i think?} We start this section with two fundamental control strategies, followed by a basic workload analysis on a service router, based on which we propose a proactive strategy to avoid computation congestion. Then we present the actual algorithm (C3PO) with implementation details. \subsection{Two Basic Strategies} \label{sec:strategy} Service execution consumes both CPU and memory as well as other resources such as bandwidth. Herein we focus on the first two since they are usually the most dominant resources. The goal of load balancing is achieved by strategically drop or forward the computation task to some other nodes to avoid being overloaded. However, instead of distributing load uniformly over all available nodes, a server is preferred to be executed as close to a client as possible to minimize induced latency. Centralized coordination is not ideal in a practical deployment (especially out of datacenters) due to the obvious reasons: 1) A central solver needs global knowledge of all the nodes in a network; 2) the optimal strategy needs to be calculated periodically given the dynamic nature of network and traffic; 3) there is a single point failure; 4) there might be only marginal improvement over a smartly designed heuristic. Therefore, we study two basic strategies in this paper. \begin{itemize} \item \textbf{Passive Control}: with this strategy, a node tries to execute as many services as possible before being overloaded. Whenever a service request arrives, it will be executed by default given enough resources. If the node is overloaded, the request will be passed to the next hop along the path to a server, or dropped if current node is already the last hop node in ISP networks. \item \textbf{Proactive Control}: with this strategy, a node tries to execute services conservatively to avoid being overloaded. To do so, a node estimates request arrival rate with which it can further estimate the potential consumption. If the estimate shows that the node may be overloaded, it only executes some requests and forwards the rest to the next hop neighbor with the lightest load. This strategy requires exchanging state information within a node's one-hop neighborhood. \end{itemize} Because of its simple logic, passive strategy has a very straightforward implementation. Clients can benefit from minimized service latency given no nodes are overloaded, since a service gets executed immediately at an edge router. For proactive strategy, the implementation relies on how estimate is made which we will detail in the following. Despite of being conservative, we still aim to keep the latency and algorithmic complexity low. \subsection{Workload Analysis} \label{sec:workload} A node $n$ receives service requests either from directly connected clients or neighbours. We assume that a node $n$ has CPU capacity $c'$ and memory capacity $m'$. For a specific service $f_j$, we denote its average CPU and memory consumption as $c_j$ and $m_j$ respectively. In practice, both can be easily measured by tracking a service execution. We also assume the execution time of $f_j$ follows an exponential distribution with its mean value equal to $t_j$\jbnote{any cite that would justify this assumption? Would be nice if possible.}. The requests for service $f_j$ can be viewed as a Poisson processes with arrival rate $\lambda_j$. We can easily recognise that the process is a typical \textit{birth-death process}. Because the joint process of multiple Poisson processs is also Poisson, the aggregated requests of all services form another well-defined birth-death process with the birth rate as $\lambda = \sum_{\forall j} \lambda_j$ and death rate as $\mu = \sum_{\forall j} \frac{1}{t_j}$. We herein focus on this aggregate request stream. To calculate average workload, for any given time, we need to estimate the average number of simultaneously running services on node $n$, denoted as $l$. This is equivalent to calculating the average queue length in a simple $M/M/1$ queueing system, where the clients in a queue represents the services running concurrently on a node by applying a multiprogramming model. Herein we consider a stable system where $\lambda < \mu$ to prevent a queue from growing infinitely long to overload a node. We will show later how a proactive strategy is able to keep the system stable. We have assumed that one CPU is allocated for service execution hence we choose to use $M/M/1$ model in this paper to simplify the discussion. However the analysis can be easily extended to $M/M/C$ model to analyse a multi-core system. Let $p_j$ denote the normalised popularity of $f_j$ derived from all the requests observed by $n$, then $p_j = \frac{\lambda_j}{\lambda}$ and note that $\sum_{\forall j} p_j = 1$ by definition. The average CPU consumption is $c'' = \sum_{\forall j} p_j \times c''_j$ and average memory consumption is $m'' = \sum_{\forall j} p_j \times m''_j$. If we let $\rho = \frac{\lambda}{\mu}$ (i.e., utilisation rate), then we have $l = \frac{\rho}{1 - \rho}$ by applying a stationary analysis on $M/M/1$ model. Therefore we can calculate the overall workload induced by executing services in a straightforward way: namely $l \times c''$ for CPU load and $l \times m''$ for memory load. \subsection{Probabilistic Execution} \label{sec:prob} To avoid overloading a node, we need to make sure the workload is less than $n$'s actual capacity. As we have shown, workload is directly controlled by the queue length $l$, which can be further tuned by probabilistically selecting some requests in a stream to execute and forwarding the rest to the next hop. For each service request, if we let node $n$ execute a service with probability $q$, and $q \in [0,1]$ follows a uniform distribution. According to basic queueing theory, the resulting sub-process forms another well-defined birth-death process, with a new birth rate $q \times \lambda$ and the same death rate $\mu$. Therefore the new sub-process has a new utilisation rate equal to $q \times \rho$. To calculate $q$, we can simply perform the following derivations by letting the induced load (e.g., for CPU) $l \times c''$ less than the capacity $c'$. \begin{align} l \times c'' < c' & \Longrightarrow \frac{q \times \rho}{1 - q \times \rho} \times c'' < c' \\ & \Longrightarrow \rho \times q < \frac{c'}{c' + c''} \\ & \Longrightarrow q < \frac{c'}{c' + c''} \times \frac{\mu}{\lambda} \end{align} The formula has a very intuitive explanation: if services can be executed faster on average (i.e., higher death rate $\mu$), node $n$ increases $q$ in order to serve more requests by maintaining a longer queue; otherwise $n$ decreases $q$ to reduce the queue length. If requests arrive faster (i.e., higher birth rate $\lambda$), the node also decreases $q$ to keep the number of simultaneously running services low. Similarly, we can perform the same calculations for memory constraint $m'$. Eventually, we set $q$ with the following formula. \begin{align} & q = \max\{ \min\{ \frac{c'}{c' + c''}, \frac{m'}{m' + m''} \} \times \frac{\mu}{\lambda}, 1\} \label{eq:0} \end{align} The formula above essentially indicates that the final $q$ is decided by the first bottleneck in a system, either CPU or memory in our case. Also, $q$ is capped by $1$, indicating that an underutilised system will simply accept all the requests. \subsection{Proactive Control - C3PO} \label{sec:congestion} We present an implementation of proactive control in Algorithm~\ref{algo:1}, namely \textit{C3PO} -- Computation Congestion Control (PrOactive). The algorithm consists of two major functions: \textbf{on\_arrival($\cdot$)} (line 1--10) is called whenever a service request arrives; and \textbf{on\_complete($\cdot$)} (line 12--21) is called whenever a service execution is completed. The notations used in the algorithm follow the same definition as those in the previous text. By keeping track of CPU usage $c''$, memory usage $m''$, execution rate $\mu$, and request arrival rate $\lambda$, the previous analysis shows how to control the workload by tuning execution probability $q$. However, maintaining a complete history of these statistics can be very expensive. In the actual implementation, we use four circular buffers of size $k$: 1) buf$_\lambda$ for the timestamps of the most recently arrived requests; 2) buf$_\mu$ for the execution time of the most recently finished services; 3) buf$_{c''}$ and 4) buf$_{m''}$ for CPU and memory usage of the most recently finished services. \begin{algorithm}[!tb] \caption{C3PO - Proactive Computation Control} \label{algo:1} \begin{algorithmic}[1] \STATE{void \textbf{on\_arrival} (request $r$):} \STATE{\quad buf$_\lambda$[$i$] $\leftarrow$ timestamp ($r$)} \STATE{\quad $\lambda \leftarrow$ mean\_rate (buf$_\lambda$)} \STATE{\quad $\Delta \lambda \leftarrow$ max$(0, \lambda - \lambda')$} \STATE{\quad $\lambda \leftarrow \lambda + \Delta \lambda$} \STATE{\quad $q \leftarrow$ \textbf{eq.\ref{eq:0}} ($\lambda, \mu, c', c'', m', m''$)} \STATE{\quad \textbf{if} draw\_uniform ([0,1]) $ < q$ \textbf{then} execute ($r$)} \STATE{\quad \textbf{else} forward\_to\_lightest\_load\_node ($r$)} \STATE{\quad $i \leftarrow (i+1)$ mod $k$} \STATE{\quad \textbf{if} $i == 0$ \textbf{then} $\lambda' \leftarrow 0.5 \times $($\lambda' + \lambda - \Delta \lambda$)} \STATE \STATE{void \textbf{on\_complete} (service $s$):} \STATE{\quad buf$_\mu$[$i$] $\leftarrow$ execution\_time ($s$)} \STATE{\quad buf$_{c''}$[$i$] $\leftarrow$ cpu\_consumption ($s$)} \STATE{\quad buf$_{m''}$[$i$] $\leftarrow$ memory\_consumption ($s$)} \STATE{\quad $i \leftarrow (i+1)$ mod $k$} \STATE{\quad \textbf{if} $i == 0$ \textbf{then}} \STATE{\quad \quad $\mu \leftarrow 0.5 \times $($\mu +$ mean(buf$_{\mu}$)$^{-1}$)} \STATE{\quad \quad $c'' \leftarrow 0.5 \times $($c'' +$ mean (buf$_{c''}$))} \STATE{\quad \quad $m'' \leftarrow 0.5 \times $($m'' +$ mean (buf$_{m''}$))} \STATE{\quad forward\_result (s)} \end{algorithmic} \end{algorithm} With these four circular buffers, we can calculate the recent values of the parameters in eq.\ref{eq:0}. We decide to use fixed buffer instead of fixed time window to prevent the memory usage of Algorithm \ref{algo:1} from being subject to service arrival/completion rate. Parameter $k$ represents a trade-off between stability and responsiveness. Larger $k$ leads to more stable estimates whereas smaller $k$ indicates higher responsiveness of a strategy to the changes in two metrics (i.e., $\lambda$ and $\mu$). Line 2--6 calculate the execution probability $q$. The algorithm also maintains a variable $\lambda'$ for the average arrival rate of previous $k$ requests, so that we can calculate the variation in $\lambda$ as $\Delta \lambda = \lambda - \lambda'$. It is definitely worth emphasising line 4 and 5: when $\Delta \lambda > 0$, it indicates an increase in request arrival rate, then C3PO will enter into conservative mode. In conservative mode, C3PO updates $q$ at line 6 by plugging $(\lambda + \Delta \lambda)$ as arrival rate in eq.\ref{eq:0} rather than plugging original $\lambda$. In such a way, C3PO "pessimistically" estimates the arrival rate will increase at the same rate $\Delta \lambda$ in a near future. If $\Delta \lambda \leq 0$, C3PO operates in normal mode. In some sense, "being proactive" is achieved by "being conservative" when noticing a potential increase in resource consumption. Although $\lambda$ needs to be calculated at every request arrival (line 3), we can optimise the performance by using another variable $x$ to keep track the sum of arrival intervals. If we further let $y \leftarrow \text{buf}_\lambda[(i+1) \text{ mod } k] - \text{buf}_\lambda[i]$ and $z \leftarrow \text{timestamp}(r) - \text{buf}_\lambda[(i-1) \text{ mod } k]$ before performing line 2, then mean rate can be calculated by $\lambda \leftarrow (x - y + z]) / (k - 1) $. Because all $x,y,z$ can be updated with $\mathcal{O}(1)$, this reduces the complexity of "mean\_rate" function from $\mathcal{O}(k)$ to $\mathcal{O}(1)$ by avoiding traversing through all the timestamps in buf$_\lambda$. Other parameters except $\lambda$ are updated only periodically in both functions (line 10, 18-20). We apply an ARMA (AutoRegressive Moving Average) model with exponential mean when updating these parameters. Both history and recent measure are given the equal weight 0.5. To keep the code short and easy to understand, we did not perform further optimisations in Algorithm \ref{algo:1}. \section{Design Requirements and Challenges} \label{sec:arch} The overall INFv architecture is shown in Figure \ref{fig:architecture}. The three different logical subsystems are separated by dotted lines. First subsystem profiles apps to capture good offloading candidates based on their energy and computation characteristics then devises offloading strategies. The second subsystem runs both on top of a user device and its counterpart on a virtual machine on a generic machine in the network (NFV). On user devices, it monitors devices properties (e.g., screen state, connectivity, latency, etc) and makes offloading decisions by using the strategy provided by the first subsystem. On network devices, it invokes the function calls and returns the results. Finally, the third subsystem runs on the network nodes and is responsible for caching functionality and balancing the computation load. In the following sections we identify the design requirements and challenges. Then we present the overall system architecture to illustrate its basic functionality. \begin{figure} \centering \includegraphics[width=0.45\textwidth]{figures/architecture/overall.pdf} \caption{Design of INFv overall system.} \label{fig:architecture} \end{figure} \subsection{Profiling Subsystem} \label{sec:profiling} In mobile code offloading, apps are typically partitioned into a set of functionality to execute locally and another to execute remotely. Such system needs to detect good candidates to offload, e.g., based on energy consumption and execution time. The selection is done via static and dynamic analysis on apps' behaviors (a.k.a., profiling apps). Since profiling per se is energy consuming and can degrade devices' performance, we devise our first requirement: \textbf{Req1)} \emph{App profiling should have minimal impact mobile device energy consumption and performance.} In our design most of the profiled metrics and estimations are performed remotely (INFv servers) for a given mobile device. INFvs profiling subsystem consists of an app analysis cluster and repository containing these apps' partition functionality as well as their respective metadata. This metadata includes the app representation (e.g., information regarding app structure and method invocations) and estimated resource usage (e.g., energy, execution time). The app analysis cluster has a set of schedulers that launch VM instances to analyze apps then stores the respective results in the repository. App analysis is done through static (i.e. parsing decompiled bytecode) and dynamic analysis of the apps. The first is used to retrieve the metadata app representation and do an initial prediction of possible partitions (e.g., pinning to execute locally functionality that uses devices hardware). The second is used to benchmark app partitions and to retrieve functionality execution time, parameter state and energy consumption (i.e., partition's metadata), which is used for performing informed offloading decisions. \subsection{Offloading Subsystem} With the app behavior predictions and offloading strategy in place, an offloading subsystem is required for instrumenting and modifying app behavior to support offloading. One of our design principles is to minimize the adoption barrier of the system, i.e., it should not impose any modifications on existing applications such as application repackaging, custom firmware flashing or custom app stores. Therefore we devised our second requirement: \textbf{Req2)} \emph{It must have minimal impact on the ecosystem.} Mobile device users should be able to run unmodified apps downloaded from the official app stores. Since we do not repackage existing apps to avoid introducing any difficulties in adopting our solution, remote resource execution should be done in an automated fashion and so we reach our third requirement. \textbf{Req3)} \emph{It must enable apps to make use of remote resources in a transparent and efficient manner.} With our design, the mobile device fetches the profiling information to perform offloading decisions without affecting user experience and performance. As a result our design focuses on allowing the automation of the offloading process, without requiring programming frameworks or manual annotation of functionality. \begin{figure} \centering \includegraphics[width=0.25\textwidth]{figures/architecture/mobile.pdf} \caption{Design of INFv End Device system. } \label{fig:mobilearch0} \end{figure} As shown in Figure \ref{fig:mobilearch0}, the INFv mobile ecosystem consists of a stock mobile OS (discussion in Section \ref{sec:security}), an unmodified application to be offloaded and a per device INFv network stub. \liang{FIX: calling it network module is confusing ... would network stub make more sense?}\manote{i think stub makes sense here, good point.} The per device INFv network module is a standalone process responsible for the monitoring of installed apps and fecthing their partitions metadata. It also handles the offloading requests originating and destined to the mobile device apps, abstracting the network interaction. The INFv monitor is a binary patch applied to apps processes which provides the execution interception mechanisms. Using the partitions metadata, i.e., resource usage estimations and functionality set to be offloaded, the INFv monitor can decide whether an app functionality should be offloaded or not reducing the overall energy consumption and execution time of the app. \subsection{Network Subsystem} Functionality execution consumes multiple resources on a network device, especially CPU cycles for computation intensive tasks. It introduces a new type of "congestion" in a network which we refer to as \textit{"computation congestion"}. Different from conventional traffic congestions which are avoided by the cooperation of both communication ends, in-network services do not necessarily impose a point-to-point paradigm. Also different from the classic load balancing problem in the cloud, which often has a regular structure (i.e., regular network topology, central coordination, homogeneous configurations, uniform demands, and etc.), the situation in an ISP network is often more complicated. So for the second subsystem we highlight the following design requirements: \textbf{Req5)} \emph{It must support arbitrary network topologies and node heterogeneity.} Not only can the ISPs topology be irregular when compared to the cloud, but it also has heterogeneous node configurations (including NFV nodes)\jbnote{citation?}. The functionality demand distribution can be highly skewed hence resources in a neighborhood needs to be well utilized, so we define our last requirement: \textbf{Req6)} \emph{It must adapt to demand and balance load in the network.} Additionally, as central coordination can incur extra costs (e.g., dedicated network services) and can reduce responsiveness of the nodes hosting these functionalities, our design will also be decentralized. Next sections provides more details on each of INFv's subsystems. The network subsystem is responsible for receiving clients' requests, performing workload balancing, and scheduling the execution of offloaded functionality. This subsystem is fully decentralized and implements a ``computation congestion control'' algorithm that can pro-actively distribute functionality in a nodes' neighborhood. The INFv mobile end system connects to the closest INFv-enabled network node by explicit registration. Service discovery can be done by using either a DNS-like service or ad-hoc discovery. The connected node maintains a message queue system to deliver messages to and from the mobile device. When a new offloading request arrives at the queue, based on the availability (cache) of the functionality and the current workload, the request may either be executed locally or offloaded to a neighbor. In both cases, a new VM should be spawned to execute the request. This VM runs a lightweight process that loads the app functionality (e.g., classes, native binaries) and executes the request invocation call. \section{Design Goals \& Architecture} \label{sec:arch} \begin{figure} \centering \includegraphics[width=0.45\textwidth]{figures/architecture/newoverall} \caption{Design of INFv overall system, the three subsystems are divided with gray dashed lines.} \label{fig:architecture} \vspace{-5mm} \end{figure} Based on the limitations of previous work, and keeping in mind the recent availability of in-network resources, we identified four major design requirements for INFv as well as their corresponding challenges. \textbf{Instrumenting apps:} App instrumentation is needed for profiling and providing offloading capabilities. How can apps be modified without performing app repackaging, using specialized compilers, custom OS or app stores? \textbf{Understanding apps:} With instrumentation in place, how to detect which functionality is consuming the most energy or executing for longer? Can we analyze apps without incurring a performance penalty on mobile devices? \textbf{Offloading functionality:} How to enable apps to make use of remote resources in a transparent and efficient manner with minimal adoption cost? Can offloading adapt to a dynamic network environment and still ensure its energy and performance benefits? \textbf{Caching functionality:} How to cache functionality in a network, adapting to demand and reducing latency, even for arbitrary network topologies and heterogeneous nodes? \textbf{Deployment assumptions:} Based on recent/expected NFV/MEC adoption by ISPs, we believe these standards will soon be widely available in the ISPs networks. More specifically, and in compliance with the MEC proposal, placed in the Radio Access Network (RAN), where traffic offloading functions can be implemented to filter packets based on their end-point~\cite{mec,lipa} (IP protocol). The overall INFv architecture that addresses these challenges is depicted in Fig.~\ref{fig:architecture}. It is divided in three different logical subsystems (separated by dashed lines), each addressing the aforementioned challenges. The leftmost subsystem (Section~\ref{sec:profiling}) profiles and analyzes apps. The rightmost subsystem (Section~\ref{sec:offloading}) provides the on device offloading capabilities. It runs on the user device and executes code on a remote VM in the network. Finally, the third subsystem (Section~\ref{sec:network}) runs on the network nodes (NFV) and is responsible for caching functionality and balancing the computation load. In the next sections we detail each of them and describe their technical challenges. \section{Conclusion \& Future work} \label{sec:discussion} Battery is a huge constraint for mobile devices and the ever growing demands of computation on limited capacity are unlikely to disappear any time soon. Meanwhile, in-network storage and computation resources are growing. We proposed INFv to exploit in-network resources for mobile function offloading. We described its data-driven design and implementation based on a large scale analysis of a real app market. Our evaluation demonstrates that INFv's non-intrusive offloading technique can significantly improve mobile device's performance (up to 6.9x energy reduction and 4x faster) and effectively execute functionality in the network while reducing latency. Our analysis shows the potential for functionality caching and popular app offloading, while also providing interesting insights into Android apps' obfuscation and composition. INFv is a working system and many of its components are open-sourced~\cite{broker,droidsmali,lp}. There are some limitations and caveats which deserve further investigation in the future. First, INFv requires attention to the security and privacy of communication and offloaded functionality. While it provides isolation and detects the use of critical OS APIs, in the future we will consider techniques for detecting vulnerabilities/malware~\cite{mariconti2016mamadroid, 8514191} and access to privacy sensitive information~\cite{enck_taintdroid:_2014}. Although it does not require a custom OS, a one-time root is required, which can be disabled after install. If deployed by an ISP, it can be pre-installed on devices or installed in stores. For other scenarios, either root would be required or, an existing vulnerability could be leveraged to install INFv and secure the device~\cite{mulliner_patchdroid:_2013}. Second, UI automation might not cover all app code and its generated state might not be representative of real user's input. A significant amount of work exists on improving coverage~\cite{machiry_dynodroid:_2013,mahmood_evodroid:_2014, choudhary_automated_2015, chimp} and we are looking to further improve our dynamic analysis by exploiting crowdsourcing platforms~\cite{crowdflower} to test apps with real users. Additionally, an iOS implementation should be possible using similar interception mechanisms~\cite{cydia} and static analysis can be accomplished by dumping the decrypted apps from memory~\cite{dumpdecrypted}. We also plan to explore different interception techniques to better support native code~\cite{cydia}. Finally, we are working to deploy a small-scale real-user test in the coming year to gain valuable feedback to further improve INFv. \section{Architecture Evaluation} \label{sec:eval} \begin{figure} [t!] \includegraphics[width=8cm]{figures/offloading/last} \caption{Experimental setup.} \label{fig:last} \vspace{-5mm} \end{figure} We first describe how a typical deployment of INFv then present thorough evaluations demonstrating that INFv delivers on its promise of energy savings and faster app execution. \textbf{INFvs use case}: \textbf{1)} The profiler analyzes apps and computes partition sets; \textbf{2)} The user equipment (UE) installs apps and the local INFv installation downloads their partition metadata; \textbf{3)} The UE launches apps, and if the network conditions (bandwidth \& latency) are favorable, the execution is offloaded; \textbf{4)} the INFv network system forwards offloading request to an available backend, and finally, \textbf{5)} the backend executes requests. \textbf{Our experimental setup} is shown in Fig.~\ref{fig:last}. Both INFv's network subsystem and the MQ system are run within docker containers. The selected MQ protocol was MQTT (optimized for mobile devices) and our messages are encoded with protocol buffers~\cite{protobuf}. The app profiler utilizes hardware-level virtualization (Android x86) to profile the user apps. Power measurements are taken with a Monsoon Power Monitor and latency is emulated using \texttt{TC NetEm} (Traffic Control Network Emulation). In all experiments, phones are factory reset with Android 4.4, no Google account, and INFv pre-installed. In Section~\ref{sec:evaluation:facedetect} and~\ref{sec:evaluation:linpack} we used a Galaxy S2 (i9100) and offload to an Intel Q6600 (4GB of RAM and a 100 Mbit fiber connection). Section~\ref{sec:runtimeeval} uses a more up-to-date setup: a Galaxy S5 and an Intel i7 4790K (16GB RAM, 300 Mbit fiber). Additionally, while 3/4G setups use real mobile networks, in WiFi the UE and backend share a common WiFi access point. \textbf{The offloaded apps} were \emph{Linpack}~\cite{lp}, \emph{FaceDetect}, \emph{QuickEditor}~\cite{quickeditor}, and \emph{QuickPhoto}~\cite{quickphoto}. \emph{Linpack} is computationally intensive and \emph{FaceDetect} has high state transmission costs and have been widely used to benchmark MCO performance~\cite{kosta_thinkair:_2012,zhang_refactoring_2012,Shi:2014:CCO:2632951.2632958}. \emph{QuickEditor} and \emph{QuickPhoto} both use Google Drive, and although not computationally intensive, they exemplify 1)~how INFv can target common functionality across apps and 2)~how INFv can provide functionality otherwise absent from a device. Each app is standalone, i.e., no client/server counterpart, and has no special design decisions or implementation to facilitate code offloading. \rthree{The evaluation is completely underwhelming: you select two outliar apps that are obvious offload candidates (linpack is ridiculous if you ask me) and only evaluate those in a simple setup; this part however is, more or less, completely covered by previous work and only shows your system works. The second part is run entirely in simulation and I can't really take anything interesting away from it. This two parts feel almost unrelated, and it doesn't help the paper at all.} \rone{Evaluation is based on a couple of home grown apps. (It does not show the full capability of the system.)} \manote{Clearly users are not impressed by our two apps. In our previous paper we add plus a text editor and patch including a security app. Perhaps I can look into one of Tarkoma students \footnote{https://github.com/huberflores} which has a couple of apps used in their paper such as NQueens and MiniMax Chess. They kinda cheated as they basically just did two apps for client and server, no real automation or anything. But at least the chess shows the source algorithm. Regarding the second comment, well this is an extremly complex process and there is a reason why all papers work with opensource apps. If we are to go with a real app, i would prefer opensource and we need to know exactly what to offload.} \subsection{Impact of Code Partitions} \label{sec:evaluation:linpack} \begin{figure} [t!] \includegraphics[width=0.47\textwidth]{figures/offloading/offloading} \caption{Benefits of mobile code offloading for two apps: Linpack and FaceDetect.} \label{fig:offloadbenefits} \vspace{-5mm} \end{figure} Linpack measures a system's floating point computing power by randomly generating a dense matrix of floating point numbers on $[-1, 1]$ and performing LU decomposition for $M$ cycles (iterations). We added support for multi-threading, a feature many previous automated offloading architectures do not or only partially support~\cite{cuervo_maui:_2010,chun_clonecloud:_2011,kemp_cuckoo:_2010}. We experimented using two different offloading partition sets. For the first (\emph{All}), GN provides two partitions that minimize network communication: 1)~a partition that interacts with the UI, therefore invalid for offloading, and 2)~a valid partition that performs computation, i.e., all computation is performed remotely and there is almost no communication costs as threading occurs on the backend. The second (\emph{Lin}) represents the worst case scenario by offloading individual classes (i.e. $N$ partitions where $N$ is the number of classes in the app). For \emph{Lin}, only the Linpack class and calculations are offloaded, and thus, threading, as well as pre- and post-cycle processing, occurs on the client with a higher communication penalty. For this experiment (and the next) we perform unconditional offloading (i.e. no runtime decisions) to depict the partition trade-offs. Fig.~\ref{fig:offloadbenefits}A plots the speed up for the Linpack benchmark running 4 threads, showing that INFv provides the expected computational performance benefits of code offloading. For the \emph{All} partition, INFv achieves a speed up over 4.0x on both WiFi and 3G since there is almost no communication. When the more restrictive partitioning (\emph{Lin}) is used, the WiFi experiment achieves a 1.57x speed up. However, the 3G experiment shows \emph{reduced} performance (0.73 speed up), due to the 3G latency and the high frequency of communication (up to 40 messages, 10 per thread, for each cycle). Next, Fig.~\ref{fig:offloadbenefits}B plots the distribution of power consumption for both partition sets. The local execution with 2 and 4 threads had a median power consumption of 3 and 6W, respectively; for offloaded executions it was below 2W. For the WiFi \emph{All} partition, the quartiles show a tight distribution of power consumption and, since the UE was mostly idle with a mean energy consumption close to the observed Android background activity (dashed line), the overall energy consumption was reduced by up to 4 times. Offloading without modularity optimizing can result in reduced performance in high latency networks despite the power consumption reduction. Taken together, Fig.~\ref{fig:offloadbenefits}A and~\ref{fig:offloadbenefits}B, show that INFv's MCO provides real benefits but also demonstrates the trade-offs of different partitionings. \subsection{Cost of State Synchronization} \label{sec:evaluation:facedetect} The FaceDetect (FD) app, which finds the coordinates of faces in images, is useful for measuring the trade-offs between data transfer and computational speed up. The offloaded partition contains the classes interacting with the face detection APIs and the client device just sends the underlying Android Bitmap object and receives an array of coordinates. The execution time and power were measured from when the app starts up to when the results are drawn on the screen. To test the impact of data transfer, we use multiple images from the AT\&T face database~\cite{facedb} ranging in size from 0.02MB to 1.2MB. Fig.~\ref{fig:offloadbenefits}D plots the execution time as a function of image size and we can see that local execution is faster for images $\leq$ 0.07MB. This is because detecting faces in small images does not have enough computational cost to outweigh the communication costs of offloading. For larger images, the WiFi communication costs are compensated by the VM processing speed. For example, with the 1.2MB image, using WIFI has an execution speed 1.45x faster, but for a 0.2MB image offloading was 3.86x slower. Unfortunately offloading was never justified (in terms of execution time) over 3G due to its high latency. Fig.~\ref{fig:offloadbenefits}C plots the total Joules FaceDetect consumed, not counting baseline OS consumption. We note that for small images ($\leq$ 0.25MB), local execution results in less power consumption than 3G, although after this point, offloading over 3G saves energy. Offloading over WiFi results in lower power consumption than local execution for all but the smallest image in the dataset. For example, an image with 1.2MB consumes 1.9x less battery when offloaded via 3G connectivity and 6.9x less battery if offloaded via WiFi. In the case of WiFi, the decreased execution time due to the VM processing power is the significant factor in energy savings. The 3G energy consumption is higher than WiFi for two reasons: 1)~there is additional radio overhead for 3G and 2)~the total execution time is larger due the higher RTT. The main take away from these experiments is that, as in the Linpack experiments, INFv's offloading engine provides both computational and energy benefits. However, if there is substantial interaction between local and offloaded objects that involves passing a lot of data, it can result in a net \emph{loss} of performance. In Section~\ref{sec:runtimeeval} we show how profiling metadata can be used to prevent such scenarios. \subsection{Responsiveness to Jitter} \label{sec:jitter} \manote{we need here some short sentence to connect it with previous experiments} \begin{figure} [t!] \includegraphics[width=8cm]{figures/jitter} \caption{Comparison of two control strategies by examining two adjacent routers: client $\rightarrow$ router $n_1$ $\rightarrow$ router $n_2$ $\rightarrow$ server. Two jitter are injected at time 40 ms and 70 ms. $x$-axis is time (ms) and $y$-axis is normalized load. Red numbers represent the average load during a jitter period.} \label{fig:3} \vspace{-5mm} \end{figure} Next, we study how INFv's control strategies respond to sudden increases in workload (i.e., jitter). We setup a toy network topology composed of a client, two routers ($n_1$ and $n_2$), and a server (acting as a catch-all for requests not handled by $n_1$ or $n_2$); i.e., client $\rightarrow$ router $n_1$ $\rightarrow$ router $n_2$ $\rightarrow$ server. We simulate the client's request flow at a stable rate of $\lambda = 1000/s$ but inject two instances of jitter at $6\lambda$ for 10ms at time 40ms ($j_1$) and 70ms ($j_2$). Fig.~\ref{fig:3} plots the workload over time when the routers use a passive strategy (PAS$n_1$ and PAS$n_2$ in the first two rows) vs. a proactive strategy (PRO$n_1$ and PRO$n_2$ in the second two rows). The two right most columns zoom in to the period when $j_1$ and $j_2$ have just occurred. For passive control, PAS$n_1$ takes most of the load (88\%), exhibiting consistent behavior for both $j_1$ and $j_2$. However, the proactive routers show an interesting variation. For $j_1$, although PRO$n_1$ successfully offloads 31.8\% of load to PRO$n_2$, it also experiences high load for a period of 2ms (row 3, column 2). After $j_1$, however, PRO$n_1$ enters a conservative mode. Thus, when $j_2$ arrives, the load curve on PRO$n_1$ is much flatter with no clear peak appearing at all. Instead, it proactively offloads more tasks to PRO$n_2$, resulting in PRO$n_2$ absorbing about 36.7\% of the load from $j_2$. Between 80 and 130ms we see some load still transferred from PRO$n_1$ to PRO$n_2$ because PRO$n_1$ remains in conservative mode. After 130ms, PRO$n_1$ returns to normal mode and the load on PRO$n_2$ goes to 0. \begin{figure}[t!] \centering \includegraphics[width=0.45\textwidth]{figures/offloading/profiling} \caption{Power consumption distribution (A \& B) for 20 executions over 4G, with and without INFv. Crosses represent the median. In C the dashed line represents INFvs' consumed power versus the local execution (continuous).} \label{fig:profile} \vspace{-5mm} \end{figure} \rone{How accurate is your estimation of energy consumption? It seems particularity difficult given the result of figure 8.A that shows very high variance in the amount of power consumption with INFv.} By checking the second and third columns, we are able to gain an even better understanding on what actually happens when jitter arrives. For both $j_1$ and $j_2$, the proactive strategy responds faster; i.e., $n_2$'s load curve rises earlier and faster. For $j_2$, the proactive strategy responds even faster since PRO$n_2$ is already in conservative mode: PAS$n_2$ only starts taking load at 74 ms, 4 ms later after the $j_2$ arrives at PAS$n_1$. The major take away here is that INFv is highly responsive to workload jitter due to its network subsystem. \subsection{Runtime decisions} \label{sec:runtimeeval} \rtwo{It would be good to compare the performance of INFv when offloading is carried out to the cloud rather than ISP. How much latency does it really buy us given the excellent connectivity of large public clouds?} \begin{figure}[t!] \centering \includegraphics[width=0.45\textwidth]{figures/offloading/jouleExecCombined} \caption{Energy and execution time of FaceDetect execution with INFv enabled. Crosses represent the median. Values are normalized by the mean values of local execution.} \label{fig:latency} \vspace{-5mm} \end{figure} Finally we evaluate how INFv behaves in 4G, with and without additional induced latency, to stress test INFv's runtime decisions. Fig.~\ref{fig:profile} A) and B) show the observed energy consumption distribution with and without INFv, for 20 experiments using a 1.2MB image~\cite{facesimage}. In C) we depict the power over time for three of these experiments. While the execution without INFv (continuous line), consumed over 2 W for most of the experiment time ($\mu \approx 11.57s$), the execution with INFv (dashed line), is mostly comprised of two spikes in energy consumption. These two spikes represent two distinct phases: 1) image transmission and 2) retrieving and displaying the results; and are dependent on the current connectivity state, e.g., transition to a 4G connected state. In A) and B) we show the power distribution for the 20 experiments, with and without INFV, respectively. The power distribution in A) has an higher variance but the majority of the observations are lower than 2W ($\mu \approx 1.35W$ and within a 95\% confidence interval of 0.139W \manote{should we keep the confidence interval or mean is enough?}) and its execution is up to 2,8 times faster ($\mu \approx 2.3$ times) than the execution without INFv, which results in over 66\% energy savings over the 20 executions (idle time excluded). While UEs are becoming more powerful, so are commodity processors and mobile networks, demonstrated by the execution speed improvements in this experiment compared to the 3G experiments (Section~\ref{sec:evaluation:facedetect}). Fig.~\ref{fig:latency} shows the impact of latency on execution time and energy consumption of FD over 120 executions. The observed latency consists of the latency induced on the backend network interface (TC in Fig.~\ref{fig:last}) and the real 4G latency.\footnote{Note that while 300ms might be unusual in 4G, it is quite common in 3G.} The energy consumption is always lower when offloading, we see a reduction in the savings from close to 70\% less energy (no induced latency) to 40\% due to higher latency. A major takeaway here has to do with in-network vs. cloud deployment: the overall LTE round-trip time (RTT) for offloading to a cloud instance is often over 100ms\footnote{We measured a mean latency of 109.4 and 112.2ms from a mobile device with LTE in Barcelona, Spain to Amazon EC2 regions with the lowest latencies (Frankfurt, \textit{eu-central-1} and Ireland, \textit{eu-west-1}).}; quite high compared to hosting the functionality at the ISP's Radio Access Network (RAN) where devices see only 15-45ms RTT~\cite{laner_comparison_2012}\footnote{we confirmed the lower bound LTE latency values using an USRP transceiver~\cite{B210} and a conservative software-based LTE protocol stack~\cite{openair}.}. I.e., deploying to the RAN can reduce latency by 58.9\% to 86.7\% (over 90ms difference). Since our results indicate that a 70ms variation in latency can incur up to 24.5\% and 21.6\% increase in the average execution time and energy consumption, respectively, hosting functionality in-network brings clear benefits. Further, reducing latency via in-network deployment also increases the set of viable candidate apps for offloading to include those that are particularly latency sensitive (e.g., games). \begin{figure} \centering \includegraphics[width=0.35\textwidth]{figures/offloading/TimeEnergy} \caption{Energy consumption vs. execution time of FaceDetect using INFv under varying latency.} \label{fig:lastexp} \vspace{-5mm} \end{figure} Finally in Fig.~\ref{fig:lastexp} we plot the execution time versus consumed energy for the FD app with the \emph{INFv offloading decision model}. The RM keeps a rolling window of observed latency (last 3) to the server, which is updated whenever there is no offloading communication (i.e., no threads paused or pending messages) for $>30s$ and the screen is on. There were 260 experiments over a $>7$ hour period (100ms periods). We vary the latency (from 0--600ms, with 50ms steps) 30s after each experiment starts. INFv decides whether to offload the face detection partition based on the connection properties at runtime (latency and bandwidth vs. transmitted state) and the profiling estimates (i.e., energy and execution time). Therefore, when executed locally, its behavior should resemble the experiments in Fig.~\ref{fig:profile}A. Note that the majority (86.7\%) of local execution times fell within one $\sigma$ (the dark gray area in the graph) from those of the experiments in Fig.~\ref{fig:profile}A, and over 96\% of the observed values within two $\sigma$ (light gray). Moreover, 99\% of local executions' energy consumptions were within one $\sigma$. \manote{I think this, and the previous observations on the confidence intervals, answer reviewer 1\#12} There were 4 executions that took \emph{longer} than the local experiments, however, they are an artifact of the periodicity of the latency measurements: INFv was not able to detect the increase in latency prior to making an offloading decision. This is important because such cases can occur due to changes in connectivity (e.g., 4G to 3G) or ISP service degradation. While such impact can be reduced by increasing measurement periodicity, the first is already detected by monitoring changes in the default network interface. Ultimately, it is clear that, even in the presence of high latency variance, \emph{INFv detected when computation should not be offloaded and energy consumption was greatly reduced for all offloaded experiments}, performing faster than the worst local execution 98.5\% of the time and faster than all local executions 93.2\% of the time. \subsection{Offloading Popular Libraries and Apps} \label{sec:offloadable} \begin{figure} [] \includegraphics[width=8cm]{figures/offloading/gn} \caption{Percentage of offloadable code per number of Girvan-Newman partitions. Black circles represent the optimal partition given by the louvain algorithm.} \label{fig:gn} \vspace{-5mm} \end{figure} To evaluate INFv's support for the most popular libraries and apps, we offloaded an ubiquitous library and performed a partitioning analysis of the top free apps in the GP market. First, we studied the top 2.5K apps and found that 76.4\% of apps use Google Mobile Services (GMS). We chose two applications that use a common GMS service -- Google Drive~(GD). The first, QuickEditor~\cite{quickeditor}, is a text editor that allows users to create, open, and edit text files stored in their GD. The second, QuickPhoto~\cite{quickphoto}, uses the device's camera to take pictures and upload them to GD. To support both apps in a device \emph{without GMS installed}, 26 GMS classes were offloade , none of them app specific (code available at~\cite{gmsreplace}). With our in-network solution the number of extra network hops to provide GMS functionality are minimal since GD calls already trigger communication which is forwarded through the RAN. The network communication overhead is also quite minimal: around 46, 50, and 10B, respectively, to create a class, invoke a method, and receive a response. Second, to address the concern of how many apps are actually offloadable we inspected the top 24 apps regarding INFv's partitioning and validation mechanisms (Section~\ref{sec:partitions}). Our first finding was that only 6\% of app classes extend UI or hardware related classes. While all other classes could potentially be offloaded, we want to minimize the communication between local and offloaded code. To this end, we used our dynamic analysis platform to execute the apps for 5 minutes each and extract their runtime call graphs to discover valid offloading partitions (i.e., GN communities). Previous work~\cite{choudhary_automated_2015} has shown this to be a reasonable interval to achieve high coverage. Classes that communicate often are likely to share a purpose (e.g., handle UI interaction) and so, building communities based on their communication should separate distinct functionality. In fact, Figure~\ref{fig:gn} shows how increasing the number of partitions increases the amount of offloadable code due to this separation of purposes. At 30 GN communities, all but a single app have between 24\%-68\% of their code suitable for offloading (hundreds to thousands of classes). If we use the Louvain~\cite{blondel2008fast} algorithm to pick the optimal partitioning (based on modularity), we see find that the median number of partitions per app is 17 and that their offloadable code ranges from 7 to 57\% ($\tilde{x} \approx 24\%$) with only two apps below 10\%. While the benefits of offloading such partitions are dependent on the runtime environment (e.g., state, network connectivity, etc.) these results indicate that our offloading strategy can be applied to more popular and complex apps with huge real-world user bases. \section{Introduction} \label{sec:intro} Pervasive mobile clients have given birth to complex mobile apps, many of which require a significant amount of computational power on users' devices. Unfortunately, given current battery technology, these demanding apps impose a huge burden on energy constrained devices. While power hogging apps are responsible for 41\% degradation of battery life on average~\cite{oliner_carat:_2013}, even popular ones such as social networks and instant messaging apps (e.g., Facebook and Skype) can drain a device's battery up to \emph{nine times faster} due only to maintaining an on-line presence~\cite{Aucinas:2013:SOW:2535372.2535408}. \begin{table*}[t!] \centering \begin{tabular}{@{}cccccccc@{}} \toprule \textbf{MCO} & \textbf{Partitions} & \textbf{Dynamic} & \textbf{No Repackage} & \textbf{Stock OS} & \textbf{Cloud} & \textbf{Network} & \textbf{Deployment} \\ \midrule MAUI~\cite{cuervo_maui:_2010} & Manual / Method & \xmark & \xmark & \cmark & \cmark & \xmark & \xmark \\ ThinkAir~\cite{kosta_thinkair:_2012} & Manual / Method & \xmark & \xmark & \cmark & \cmark & \xmark & \cmark (EC2,cost) \\ CloneCloud~\cite{chun_clonecloud:_2011} & Auto / Thread & \cmark & \xmark & \xmark & \cmark & \xmark & \xmark \\ Comet~\cite{gordon_comet:_2012} & Auto / Thread & \textbf{--} & \cmark & \xmark & \cmark & \xmark & \xmark \\ Zhang et al.~\cite{zhang_refactoring_2012} & Auto / Class & \xmark & \xmark & \cmark & \cmark & \xmark & \xmark \\ INFv & Auto / Class & \cmark & \cmark & \cmark & \cmark & \cmark & \cmark (cache,load) \\ \bottomrule \end{tabular} \caption{Mobile Cloud Offloading~(MCO) systems and properties. The comparison reveals that INFv supersedes the previous designs in many aspects. (red cross means the feature is not supported whereas green tick means the opposite.)} \label{tab:infvrules} \vspace{-5mm} \end{table*} Recent work has proposed various solutions to offload and execute functionality of mobile apps remotely in a cloud, referred to as a mobile-to-cloud paradigm~\cite{cuervo_maui:_2010,kemp_cuckoo:_2010,kosta_thinkair:_2012,chen_coca:_2012, zhang_refactoring_2012,gordon_comet:_2012,chun_clonecloud:_2011}. Their evaluations have shown that the energy consumption of CPU intensive apps, e.g., multimedia processing apps and video games, can be reduced by an order of magnitude~\cite{chun_clonecloud:_2011, cuervo_maui:_2010}. Beside the extended battery life, there are other benefits, such as faster execution time, responsiveness, and enhanced security by dynamic patching~\cite{mulliner_patchdroid:_2013}. However, prior work suffers from two limitations. First, they overlooked the potential of exploiting ISPs' in-network resources for functionality offloading, simply using the network as a transmission fabric. Quite different from a decade ago, network middle boxes are no longer simple devices which only forward packets, often featuring multi-core general purpose processors~\cite{xeon} far more capable than those of mobile devices. In fact, many ISPs' own network services have been shifting from specialized servers to generic hardware with the adoption of the NFV (Network Function Virtualization) paradigm\footnote{Telefonica aimed to shift 30\% of their infrastructure to NFV technologies by the end of 2016~\cite{telefonica:nfv,telefonica:cartablanco,telefonica:unica}. Other providers such as AT\&T~\cite{att:nfv}, Vodafone~\cite{ericsson:nfv}, NTT Docomo~\cite{nttdocomo:nfv} and China Mobile~\cite{chinamobile:nfv} are following similar steps.}. This paradigm can be naturally extended from basic network functions (e.g., packet filtering) to the more general functionality of mobile apps, exploiting ``last-hop'' proximity to effectively reduce latency, network load, and improve availability compared to a centralized mobile-to-cloud deployment. When deployed close to cellular towers (Radio Access Network), offloading latency could be reduced by up to 86.7\%, reducing the energy consumption and execution time by up to 21.6\% and 24.5\%, respectively, when compared to a popular cloud alternative (Section~\ref{sec:runtimeeval}). Furthermore, such a system could potentially be extended to adapt an app's lifecycle to network conditions, further reducing devices' energy consumption (e.g., delay network dependent background execution~\cite{almeida_empirical_2016} in the case of congestion) and the volume of signaling offloaded to the Core Network (CN)~\cite{patel2014mobile}. Unfortunately, previous systems either failed to address the challenges of deploying and scaling mobile code offloading systems at all, or overlooked the opportunities to effectively exploit in-network resources. Second, these solutions often utilize intrusive offloading techniques which either require custom OS distributions~\cite{chun_clonecloud:_2011,gordon_comet:_2012}, app repackaging~\cite{zhang_refactoring_2012}, or even alternative app stores, not only increasing security risks and deployment costs, but also greatly increasing the barrier to the market adoption. \rthree{- the merits of operator offload are not obvious (since wired latencies are very small when compared to wireless ones) - the authors should quantify them better. - it is not obvious to what extent the design leverages operator networks (or their proximity to the mobile users) - all the network part is done in simulation. you fail to convince the reader there is a single benefit that can be had in operator networks that cannot be had in a cloud offloading scenarios (all major cloud operators have presence in all continents and wired latencies should be well below 50ms - so why should we care about operator offload?).} \rthree{you need a crisp reason for why operator offload makes sense (aside from the operator making some cash), and you need to implement a full system that actually relies on operator deployments to get its job done.} \manote{I think I briefly addressed these complaints in MA\#1 by adding the latency, energy and execution time numbers retrieved from our last experiment.} This paper presents INFv, the first mobile computation offloading system able to cache, migrate, and dynamically execute mobile app functionality on demand in an ISP network. It uses advanced interception and automatic app partitioning based on functionality clustering, combined with in-network load balancing algorithms to perform transparent, non-intrusive, in-network functionality offloading. INFv aims to bridge the gap between the limited battery capacity of user devices and the ever-growing energy demands of modern mobile apps\cite{oliner_carat:_2013,Aucinas:2013:SOW:2535372.2535408} by extending the promising NFV paradigm to mobile apps. More specifically, we make the following contributions: 1)~We present INFv's data-driven architecture and design, along with key mechanisms and various technical details required to achieve non-intrusive offloading and adaptive in-network resource management. 2)~We show that INFv is able to greatly improve apps energy consumption (reduced by up to 6.9x) and speed up app execution (up to 4x faster). It performs similar to, or better than, local execution 93.2\% of the time over 4G while adapting to dynamic network conditions and up to 24.5\% faster than a cloud alternative. 3)~We compare different strategies to effectively balance functionality load in the network while reducing both end-user-experienced latency and request drop rates. 4)~Through a real mobile app market study we show that app's storage cost can be reduced by up to 93.5\%, and that top apps have a median of 17 distinct functionality clusters, with up to 57\% of offloadable code. \section{Background \& Related Work} \label{sec:related} \rthree{please have a look at Mobile Edge Computing (MEC) which may be relevant to what you are trying to achieve.} \tyson{Sounds like you might want to include more stuff on RPC? Particularly work on transparent RPC used for offloading?} Mobile Code Offloading~(MCO) is a reasonably well explored area~(see Table~\ref{tab:infvrules}), however earlier work has a few limitations that we directly address with INFv. In this section we provide an overview of previous work, focusing on the lessons taken away that we used to design INFv. MCO systems can be differentiated based on their granularity and partitioning decisions (what to offload), offloading techniques (how to offload), and runtime decisions (when to offload). \textbf{What to offload} can be defined in a \emph{manual} (app developer assisted) or in an \emph{automated} manner. The first can be accomplished via programming frameworks and/or code annotations. For programming frameworks~\cite{kemp_cuckoo:_2010,chen_coca:_2012,kosta_thinkair:_2012}, both local and remote execution alternatives have to be implemented according to the framework's design constraints (e.g., concurrency models). In Maui~\cite{cuervo_maui:_2010}, annotations allow a partially automated offloading solution where developers select methods to offload. The benefit of these explicit systems is the level of customization; developers have a large degree of control over how their apps are offloaded. An alternative approach taken by other work is to make automated offloading decisions~\cite{chun_clonecloud:_2011,gordon_comet:_2012,zhang_refactoring_2012} by performing static and dynamic analysis of apps. While automated approaches give up a degree of flexibility, they benefit from being able to leverage the existing app ecosystem and general ease of use. That said, these systems do not really focus on the deployment characteristics of offloading. Thinkair~\cite{kosta_thinkair:_2012} and Cloudlets~\cite{satyanarayanan_case_2009}, however do to some extent. Thinkair allows on-demand execution in a cloud environment. It provides 6 different VM types, with varying CPU and memory configurations. Mobile devices upload \emph{specially crafted apps} to the cloud, and their local counterpart negotiates the on-demand execution on one of these VMs. A more robust approach (one that we have taken) is to support \emph{existing apps} while handling resource negotiation and functionality caching in a fully automated and transparent manner. In particular, we want to ensure that INFv supports heterogeneous network topologies and load balances cached functionality in an intelligent manner. Cloudlets~\cite{satyanarayanan_case_2009} in particular serves as a motivation for INFv as \emph{it highlights the impact of high latency in MCO} to justify the need for deploying physically proximate decentralized clusters to execute functionality. INFv directly addresses the problems and challenges raised in this work by proposing an in-network solution (``Network'' in Table~\ref{tab:infvrules}) for MCO. The majority of offloading literature proposes a method offloading granularity~\cite{cuervo_maui:_2010,kemp_cuckoo:_2010,kosta_thinkair:_2012,chen_coca:_2012}. CloneCloud~\cite{chun_clonecloud:_2011} and Comet~\cite{gordon_comet:_2012} propose full or partial thread granularity. Automated method granularity architectures incur the cost of synchronizing the serialized method caller objects, parameters, changed state and return object. Thread granularity architectures often need to synchronize thread state, virtual state, program counters, registers, stack or locks. INFv is the \emph{first to address the challenges behind caching app functionality, complementing its granularity design with a real market study to reduce its app storage requirements.} \textbf{How to offload} depends on the aforementioned characteristics. Manual approaches tend to use custom compilers (e.g., AspectJ) or builders. Automated solutions often operate on compiled apps and rely on byte-code rewriting~\cite{zhang_refactoring_2012} or VM modifications~\cite{chun_clonecloud:_2011,gordon_comet:_2012}. Altering an app generally requires repackaging and resigning it, which also implies the need for a new distribution mechanism incompatible with current app markets. Each of the above architectures, except for Comet~\cite{gordon_comet:_2012} (a distributed shared memory solution), need either app repackaging, re-writes, or both, impacting their likelihood of adoption. INFv offloading differs mainly in that it \emph{does not require a custom distribution, manual intervention or app-repackaging even in the presence of app updates.} It allows for dynamically loaded partitions (``Dynamic'' in Table~\ref{tab:infvrules}) and is fully reversible. \textbf{When to offload} was mostly done using thresholds~\cite{gordon_comet:_2012} or Integer Linear Programming~\cite{cuervo_maui:_2010,chun_clonecloud:_2011} based on the app profiling metrics Similar to CloneCloud, INFv relies on UI instrumentation to profile the different execution paths of apps. INFv performs app profiling on remote servers to reduce the overhead on mobile devices and like Thinkair~\cite{kosta_thinkair:_2012}, its energy model is based on PowerTutor~\cite{zhang_accurate_2010}. INFv improves previous systems by \emph{offloading together functionality with high communication based on their runtime invocation frequency}. \textbf{Clone detection} literature~\cite{mojica_large-scale_2014,linares-vasquez_revisiting_2014,ruiz_understanding_2012,desnos_android:_2012} focused on detecting app cloning using class/method names and tend to ignore minor custom changes to the functionality. In code caching, we are more interested in the unmodified use of third-party libraries than similar code. Unlike recent studies~\cite{linares-vasquez_revisiting_2014,mojica_large-scale_2014,wang_wukong:_2015}, some initial works~\cite{ruiz_understanding_2012, desnos_android:_2012} did not consider obfuscation, which can impact the statistical significance of their results. In~\cite{mojica_large-scale_2014} and~\cite{linares-vasquez_revisiting_2014} the authors study obfuscation based on class names. Unfortunately, they \emph{do not consider package obfuscation which affects the offloading routing mechanisms}. Wukong et al.~\cite{wang_wukong:_2015} focused on clone detection based on Android API calls, and while it highlights the challenges in overcoming obfuscation, we have found strong evidence that, \emph{a simple package name filtering might suffice to detect obfuscation at a package level.} \textbf{Mobile Edge Computing}~\cite{mec} (MEC) is an industry initiative\footnote{supported by Huawei, IBM, Intel, Nokia, NTT DOCOMO and Vodafone.} whose goal is to provide computing capabilities at the edge of the cellular network. Its focus is explicitly on the infrastructure and deployment and not on the potential applications. That said, INFv can be considered an obvious use case of MEC and the first full-fledged MCO architecture to exploit its potential. \textbf{Runtime patching} has been used to dynamically provide updates to apps. OPUS~\cite{altekar_opus:_2005} focused on providing dynamic software patching to C programs, while POLUS~\cite{chen_polus:_2007} was more focused on updating long-lived server side apps. More recently, such techniques were brought to Android with PatchDroid~\cite{mulliner_patchdroid:_2013}. It focused on security vulnerabilities and proposed a system to distribute and apply third-party in-memory security patches. Inspired by these systems, INFv modifies a single Android OS binary to extends app's functionality \emph{at runtime}, providing mechanisms similar to those of aspect oriented programming.
{'timestamp': '2019-06-17T02:15:43', 'yymm': '1906', 'arxiv_id': '1906.06240', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06240'}
arxiv
\section{Introduction\label{sec:intro}} In the past ten years, GPUs have evolved from chips specialized for graphics processing to powerful and flexible accelerators for general computational and data processing tasks. Together with improvements in hardware capabilities, there has been a growing software ecosystem. In terms of programmability, beyond the original CUDA C, GPUs can now be programmed with compiler directives (OpenACC, OpenMP), or in high level languages such as Python, MATLAB, or Julia. On the system side, there are now servers like the NVIDIA DGX-2 with all GPUs connected via NVLink and NVSwitch. These types of systems are bringing SMP-like capabilities to multi-GPU programming, as GPUs on the node can access data on other GPUs in a fast and transparent way. In this paper, we use the 2D Ising model to compare the level of performance achievable with different programming approaches on GPUs. \section{Ising Model} In statistical mechanics, ``spin system'' indicates a broad class of models used for the description of a number of physical phenomena. A spin system is usually identified by a Hamiltonian function having the following general form: \begin{equation} H = -\sum_{i \ne j}J_{ij}\sigma_i\sigma_j \label{equ:spinequ} \end{equation} The spins $\sigma$ are defined on a {\em lattice} which may have one, two, three or even a higher number of dimensions. The sum in Equation \ref{equ:spinequ} runs on the nearest neighbors of each spin location (for example, 2 in 1D, 4 in 2D and 6 in 3D). The spins and the couplings $J$ may be either discrete or continuous and their values determine the specific model. In the Ising model \cite{Ising} of ferromagnetism, the spins can be in one of two states (+1 or -1), $J_{ij}$ is $>0$ and, as a further simplification, all of the nearest neighbors $<ij>$ have the same interaction strength so that $J_{ij} = J$ for all pairs $i, j$. There are analytical solutions for the Ising model in 1D and 2D; however, these can be considered an exception because, despite the illusory simplicity of their Hamiltonian formulation, the study of spin systems in higher dimensions is by no means trivial. Most of the time, numerical simulations (very often based on Monte Carlo methods) are the only way to understand their behavior. A Monte Carlo simulation of the Ising model can be performed with the Metropolis algorithm \cite{Metropolis}, where the following steps are repeated: \begin{itemize} \item From an initial configuration of spins, flip a randomly chosen spin. \item If the change in energy between the old and new state is negative, we accept the change. \item Otherwise, the move is accepted with probability $e^{(-\beta \Delta E)}$, where $\beta$ is the inverse of the temperature of the system and $\Delta E$ is the difference in the energy due to the spin flip. \end{itemize} It is very desirable from a computational point of view to update multiple spins in parallel. Given the local interactions of a spin with its neighbors, we can see that if we consider the lattice as a checkerboard, the flipping of a spin of a particular color is completely determined by its neighbors of the opposite color. We can update all the spins of one color in parallel, keeping the other color constant, and then repeat the process with the opposite color. The checkerboard decomposition can be used to run parallel versions of other \textit{local} Monte Carlo algorithms, like the \textit{Heat Bath} algorithm in which the probability $P$ of a spin flip from $\sigma$ to $-\sigma$ is equal to $\nicefrac{e^{-\beta \Delta E}}{e^{-\beta \Delta E}+1}$. Due to their locality, algorithms like Metropolis and Heat Bath suffer from the so called \textit{critical slowing down} syndrome; a state in which it becomes increasingly difficult to flip a spin at random as it is likely to be coupled to neighboring spins pointing in the same direction. A solution to this problem is provided by an algorithm proposed by U. Wolff \cite{Wolff1989} in which a whole cluster of spins is flipped in each update instead of a single one. The cluster is constructed starting from a seed spin selected at random and looking at its neighboring spins. Those with the same sign as the seed spin are added to the cluster with a probability $P_{add}$ equal to $1-e^{-2\beta J}$, whereas they are excluded from the cluster with probability $1 - P_{add}$ (spins having the opposite value with respect to the seed spin are ignored). This implies that spins are added to the cluster with a probability that is temperature dependent. It is not difficult to check that in both the low and high temperature regimes, the Wolff algorithm is not very efficient and the simpler Metropolis algorithm performs better. As a consequence, there is still much interest in using efficient (from the computational viewpoint) implementations of the Metropolis algorithm for the simulation of the Ising (and similar) models \cite{Bernaschi2012}. In the present paper, we discuss the performance of several implementations for the simulation of the 2D Ising model running on NVIDIA Volta GPUs. We focus on the 2D model because the results can be easily compared to the analytical solution derived by Onsager \cite{Onsager}. We compare our performance with those recently produced on other computing platforms \cite{TPU2019,FPGA}. \section{Single-GPU implementations} \subsection{Basic Implementation} To begin, a basic single-GPU implementation of the checkerboard Metropolis algorithm was implemented in Python, combining features available in the popular \texttt{Numba} and \texttt{CuPy} packages. Specifically, \texttt{Numba} \cite{Numba} was used for general GPU data handling via its provided \texttt{device\_array} objects and also for its ability to compile custom CUDA kernels at runtime expressed purely in Python. In our experimentation, we found that the random number generation supported in \texttt{Numba} for use in device kernels to be fairly low performing. As a replacement, we used available bindings into the NVIDIA \texttt{cuRAND} \cite{cuRAND} library available in \texttt{CuPy} \cite{CuPy} to pre-populate an array of random numbers as a separate operation before each lattice update kernel call. \begin{figure*}[t] \begin{center} \includegraphics[scale=0.75]{checkerboard.pdf} \end{center} \caption{On the left, an abstract $12\times 12$ lattice with the checkerboard pattern highlighted is shown. In the center, the lattice is represented using two arrays, each containing one color of spins compacted along the rows. On the right, the lattice is decomposed into $4\times 4$ sub-lattices, where each sub-lattice is represented as a sequence of four $2\times 2$ blocks of spins of the same color.} \label{fig:checker} \end{figure*} The $N \times N$ checkerboard lattice of spins is represented in two separate arrays of dimension $N \times N/2$, with each array containing only spins of a single color. This decomposition is depicted in the central image in Figure \ref{fig:checker}. As each spin only takes the value of $\pm 1$, each spin location can be represented using a single byte. While further compressed data representations are possible, a byte is the smallest data type that does not require bitwise operations. With the data decomposition in place, the implementation is straightforward and consists of two steps per color, per iteration. For a given color: \begin{enumerate} \item Populate an $N \times N/2$ array of random values with \texttt{CuPy/cuRAND} \item Update spins on the lattice for the current color using the opposite colored lattice spin values and the random value array, implemented in a custom kernel written with \texttt{Numba}. See Figure \ref{fig:update_lattice_listing} for a listing of the spin update code. \end{enumerate} To better gauge the performance of \texttt{Numba}, a nearly identical implementation of this basic algorithm for single-GPU was also implemented in CUDA C. A comparison of the main lattice kernel in both implementations can be seen in Figure \ref{fig:update_lattice_listing}. \begin{figure} \begin{minipage}{0.49\textwidth} \centering \begin{lstlisting}[language=Python] @cuda.jit def update_lattice(lattice, op_lattice, randvals, is_black): n,m = lattice.shape tid = cuda.blockIdx.x * cuda.blockDim.x + cuda.threadIdx.x i = tid // m j = tid if (i >= n or j >= m): return # Set stencil indices with periodicity ipp = (i + 1) if (i + 1) < n else 0 jpp = (j + 1) if (j + 1) < m else 0 inn = (i - 1) if (i - 1) >= 0 else (n - 1) jnn = (j - 1) if (j - 1) >= 0 else (m - 1) # Select off-column index based on color and row index parity if (is_black): joff = jpp if (i else: joff = jnn if (i # Compute sum of nearest neighbor spins nn_sum = op_lattice[inn, j] + op_lattice[i, j] + op_lattice[ipp, j] + op_lattice[i, joff] # Determine whether to flip spin lij = lattice[i, j] acceptance_ratio = math.exp(-2.0 * inv_temp * nn_sum * lij) if (randvals[i, j] < acceptance_ratio): lattice[i, j] = -lij \end{lstlisting} \end{minipage} \begin{minipage}{0.49\textwidth} \centering \begin{lstlisting}[language=c] template<bool is_black> __global__ void update_lattice(char* lattice, const char* __restrict__ op_lattice, const float* __restrict__ randvals, const float inv_temp, const int nx, const int ny) { const int tid = blockDim.x * blockIdx.x + threadIdx.x; const int i = tid / ny; const int j = tid if (i >= nx || j >= ny) return; // Set stencil indices with periodicity int ipp = (i + 1 < nx) ? i + 1 : 0; int inn = (i - 1 >= 0) ? i - 1: nx - 1; int jpp = (j + 1 < ny) ? j + 1 : 0; int jnn = (j - 1 >= 0) ? j - 1: ny - 1; // Select off-column index based on color and row index parity int joff; if (is_black) { joff = (i } else { joff = (i } // Compute sum of nearest neighbor spins char nn_sum = op_lattice[inn * ny + j] + op_lattice[i * ny + j] + op_lattice[ipp * ny + j] + op_lattice[i * ny + joff]; // Determine whether to flip spin char lij = lattice[i * ny + j]; float acceptance_ratio = exp(-2.0f * inv_temp * nn_sum * lij); if (randvals[i*ny + j] < acceptance_ratio) { lattice[i * ny + j] = -lij; } } \end{lstlisting} \end{minipage} \caption{Single-GPU \texttt{update\_lattice} kernel in Python (left) and CUDA C (right) used in basic implementations. \texttt{@cuda.jit} decorator used to enable \texttt{Numba} JIT compilation of CUDA kernel.} \label{fig:update_lattice_listing} \end{figure} \subsection{Tensor Core Implementation} In \cite{TPU2019}, an implementation of the checkerboard Metropolis algorithm was developed to map the computation of nearest-neighbor sums to matrix multiplications in order to execute them on TPUs using their hardware FP16 matrix multiply units (TPU Tensor Cores). As GPUs are generally programmable and the computation can be directly expressed in CUDA, such a mapping to matrix multiplies is not necessary for GPUs and adds unneeded complexity; however, as a means for comparison, a version of this matrix multiply algorithm was implemented to utilize NVIDIA Tensor Cores available on Volta GPUs. A complete description of the algorithm can be found in \cite{TPU2019} and only key details will be discussed here. For this implementation, the lattice data is organized in a pattern similar to the right-most diagram in Figure \ref{fig:checker}. In our implementation, the lattice is organized into $256 \times 256$ sub-lattices, each further decomposed into four $128 \times 128$ blocks. At the high level, the algorithm uses matrix multiplications to compute sub-lattice local nearest neighbor sums using a kernel matrix $\bm{K}$ of the form, \begin{equation} \bm{K} = \begin{bmatrix} 1 & 1 & 0 & \dots & 0 & 0 & 0 \\ 0 & 1 & 1 & \dots & 0 & 0 & 0 \\ 0 & 0 & 1 & \dots & 0 & 0 & 0 \\ \vdots & \vdots & \vdots & \ddots & \vdots & \vdots & \vdots \\ 0 & 0 & 0 & \dots & 1 & 0 & 0 \\ 0 & 0 & 0 & \dots & 1 & 1 & 0 \\ 0 & 0 & 0 & \dots & 0 & 1 & 1 \\ \end{bmatrix}_{128 \times 128} \end{equation} For a given sub-lattice, $\bm{\sigma}^{ij}$, to compute the sum of sub-lattice local nearest neighbor spins for the black sub-blocks, $\bm{\sigma}^{ij}_{00}$ and $\bm{\sigma}^{ij}_{11}$, the following operations are performed, \begin{align} nn_\text{L}(\bm{\sigma}^{ij}_{00}) &= \bm{\sigma}^{ij}_{01} \bm{K} + \bm{K}^T \bm{\sigma}^{ij}_{10} \label{eq:b0}\\ nn_\text{L}(\bm{\sigma}^{ij}_{11}) &= \bm{\sigma}^{ij}_{10} \bm{K}^T + \bm{K} \bm{\sigma}^{ij}_{01} \label{eq:b1} \end{align} where $nn_\text{L}()$ denotes the sum of sub-lattice local nearest neighbor spins. A similar expression can be used to compute sums for the white sub-blocks, \begin{align} nn_\text{L}(\bm{\sigma}^{ij}_{10}) &= \bm{\sigma}^{ij}_{11} \bm{K} + \bm{K} \bm{\sigma}^{ij}_{00} \label{eq:w0}\\ nn_\text{L}(\bm{\sigma}^{ij}_{01}) &= \bm{\sigma}^{ij}_{00} \bm{K}^T + \bm{K}^T \bm{\sigma}^{ij}_{11} \label{eq:w1} \end{align} With these equations, one can obtain the sub-lattice local sums for a given color over the entire lattice via two batched matrix-multiply operations, corresponding to the left and right summands in either Eqs. \ref{eq:b0} and \ref{eq:b1} for the black spins, or Eqs. \ref{eq:w0} and \ref{eq:w1} for the white spins. To enable the use of tensor cores, the lattice spins and nearest neighbor sums are stored in half-precision, and the matrix multiplies are computed using \texttt{cublasHgemmBatched} routine available in the NVIDIA \verb|cuBLAS| library \cite{cuBLAS}. Once the sub-lattice local sums are obtained for a given color, a separate kernel adding boundary contributions from neighboring sub-lattices is executed, followed by a final spin update kernel which uses the completed sums and generated random values to update spins. In this implementation, we used the \verb|Philox4_32_10| generator provided by the device API of the \verb|cuRAND| library to generate per-thread random numbers within the spin update kernel. In order to avoid allocated separate global memory to store generator states and loading/storing them for every color update, we initialize a new state at each kernel call in a way such that each thread progresses coherently along the same random sequence across consecutive launches. This is possible thanks to the \verb|curand_init()| call that allows to specify a \verb|seed|, a \verb|sequence|, and an \verb|offset|. The seed determines a series of random sequences, the sequence number identifies one of those sequences, and the offset specifies an element in that sequence. For each kernel call, each thread uses the same seed, specifies as sequence number its unique linear index in the grid, and specifies an offset equal to the total count of random numbers generated in the previous kernel calls. This is in contrast to the approach in the basic implementation where an array of random values is pre-populated using the host API. To summarize, the steps to update spins for a given color are as follows: \begin{enumerate} \item Compute sub-lattice local spin sums for current color using two batched matrix-multiplication operations (via calls to \texttt{cublasHgemmBatched}) \item Add boundary contributions from neighboring sub-lattice to local sums using a custom boundary update CUDA kernel. \item Update spins for current color using completed sums and random values generated with \verb|cuRAND| in a custom spin update CUDA kernel. \end{enumerate} From this description, a few notable issues with this approach can be discussed. First, the use of matrix multiplications necessitates additional memory usage in order to store intermediate local nearest neighbor sums (for at least half of the total lattice). On top of this, to utilize tensor cores the sums and lattice spins must be stored in half-precision which further increases memory requirements. Next, the splitting of the computation into several distinct operations results in increased global device memory traffic as data must be loaded and stored from global memory in between operations. Additionally, the standalone boundary update operation yields many uncoalesced memory loads and stores when updating the sub-lattice boundaries along the direction strided in memory, resulting in poor memory bandwidth utilization for this kernel. As this problem is memory-bandwidth limited, increasing memory bandwidth pressure just to enable the mapping of the problem to tensor cores is not a wise trade-off. This is especially true when the matrix multiplications themselves consist of mostly useless FLOPs (i.e. multiplications by zero), with only two multiplications per inner product contributing to the final result, yielding a fraction of $1/64$ useful FLOPs when using $128 \times 128$ matrix multiplications. \subsection{Optimized Implementation} \begin{figure*}[t] \begin{center} \includegraphics[scale=0.92]{spin_layout.pdf} \end{center} \caption{Example of the memory accesses required to load the neighboring spins in the multi-spin case. The left side contains the abstract lattice of spins, colored according to the checkerboard pattern. Represented to the right are the actual arrays of white and black spins as they are stored in memory. Each color is compacted along the rows and stored using two spins per word. There are two possible access patterns required to load neighboring spins based on the color of target spins and on the parity of the row index of the word containing them. Assuming the target lattice is the black one, let's consider an odd row case, for example $(8, 9)_B$, and an even row case, for example $(38, 39)_B$. In both cases, all the top and bottom spins are found in the two words below and above the target word ($(2,3)_W$, $(14,15)_W$ for $(8,9)_B$, and $(32,33)_W$, $(44,45)_W$ for $(38,39)_B$). Of the neighboring spins lying on the same row, all but one are always located in the word at the same coordinates as target word ($(8,9)_W$ and $(38,39)_W$ white). The last spin is either the leftmost one in the word to the right of the central one, if the row index is odd ($(10,xx)_W$ for $(8,9)_B$), or the rightmost one in the word to the left, if the row index is even ($(xx,37)_W$ for $(38,39)_B$). It is easy to see that these cases for the side words are reversed when the target lattice is the white one.} \label{fig:multispin_layout} \end{figure*} In order to use the compute resources of the GPU as efficiently as possible, we developed an optimized implementation of the Metropolis algorithm based on the multi-spin coding technique \cite{Multispin} in CUDA C. Similar to the basic implementation, we represented the spin lattice of size $N\times M$ as two separate arrays of size $N\times M/2$, each holding one set of spins from the checkerboard representation. Each spin is represented with $4$ bits instead of using an entire byte (or larger words). This choice not only reduces the memory footprint of the lattice, with respect to using a whole word per spin, but it makes it possible to perform the sums of neighbors' values for multiple consecutive spins (of the same color) in parallel, provided that the theoretical spin values -1/1 are mapped to 0/1, respectively. The combination of the reduced number of bits used to store a spin value with the use of the largest word size (64-bit) allows drastic reductions in the number of addition instructions executed by the hardware. Assuming that each of four 64-bit words contain 16 consecutive spins from the N, S, E, and W directions, three additions are sufficient to compute the neighbors sums instead of the $48$ that would be required if each quadruple was processed independently ($16\times 3$). The choice of four bits per spin enables performing the sums without using additional variables given that each spin can contribute at most $1$. In theory, since each sum can add to at most $4$, three bits would be sufficient but that would require explicit handling of the inter-word cases with no sizeable benefit as far as performance or storage are concerned. The update of each color is performed with a single kernel that is launched with enough blocks to cover the whole lattice. Each thread is in charge of updating $64$ spins (256 bits), thus it executes two 128-bit loads from the target lattice array (the spins to be updated), eight additional 128-bit loads from the source lattice array (to fetch the four neighbors of the target spins, four loads per source word), and two 128-bit writes to store the flipped spins back into the target lattice. The separation on the spins according to the checkerboard pattern is such that it is quite simple to compute the words required to load the neighbors of a target word of spins. The neighbors of the spins in word $(i,j)$ from the target lattice are found in the words from the source lattice at coordinates $(i-1,j)$, $(i,j)$, $(i+1,j)$ (three vertically aligned words centered on $(i,j)$) and in a word from one of the sides. If $i$ is even, then this word is the one at coordinates $(i,j-1)$, otherwise it's at $(i,j+1)$. The side word contains only one spin required for the computation (the one nearest to the central word) and so it cannot be directly used in the neighbors additions. This however, can easily be fixed by shifting out the unnecessary spins and shifting in an equal number of spins from the central word, as shown in Figure \ref{fig:multispin_layout}. In order to avoid reading the lattices entries multiple times from the global memory, each block initially loads its spin tile from the source lattice into the shared memory, and then the threads load the words containing their neighboring spins from that faster memory space. We generate random numbers similarly to what we described for the tensor core implementation, using the \verb|Philox4_32_10| generator provided by the device API of the \verb|cuRAND| library. Each simulation step is performed by performing two kernel launches, one for the black and one for the white sublattice. \section{Multi-GPU implementations} A classic multi-GPU approach would implement the update of the halo spins in a different routine from the spins in the bulk to allow an overlap of communication and computation, as shown in \cite{Bernaschi2012}. While this approach is very effective and allows good scaling, in this work we exploited new capabilities available in the DGX line of systems (DGX Station, DGX-1 and DGX-2), where the GPUs are connected through NVLink and unified memory allows allocations that span multiple GPUs. When one GPU needs to access data stored on another GPU, the driver will automatically migrate the corresponding memory pages. When using multiple GPUs, the whole lattice can be partitioned into horizontal slabs and each GPU stores one slab in its own global memory in the same layout employed in the single-GPU case (according to the checkerboard pattern). In this way, each GPU needs only read access to the memory of the two GPUs that handle the slabs on top and bottom of its own region. \subsection{Basic Implementation} First, we consider distributing the basic implementation to multiple GPUs. One limitation of the \texttt{Numba} library is that a single thread can have at most one active CUDA context at a time, which actually prohibits the simple usage of unified memory to access data across multiple GPUs. Instead, a multi-process multi-GPU version was implemented using MPI via \texttt{mpi4py} and CUDA Interprocess Communication (IPC) handles, obtained directly from the \texttt{Numba} \texttt{device\_array} objects. In this case, each process obtains a CUDA IPC handle to the lattice allocations of neighboring slabs, and uses them to access spin data in the update lattice kernel when the neighbor stencil crosses slab boundaries. \subsection {Tensor Core and Optimized Implementations} Since both these implementations are written in CUDA C, the full set of options for distribution across multiple GPUs are available. \begin{figure*}[t] \begin{center} \includegraphics[scale=0.85]{multi_gpu_scheme.pdf} \end{center} \caption{Example of Unified Memory calls required to process a squared lattice with 4 GPUs enabling direct memory access to boundary regions between pairs of neighboring devices via NVLink.} \label{fig:multi_gpu_scheme} \end{figure*} The slab based distribution can be realized very easily by using the CUDA Unified Memory system. It is sufficient to allocate the entire $N\times N$ lattice via a single call to the \verb|cudaMallocManaged()| function and then, for each slab, setting the preferred location to be the memory belonging to target GPU and setting up the mapping of the first and last line of that slab in the page tables of adjacent GPUs. These operation are performed by using the \verb|cudaMemAdvise()| call by specifying, respectively, the \verb|cudaMemAdviseSetPreferredLocation| and the \verb|cudaMemAdviseSetAccessedBy| advice parameters. In total, since black and white lattices are stored in separate arrays, six \verb|cudaMemAdvise()| calls are required per GPU. Figure \ref{fig:multi_gpu_scheme} shows an example of the Unified Memory calls and the lattice regions they need to be called onto. This setup does not require any change to the existing GPU kernels to access external memory, or any explicit exchange of data among GPUs (like it would normally be necessary in a CUDA+MPI setup). Rather, the existing kernels are simply launched on each GPU with the lattice array accesses properly offset to access different slabs. When a GPU executes a load on a word belonging to one of its neighbors then a data transfer through NVLink automatically takes place. \section{Results} \subsection{Single-GPU Performance} In this section, we present single-GPU performance results. We ran our single-GPU tests on a Tesla V100-SXM card mounted in a DGX-2 \cite{DGX2}. The card is equipped with 32GB of HBM2 memory and a total of $5120$ CUDA cores. For the basic and tensor core implementations, we ran tests on lattice sizes ranging from $(20 \times 128)^2$ to $(640 \times 128)^2$ to compare directly with TPU results reported in \cite{TPU2019}. For the optimized implementation, we ran tests with different lattice sizes ranging from $2048^2$ (2 MB) to $(64\times 2048)^2$ (8 GB), quadrupling the total number of spins at each step. We also ran the largest lattice possible with the available memory, a $(123\times 2048)^2$ requiring 30.3 GB of memory. The results are reported in Tables \ref{singleGPU_res_python_tc} and \ref{singleGPU_res} respectively. Considering the performance results in Table \ref{singleGPU_res_python_tc}, both the basic implementation and the tensor core one achieve higher performance on a single Tesla V100-SXM than the single TPUv3 results reported in \cite{TPU2019}, with speedups ranging from a factor of 3 for the tensor core implementation to 5 for the CUDA C variant of the basic implementation, when comparing highest reported spin update rates. Comparing across GPU implementations in this table, the tensor core implementation and basic implementation in Python are significantly slower than the basic implementation written in CUDA C. For the tensor core implementation, this is not surprising due to the additional memory bandwidth overhead introduced from splitting the problem into more distinct operations and poor performance of the boundary update kernel due to the required uncoalesced loads and stores. In comparing the basic implementation in Python to the implementation in CUDA C, the major performance difference was mostly due to quality of the compiled spin update kernels. While the Python and CUDA C versions of these kernels are nearly identical (see Figure \ref{fig:update_lattice_listing}), the JIT-compiled Numba kernels were much less performant, in part due to greater register usage relative to the kernel generated by the \texttt{NVCC} compiler with the CUDA C source. For comparison with the performance of our optimized implementation, we include in Table \ref{singleGPU_res} the best results from the high performance TPUv3 implementation on a single and 32 TPUv3 cores, as well as the performance achieved on a FPGA \cite{FPGA} using a lattice of size exactly $1024^2$. The comparison shows that our optimized implementation on a single V100-SXM provides a speedup in excess of $3000\%$ with respect to a TPUv3 core. It is necessary to combine the processing power of 32 TPUv3 cores (four TPU units) to reach performance in the ballpark of a single Tesla V100. \begin{table}[ht] \centering \begin{tabular}{r|cccc} lattice size & Basic (Python) & Basic (CUDA C) & Tensor Core & TPU (on TPUv3 core) \cite{TPU2019} \\ \hline $ (20 \times 128)^2$ & 15.179 & 48.147 & 31.010 & 8.1920 \\ $ (40 \times 128)^2$ & 40.984 & 59.606 & 35.356 & 9.3623 \\ $ (80 \times 128)^2$ & 42.887 & 64.578 & 38.726 & 12.336 \\ $ (160 \times 128)^2$ & 43.594 & 66.382 & 39.152 & 12.827 \\ $ (320 \times 128)^2$ & 43.768 & 66.787 & 39.208 & 12.906 \\ $ (640 \times 128)^2$ & 43.535 & 66.954 & 38.749 & 12.878 \\ \hline \end{tabular} \vspace{.1in} \caption{Single-GPU performance comparison between basic, tensor core, and TPU implementations. Results reported in flips per nanosecond on the same lattices used in \cite{TPU2019}.}\label{singleGPU_res_python_tc} \end{table} \begin{table}[ht] \begin{minipage}{0.30\linewidth} \centering \begin{tabular}{rr} lattice size & flip/ns \\ \hline $ (1\times 2048)^2$ & 231.09 \\ $ (2\times 2048)^2$ & 318.95 \\ $ (4\times 2048)^2$ & 379.27 \\ $ (8\times 2048)^2$ & 411.65 \\ $(16\times 2048)^2$ & 420.44 \\ $(32\times 2048)^2$ & 420.77 \\ $(64\times 2048)^2$ & 418.23 \\ $(123\times 2048)^2$ & 417.53 \\\hline\hline 1 TPUv3 core in \cite{TPU2019} & 12.91 \\ 32 TPUv3 cores in \cite{TPU2019} & 336.01 \\\hline FPGA ($1024^2$) \cite{FPGA} & 614.40\footnotemark{}\\ \end{tabular} \end{minipage} \hspace{0.1in} \begin{minipage}{0.62\linewidth} \centering \includegraphics[scale=0.43]{single_gpu_plot.pdf} \end{minipage} \vspace{.1in} \caption{Flips per nanosecond obtained by the optimized multi-spin code on a single Tesla V100-SXM card with different lattice sizes, requiring an amount of memory ranging from 2MB to 30GB. For comparison purposes, the table also reports the best timings with 1 and 32 TPUv3 cores from \cite{TPU2019}, and with 1 FPGA from \cite{FPGA}.} \label{singleGPU_res} \end{table} \subsection{Multi-GPU Performance} In this section, we present the multi-GPU performance results. For the optimized code, we measured performance on both a DGX-2 and a DGX-2H system. The DGX-2H is a newer version of the DGX-2 server that is outfitted with higher-performing CPUs and GPUs. Its 16 Tesla V100 GPUs run at higher clock speed and feature a 450W TDP each. The performance testing of the basic and tensor core implementations were limited to the base DGX-2 system. Table \ref{weak_scaling} reports the weak scaling measurements obtained running the optimized implementation on both a DGX-2 and a DGX-2H system. The lattice size per GPU has been kept constant at $63.5\times 10^9$ spins (30GB) and we measured the flip/ns rate for $128$ update steps. As expected, the scaling is perfectly linear up to 16 GPUs. This is due to the simple access pattern of remote memory and to the high throughput of the NVLink communications. The performance figures from the table are plotted on the adjacent graph together with the numbers reported in \cite{TPU2019}. Due to memory constraints we couldn't run a test case of size similar to the largest one reported in \cite{TPU2019}. Table \ref{strong_scaling} reports the strong scaling measurements of the optimized implementation obtained on the two DGX systems. The total lattice size has been kept constant at $63.5\times 10^9$ spins (30GB) and it has been partitioned in as many horizontal slabs of the same size as the number of GPUs used in the measurements. As for the weak scaling case, we measured the flip/ns rate for $128$ update steps. Since with any number of GPUs the transfers of the top and of the bottom boundaries is negligible with respect to the processing of the bulk, the scaling is linear up to $16$ GPUs. The plot near the table shows a comparison of the performance figures from the two DGX systems. \addtocounter{footnote}{-1} \stepcounter{footnote}\footnotetext{In \cite{TPU2019} it was incorrectly reported as $0.614$, $1000$ times smaller than the actual value.} For completeness, we also report the weak and scaling measurements obtained on a DGX-2 system for the basic implementation in Python using MPI and CUDA IPC and the tensor core implementation using unified memory in Table \ref{weak_scaling_2}. Similar to the optimized implementation, both of these implementations achieve very good scaling efficiency. Notably, the tensor core implementation with unified memory achieves better scaling efficiency than the basic implementation using MPI and CUDA IPC. \begin{table}[ht] \begin{minipage}{0.5\linewidth} \centering \footnotesize \begin{tabular}{ccrr} & & \multicolumn{2}{c}{flips/ns} \\ \cmidrule(lr){3-4} GPUs & lattice size & DGX-2 & DGX-2H \\ \hline 1 & $(123\times 2048)\times (123\times 2048)$ & 417.53 & 459.16 \\ 2 & $(246\times 2048)\times (123\times 2048)$ & 828.21 & 916.40 \\ 4 & $(246\times 2048)\times (246\times 2048)$ & 1619.81 & 1831.73 \\ 8 & $(492\times 2048)\times (246\times 2048)$ & 3231.89 & 3661.47 \\ 16 & $(492\times 2048)\times (492\times 2048)$ & 6441.68 & 7381.30 \\ \hline\hline \end{tabular} \begin{tabular}{ccr} TPUv3 cores & lattice size & flip/ns \\ \hline $1\times 1\times 2$ & $(986\times 128)^2$ & 22.89 \\ $2\times 2\times 2$ & $(1792\times 128)^2$ & 91.52 \\ $4\times 4\times 2$ & $(3584\times 128)^2$ & 366.01 \\ $8\times 8\times 2$ & $(7168\times 128)^2$ & 1463.51 \\ $16\times 16\times 2$ & $(14336\times 128)^2$ & 5853.04 \\\hline \end{tabular} \end{minipage} \hspace{0.1in} \begin{minipage}{0.5\linewidth} \centering \includegraphics[scale=0.33]{weak_scaling.pdf} \end{minipage} \vspace{.1in} \caption{Weak scaling of the optimized multi-spin code measured using up to 16 V100-SXM GPUs in a DGX-2 and DGX-2H system, keeping the number of spins per GPU fixed at $(123\times 2048)^2$ (top table). For comparison purposes, the lower table contains the weak scaling measurements reported in \cite{TPU2019} on a multi-TPU system. On the right, are plotted the scaling figures for the DGX systems, and for the TPU system. A single DGX-2 outperforms 64 TPU units (256 chips, 512 cores). Dividing flips/ns by number of cores, the flips per nanosecond per TPUv3 core is roughly 11.43, compared to 417.53 per GPU — more than a $30\times$ speedup.} \label{weak_scaling} \end{table} \begin{table}[ht] \begin{minipage}{0.50\linewidth} \centering \begin{tabular}{ccrr} & & \multicolumn{2}{c}{flips/ns} \\ \cmidrule(lr){3-4} no. of GPUs & lattice size & DGX-2 & DGX-2H \\ \hline 1 & & 417.57 & 453.56 \\ 2 & & 830.29 & 925.99 \\ 4 & $(123\times 2048)^2$ & 1629.32 & 1848.44 \\ 8 & & 3252.68 & 3682.90 \\ 16 & & 6474.16 & 7292.19 \\ \hline \end{tabular} \end{minipage} \hspace{0.1in} \begin{minipage}{0.5\linewidth} \centering \includegraphics[scale=0.33]{strong_scaling.pdf} \end{minipage} \vspace{.1in} \caption{Strong scaling of the optimized multi-spin code measured using both a DGX-2 and DGX-2H system with a lattice of fixed size equal to $(123\times 2048)^2$. On the right, it is shown a plot of the two scaling measurements.} \label{strong_scaling} \end{table} \begin{table}[ht] \centering \begin{tabular}{ccrr} no. of GPUs & lattice size & Basic (Python) & Tensor Core \\ \hline 1 & $(640\times128) \times (640\times128)$ & 43.488 & 38.747 \\ 2 & $(1280\times128) \times (640\times128)$ & 82.447 & 77.492 \\ 4 & $(1280\times128) \times (1280\times128)$ & 164.352 & 154.980 \\ 8 & $(2560\times128) \times (1280\times128)$ & 327.136 & 309.918 \\ 16 & $(2560\times128) \times (2560\times128)$ & 648.254 & 619.520 \\ \hline 1 & & 43.481 & 38.752 \\ 2 & & 83.146 & 78.104 \\ 4 & $(640\times128) \times (640\times128)$ & 165.793 & 156.676 \\ 8 & & 330.258 & 313.077 \\ 16 & & 650.543 & 602.083 \\ \hline \end{tabular} \vspace{.1in} \caption{Weak (top) and strong (bottom) scaling of the basic and tensor core implementations measured using up to 16 V100-SXM GPUs in a DGX-2 system. Results reported in flips/ns.}\label{weak_scaling_2} \end{table} \subsection{Validation} \begin{figure*}[ht] \begin{center} \includegraphics[scale=0.65]{magn_param.pdf} \end{center} \caption{Steady state magnetization measures obtained with the multi-spin code for lattice sizes $512^2$, $1024^2$, $2048^2$, and $4096^2$. The solid vertical line marks the critical temperature value $T_c=2.269185$. } \label{fig:magn} \end{figure*} \begin{figure*}[t] \begin{center} \includegraphics[scale=0.65]{binder_param.pdf} \end{center} \caption{Binder parameter obtained with the multi-spin code for lattice sizes $512^2$, $1024^2$, $2048^2$, and $4096^2$ running for, respectively, 16M, 64M, 256M, and 1B update steps.} \label{fig:binder} \end{figure*} As mentioned in Section \ref{sec:intro}, there is an analytical solution for the 2D Ising model in the limit of infinite volume that shows the presence of an order-disorder phase transition such that the magnetization is $0$ for $T>T_c$ whereas it is equal to: \begin{equation}(1-[\sinh{(2J/T)}]^{-4})^{\frac{1}{8}}\label{eqn:magn} \end{equation} for $T<T_c$. The condition for determining the critical temperature $T_c$ at which the phase transition occurs is $(\tanh{(2J/T_c)})^2=1$, corresponding to $T_c=2.269185J$. To verify the accuracy of our optimized code for the simulation of the 2D Ising model, we carried out a set of tests for different temperatures and lattice sizes comparing the results of simulated magnetization with the corresponding (\textit{i.e.,} for the same temperature) values of Equation \ref{eqn:magn}. Figure \ref{fig:magn} shows the simulated magnetization with respect to the temperatures along with the values of the analytical expression \ref{eqn:magn}. Another interesting quantity is the so-called Binder parameter or Binder cumulant \cite{Binder} corresponding to the kurtosis of the order parameter (\textit{i.e.,} the magnetization). The Binder parameter $U_L$ can be computed as $$U_L=1-\frac{<m^4>_L}{(<m^2>)^2_L}$$ This parameter makes it possible to accurately determine phase transition points in numerical simulations of various spin models. The phase transition point may be identified comparing the behavior of $U$ as a function of the temperature for different values of the system size $L$. The critical temperature corresponds to the point where the curves for different values of $L$ cross. Our measures of the Binder parameter are reported in Figure \ref{fig:binder} for the same lattice sizes used for the magnetization. As expected they show a phase transition occurring at the critical temperature $T_c$. Although these measures confirm the accuracy of the simulations using our implementation, we found other interesting effects on large systems ({\em e.g.,} for $L > 1024$) that deserve an in-depth analysis. In particular we observed that in some runs, the time (measured as number of lattice sweeps of the Metropolis algorithm) required to reach the \textit{steady} state is much larger than expected (far from the critical temperature, it should be $\sim L^2$). In those cases, spins tend to organize into bands (horizontal, vertical or even diagonal), remaining in those meta-stable states for very long times. We plan to study that phenomenon in a forthcoming paper. \section{Conclusions} We have presented several implementations of the 2D Ising model using a variety of approaches. All the implementations are accurate, fast and scale very well to multi-GPU configurations. We discussed some of the limitations of the basic and tensor core approaches outlined, however, found that all outperformed results on TPU systems \cite{TPU2019}. Our optimized implementation achieves state-of-the-art performance and compares favorably to custom FPGA solutions \cite{FPGA}. These codes can be easily extended to simulate other models for which there are no analytical solutions, for instance a 2D Ising spin glass model, and can also be used to study the dynamics of the classic ({\em i.e.,} ferromagnetic) Ising model simulated with the Metropolis algorithm. The different versions of the code are available at http://github.com/NVIDIA/ising-gpu. \section*{Acknowledgements} We would like to thank Profs. Giorgio Parisi, Enzo Marinari and Federico Ricci-Tersenghi from the University of Rome "Sapienza" for useful discussions about the convergence properties of the Ising model on large lattices. \bibliographystyle{unsrt}
{'timestamp': '2019-06-17T02:17:39', 'yymm': '1906', 'arxiv_id': '1906.06297', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06297'}
arxiv
\section{Introduction} Semantic annotation of content and data is a fundamental task for generating the building blocks of many endeavors on the semantic web such as building knowledge graphs, generally speaking, making the content consumable by automated agents. Schema.org vocabulary \cite{journals/cacm/GuhaBM16} is currently the de-facto standard for annotating content and data on the web. The vocabulary is maintained by the schema.org initiative and it contains 614 types and 905 properties\footnote{See \url{https://schema.org/docs/schemas.html} Last accessed: 02.04.2019}. In terms of coverage, schema.org can be examined in two dimensions, namely task and domain. Figure \ref{fig:ontology-dimensions} demonstrates the schema.org vocabulary between these dimensions. The x-axis represents the domain dimension, ranging from high generic complexity to high domain-specific complexity. High generic complexity indicates that a vocabulary covers various domains in a superficial way. As the domain-specific complexity increases, the number of domains covered by a vocabulary decreases and the level of detail of a specific domain increases. The y-axis represents the task dimension, ranging from web search to building knowledge graphs. These tasks contain various processes such as knowledge generation and curation. Knowledge generation is creating semantically annotated data based on (a) manual (e.g. via a web form) (b) semi-automated (e.g. via mappings on metadata of structured sources) and (b) automated (e.g. via extraction from unstructured data) techniques. Knowledge curation is a process consists of knowledge assessment, knowledge cleaning and knowledge enrichment \cite{DBLP:conf/sigmod/DongS15, DBLP:journals/semweb/Paulheim17}. On the task dimension, schema.org vocabulary can be found closer to the web search task, since it contains types and classes to represent everything relevant for this task. On the domain dimension, it has high generic complexity, since it contains types and properties to represent several domains (e.g. events, media, accommodation) in a shallow manner. \begin{figure}[h \centering \includegraphics[width=0.8\textwidth]{images/ontology_dimensions.png} \caption{schema.org vocabulary in task and domain dimensions. The goal of domain specification process is to create patterns that are domain and task specific.} \label{fig:ontology-dimensions} \end{figure} The schema.org vocabulary aims to achieve rapid uptake and growth, and to that end, they take the burden off of the content publisher and put it on the data consumer. Therefore its data model is quite flexible in terms of type hierarchy and inheritance of properties by specialized types (e.g. a Waterfall can have a telephone number). Moreover, there are multiple ways to represent the same information. This is achieved by using disjunctive ranges (e.g. the address of a local business can be defined as a string value or as a structured value) and allowing multiple properties with the same purpose (e.g. address of local business can be defined through address, contactPoint or location property) on a type. Although this flexibility and heterogeneity serve for the goals of schema.org vocabulary, it comes with a side effect of contributing to generic complexity of the vocabulary. The high generic complexity can make the knowledge generation process quite challenging, especially within a specific domain. This can happen for two reasons (a) the publishers may not know which types and properties are correct for their domain (b) the schema.org vocabulary may not contain necessary types and properties for their domain. From a task perspective, the vocabulary may need to be restricted and constrained in a certain way that it fits to the needs of a specific task. For instance, a domain specific pattern can be used to support knowledge curation, to assess whether the knowledge graph contains the required information in a way that fits to the requirements of an application like a dialogue system. One way to guide data publishers to create semantically annotated data and content for a specific domain and task is to provide domain specific patterns of the schema.org vocabulary. On one hand these patterns can make schema.org vocabulary suitable for different tasks by restricting and constraining the vocabulary, on the other hand, they can make it more domain specific by reducing the generic complexity and increasing the domain specific complexity. These patterns would serve as an agreement between publishers and consumers to ease the knowledge generation and curation processes for specific domains and tasks. In this paper we present a formal approach for domain specification, a process that applies an operator to the schema.org vocabulary in order to generate a domain specific pattern. We give formal definitions of domain specification operators and an abstract syntax based on Shapes Constraint Language (SHACL) \cite{bibSHACL}. In order to demonstrate its usage, we give concrete domain specification operator implementations in SHACL and introduce several use cases. The rest of the paper is structured as follows: Section \ref{sec:schema-org} gives a brief introduction to the schema.org and describe the formalization we adopt. In Section \ref{sec:shacl}, we give a brief introduction to SHACL and its components we adopt for defining domain specification operators. Section \ref{sec:domain-spec} describes the domain specification process formally. We show some concrete domain specification examples for tourism domain in Section \ref{sec:examples}. Section \ref{sec:related-work} gives an overview of the related work and Section \ref{sec:conclusion} concludes the paper with final remarks and future directions. \section{Schema.org} \label{sec:schema-org} schema.org is a vocabulary to describe "things" on the web. With this intention it was founded in 2011 by four major search engine providers Bing, Google, Yahoo! and Yandex. The development of schema.org is not only driven by a consortium that consists of members of all four mentioned companies but also by a large community, that collaborates on the vocabulary. The vocabulary has regular releases\footnote{v3.5 as of 02.04.2019}. Each release addresses some issues about the existing types and properties or extends the vocabulary by adding new types and properties. Besides extending the core vocabulary directly, third parties can define "external extensions" under a different namespace. These extensions typically contain types and properties that are aligned with the core schema.org vocabulary\footnote{e.g. with RDFS or SKOS constructs }. The data model of schema.org is quite simple and, according to the schema.org documentation, "very generic and derived from RDF Schema"\footnote{https://schema.org/docs/datamodel.html - accessed on April 1, 2019}. The schema.org data model organizes types in a multiple inheritance hierarchy. The vocabulary contains properties that have one or more types in their domains and one or more types in their range definitions. The ranges of a property may need to be altered in practice, by defining a value with multiple types. A prominent example for this so called multi-typed entity (MTE)\footnote{\url{https://github.com/schemaorg/schemaorg/wiki/How-to-use-Multi-Typed-Entities-or-MTEs}} practice is the annotation of hotel rooms \footnote{\url{https://schema.org/docs/hotels.html}}. The schema:HotelRoom type contains properties for describing beds and amenity features. However, to describe a daily room price, the hotel room must be defined also as an instance of schema:Product, which allows the usage of schema:offers property. The MTE practice is a good example for why customization of schema.org for specific domains and tasks is needed. The MTE practice is in principle a way to overcome the generic nature of schema.org vocabulary for specific domains and tasks. However, for data publishers in tourism domain, it may be complicated to find out which types should be used for an MTE. Domain specific patterns created by domain experts can enforce conjunction of multiple types as the range of a property to guide data publishers. As for the formal definition of schema.org, we mostly share the views presented by Patel-Schneider in \cite{DBLP:conf/semweb/Patel-Schneider14}. Following that full-fledged definition, we make the below formal definition of schema.org for the purpose of describing the domain specification process described in this paper: \begin{definition} The schema.org vocabulary is a pair $(T,P)$ of finite sets $T$ and $P$, where: \begin{enumerate} \item $T \cap P = \emptyset$. \item a type $t \in T$ is a regular type when $t$ is a more specific type than Thing in schema.org vocabulary \item a type $t \in T$ is a datatype when $t$ is a more specific type than DataType in schema.org vocabulary. \item each type and property is identified with a URI in the schema.org namespace \item a type in $T$ or a property in $P$ can be represented with only one URI and a URI that represents a type or a property cannot represent another type or a property. \end{enumerate} \end{definition} \begin{definition} A type $t \in T$ is a pair $(U, S)$ where $U$ is the identifier of the $t$, $S$ is the set of subtypes of $t$. \end{definition} \begin{definition} A property $p \in P$ is a pair $(U, D, R)$ where U is the identifier of $p$ and D and R are the set of types that are in the domain and range of $p$, respectively. \end{definition} While the definitions above are inspired by the formal definition made in \cite{DBLP:conf/semweb/Patel-Schneider14}, we introduce some simplifications based on the scope of our work. The work in \cite{DBLP:conf/semweb/Patel-Schneider14} defines a schema.org knowledge base, which consists of types, properties and instances. Since we only deal with the vocabulary for creating domain specific patterns, we ignore the instances. We consider enumeration types, as regular types in $T$. The distinction between datatypes and non-datatypes are only made for syntactic purposes to support SHACL syntax (See Section \ref{sec:domain-spec}). Additionally, we do not consider subproperties in our definition. \section{SHACL} \label{sec:shacl} SHACL is a recent W3C recommendation for defining constraints over RDF data. The language does not have a normative abstract syntax and formal semantics\footnote{See \href{https://www.w3.org/TR/shacl-abstract-syntax/}{here} for details and a link to a proposed abstract syntax and semantics. Last accessed on 23.03.2019}. A syntactically well-formed SHACL shape is ensured by a set of shapes\footnote{https://www.w3.org/ns/shacl-shacl} that implement the SHACL Syntax Rules \footnote{https://www.w3.org/TR/shacl/\#syntax-rules}. For the domain specification process proposed in this paper, we use a subset of SHACL-CORE\footnote{\textit{sh} prefix is used for SHACL-Core namespace} elements. We adopt the following SHACL elements for the syntax of domain specification operators: \begin{enumerate} \item Node shapes (sh:NodeShape) to define restricted types \item Property shapes (sh:PropertyShape) to define allowed properties on a restricted type \item Class-based targets (sh:targetClass) to determine the target type of a domain specification operator \item Value type constraints (sh:class and sh:datatype) to modify the range of an allowed property on a restricted type. \item Cardinality constraints to define required properties \item Shape-based (sh:node and sh:property) constraints to define range restrictions \item Logical constraints (sh:or) to apply logical operations on a set of constraints \end{enumerate} The aforementioned elements are selected based on our experience with schema.org annotations in various use cases in tourism domain (see Section \ref{sec:examples}). We explain how these elements are used in our abstract syntax for domain specification operators in Section \ref{sec:domain-spec}. The elements we adopt from SHACL vocabulary and their dependencies (e.g. URI and blank node syntax as defined in RDF specification) do not imply any semantics for our approach. \section{Domain Specification} \label{sec:domain-spec} Domain specification is a process that generates domain specific patterns by applying an operator to the schema.org vocabulary. The resulting patterns provide basis for knowledge generation from structured and unstructured sources and help to assess knowledge graphs on a larger scale. Overall, domain specification process has two major goals in the domain and task dimensions (see Figure \ref{fig:ontology-dimensions}) (a) reducing the generic complexity and increasing domain specific complexity (b) restricting and constraining the schema.org vocabulary according to certain tasks. We define following types of domain specification processes to achieve these goals: \begin{itemize} \item Simple Domain Specification (SDS) reduces the generic complexity of schema.org by generating a Simple Domain Specific Pattern (SDSP) through removing types and properties. \item Restriction Domain Specification (RDS) generates a Restricted Domain Specific Pattern (RDSP) by restricting the ranges of remaining properties in an SDSP for various tasks \item Extension Domain Specification (EDS) generates an Extended Domain Specific Pattern (EDSP) that increases the domain-specific complexity by adding new types and properties to an SDSP or RDSP \end{itemize} In the rest of this section, we give formal definitions for the three of four aforementioned domain specification process types, namely SDS, RDS and EDS. We explain the patterns produced by these processes with a running example and describe the abstract syntax of domain specification operator for each process based on SHACL elements. \footnote{We describe the abstract syntax for domain specifications with \href{https://www.w3.org/TR/2004/REC-xml-20040204/\#sec-notation}{"EBNF for XML" notation}. We extend the notation with [..] structure for describing special sequences in natural language (e.g. [a valid URI]).} The definition of CDS is left for the future work. \subsection{Simple Domain Specification (SDS)} \label{sec:sds} An SDS produces an SDSP based on schema.org through following steps: \begin{enumerate} \item Define $T^{\cap}$, a subset of $T$ by excluding types and $P^{\cap}$, a subset of $P$ by excluding properties from the schema.org vocabulary (Equation \ref{eq:subsets}). \begin{equation} \label{eq:subsets} \begin{gathered} T^{\cap} \subseteq T \\ P^{\cap} \subseteq P \end{gathered} \end{equation} \item Define $T_p$, the local properties for types in $T^{\cap}$ (Equation \ref{eq:localprops}): \begin{equation} \label{eq:localprops} \begin{gathered} T_p = \{(type, property) \in T^{\cap} \times P^{\cap} \colon domain^\cap(property,type) \}\\ \end{gathered} \end{equation} The predicate "$domain^\cap$" holds true for a $type \in T^{\cap}$ and $p = (U,D,R)$ where $type \in D$. The following example shows the local properties for the type \texttt{Hotel}\footnote{s is a prefix for http://schema.org/ namespace.} in an SDSP. \begin{equation} \begin{gathered} (\{(s:Hotel, s:checkinTime), (s:Hotel, s:checkoutTime), \\(s:Hotel, s:containsPlace), (s:Hotel, s:location), \\(s:Hotel, s:name)\}) \end{gathered} \end{equation} \item Define $T_r$, the local ranges defined on a local property on a type (Equation \ref{eq:localranges}): \begin{equation} \label{eq:localranges} \begin{gathered} T_r = \{((type, property), rangeType) \in T_p \times T^{\cap} \colon\\ range^\cap(property, rangeType) \}\\ \end{gathered} \end{equation} The predicate "$range^\cap$" holds true for a $type \in T^{\cap}$ and $p = (U,D,R)$ where $type \in R$. Simple local ranges are defined to build an SDSP as follows\footnote{ All subtypes of the shown types ($type = (U, S)$ and $type_{sub} \in S$) are included in all three types of domain specific patterns}: \begin{equation} \begin{gathered} (\{((s:Hotel, s:checkInTime), s:DateTime), \\((s:Hotel, s:checkOutTime), s:DateTime),\\ ((s:Hotel, s:containsPlace), s:Place), \\((s:Hotel, s:location), s:PostalAddress),\\((s:Hotel, s:name), s:Text)\}) \end{gathered} \end{equation} \end{enumerate} The process described and demonstrated above is realized through an operator defined in terms of SHACL elements. The abstract syntax of this operator is as follows: An SDS operator is a node shape that is identified with a URI or a blank node. An SDS operator has a target type from the schema.org vocabulary and contains one or more property shapes, each of which represents the definition of a local property on the target schema.org type. \begin{EBNF} \item[SDS] \<NodeShape>, \<SDOTargetType>, \<SDSPropertyShape>+; \item [NodeShape] \<Identifier>, \<NodeShapeType>; \item[Identifier] \spec {a URI} | \spec {a BlankNode}; \item[NodeShapeType] \spec{ URI of the SHACL NodeShape Type } \item[SDOTargetType] \spec{a class-based target whose value is a URI of type t is a regular type in T}; \end{EBNF} A property shape in an SDS consists of a schema.org property and one or more type specifications for the range of the property. It may also optionally contain a cardinality constraint to specify whether a property is required. A property shape may specify a range with multiple disjunctive types. \begin{EBNF} \item[SDSPropertyShape] \<SDOProperty>, \<CardinalityConstraint>?, (\<ValueTypeConstraint+> | \<SimpleDisjunctiveConstraint>); \item[SDOProperty] \spec{URI of property p where $p \in P$~}; \end{EBNF} A value type constraint enforces the type of a value. It requires the URI of a type in schema.org vocabulary as the value of sh:class parameter or the URI of an XSD datatype as the value of sh:datatype property. \begin{EBNF} \item [ValueTypeConstraint] \<SimpleClassConstraint> | \<DatatypeConstraint> ; \item[SimpleClassConstraint] \spec{A SHACL Class constraint with sh:class parameter and a value t where t is a regular type in T}; \item[DatatypeConstraint] \spec{A SHACL Datatype constraint with sh:datatype parameter and a value t where t is a datatype in T}; \end{EBNF} A cardinality constraint enforces the number of values a property can take. It takes only the integer 1 as value for sh:minCount parameters to specify minimum required value occurrences. \begin{EBNF} \item[CardinalityConstraint] \<MinCount>; \item[MinCount] \spec{minimum cardinality constraint with sh:minCount 1}; \end{EBNF} A simple disjunctive constraint applies logical OR operation to a given list of value type constraints. \begin{EBNF} \item[SimpleDisjunctiveConstraint] \spec{ OR(\<ValueTypeConstraint+>) } ; \end{EBNF} \subsection{Restricted Domain Specification (RDS)} \label{sec:rds} An RDS produces a restricted domain specific pattern by replacing one or more types in the range definitions of an SDSP with types from an external vocabulary. An external type (i.e. an element of the set $T_{ext}$) must be downwards compatible with the schema.org type that it replaces (i.e. the schema.org type could be used instead, in the data created based on the pattern). A type in $T_{ext}$ may be a part of an external extension of schema.org, meaning it is placed in schema.org's hierarchy. An external vocabulary is a pair $(T_{ext}, P_{ext}) $, where the types and properties are formalized in the same manner as schema.org vocabulary described in Section \ref{sec:schema-org}. An RDS defines $T'_r$, by replacing one or more elements of $T_r$ with a \\ $((type, property), rangeType')$ where $(type,property) \in T_p$ is the type-property pair whose range will be restricted and $rangeType' \in T_{ext}$. Assume there is a new type \texttt{n:HotelRoomProduct} \footnote{n is a prefix for an external vocabulary namespace}defined which is a conjunction of types \texttt{s:HotelRoom} and \texttt{s:Product} and is an element of $T_{ext}$. The type \texttt{n:Location} that is based on \texttt{s:Place} contains only the property \texttt{s:address}. Then, an RDF range restriction can be written as following\footnote{n:HotelRoomProduct is in the domain of all properties of s:HotelRoom and s:Product types. These properties, as well as all properties of s:PostalAddress are also in the domain specific pattern, but left out in the example for the sake of conciseness.}: \begin{equation} \begin{gathered} (\{((n:Location, s:address), s:PostalAddress),\\((s:Hotel, s:checkInTime), s:DateTime), \\((s:Hotel, s:checkOutTime), s:DateTime),\\ ((s:Hotel, s:containsPlace), n:HotelRoomProduct), \\((s:Hotel, s:location), n:Location),\\((s:Hotel, s:name), s:Text)\}) \end{gathered} \end{equation} The abstract syntax of an RDS operator is specified based on the abstract syntax of an SDS operator as follows: An RDS is a SHACL node shape with a target type from the schema.org vocabulary and one more property shapes. \begin{EBNF} \item[RDS] \<NodeShape>, \<SDOTargetType>, \<RDSPropertyShape>+; \end{EBNF} A property shape in an RDS extends a property shape in SDS with range restrictions. \begin{EBNF} \item[RDSPropertyShape] \<SDOProperty>, \<CardinalityConstraint>?, (\<ValueTypeConstraint> | \<RangeConstraint> | \<DisjunctiveConstraint>)+; \end{EBNF} A range constraint consists of a value type constraint that declares a type in the range and a node constraint that further restricts the specified type. \begin{EBNF} \item[RangeConstraint] \<ValueTypeConstraint>, \<NodeConstraint>; \item[NodeConstraint] \<NodeShape>, \<RDSPropertyShape>+; \end{EBNF} A disjunctive constraint extends a simple disjunctive constraint in an SDS by applying logical OR operator on a list of value type constraints and range restrictions. \begin{EBNF} \item[DisjunctiveConstraint] \spec{OR\{(\<ValueTypeConstraint> | \<RangeConstraint>)+\}} ; \end{EBNF} \subsection{Extended Domain Specification (EDS)} An EDS process generates an extended domain specific pattern by extending an SDSP or an RDSP through \begin{enumerate} \item adding new types and properties to define $T^{\cap\cup}$ and $ P^{\cap\cup}$ (Equation \ref{eq:eds-a}) \item defining new properties to an existing type to define $T^{\cup}_p$ (Equation \ref{eq:eds-b}) \item adding new types to the ranges of properties on an existing type to define $T^{\cup}_r$ (Equation \ref{eq:eds-c}) \end{enumerate} The types and properties may come from an external vocabulary as described in Section \ref{sec:rds}. There are two predicates in Equation \ref{eq:eds-b} and \ref{eq:eds-c} that help to build the sets for new properties for an existing type and new ranges on existing properties of existing types. The predicates $domain'$ and $range'$ hold true for the same conditions as defined for $domain^\cap$ and $range^\cap$ in Section \ref{sec:sds}, but for an external vocabulary instead of schema.org. Remember that, an external vocabulary can be an external extension of schema.org. \begin{equation} \label{eq:eds-a} \begin{gathered} T^{\cap\cup} = T^{\cap} \cup \{type' \in T_{ext}\}\\ P^{\cap\cup} = P^{\cap} \cup \{property' \in P_{ext}\} \end{gathered} \end{equation} \begin{equation} \label{eq:eds-b} \begin{gathered} T^{\cup}_p = T_p \cup \{(type', property') \in T_{ext} \times P_{ext} \colon domain'(property', type')\} \end{gathered} \end{equation} \begin{equation} \label{eq:eds-c} \begin{gathered} T^{\cup}_r = T_r \cup \{((type', property'), rangeType') \in T^{\cup}_p \times P_{ext} \colon range'(property', type')\} \end{gathered} \end{equation} The next example shows the definition of a property from an EDSP. It adds a new property, \texttt{n:totalNumberOfBeds}, to the type \texttt{s:Hotel} from an external extension of schema.org. \begin{equation} \begin{gathered} (\{((n:Location, s:address), s:PostalAddress),\\((s:Hotel, s:checkInTime), s:DateTime), \\((s:Hotel, s:checkOutTime), s:DateTime),\\ ((s:Hotel, s:containsPlace), n:HotelRoomProduct), \\((s:Hotel, s:location), n:Location),\\((s:Hotel, s:name), s:Text)\\((s:Hotel, n:totalNumberOfBeds), s:Number))\}) \end{gathered} \end{equation} An EDS operator extends an SDS or an RDS operators with types from an external vocabulary. Given the abstract syntaxes of these two operators, an EDS can be described as follows: \begin{EBNF} \item[EDS] \<NodeShape>, (\<SDOTargetType> | \<ExtTargetType>), \<EDSPropertyShape>+; \item[ExtTargetType] \spec{URI of type t where $t \in T_{ext}$}; \item[EDSPropertyShape] (\<SDOProperty> | \<ExtProperty>), \<CardinalityConstraint>?, (\<ExtValueTypeConstraint> | \<ExtRangeConstraint> | \<ExtDisjunctiveConstraint>)+; \item[ExtProperty] \spec{URI of property p where $p \in P_{ext}$}; \item[ExtValueTypeConstraint] \<SimpleClassConstraint> | \<ExtClassConstraint> | \<DatatypeConstraint>; \item[ExtClassConstraint] [A SHACL Class constraint with a value t where $t \in T_{ext}$]; \item [ExtRangeConstraint] \<ExtValueTypeConstraint>, \<ExtNodeConstraint>; \item[ExtNodeConstraint] \<NodeShape>, \<EDSPropertyShape>+; \item[ExtDisjunctiveConstraint] \spec{OR\{(\<ExtValueTypeConstraint> | \<ExtRangeConstraint>)+\}} \end{EBNF} \section{Use Cases and Examples} \label{sec:examples} In the section, we demonstrate domain specifications with examples and explain our current use cases and tooling. First we describe two different use cases where domain specific patterns have proven useful. Then we exemplify the domain specification process, particularly a concrete domain specification operator implemented with SHACL. \subsection{Web Content Annotations in Tourism} Domain specific patterns have been used in tourism domain by Destination Management Organizations (DMOs). The work in \cite{DBLP:conf/otm/AkbarKPSTF17} describes the generation of schema.org annotated tourism related data such as events, accommodation and infrastructure from raw data sources. The patterns have been used to guide the mapping process of the metadata of the IT solution provider of Mayrhofen DMO. The domain specifications are also used for manual generation of annotated data, through an editor that dynamically builds forms for annotation creation\footnote{https://actions.semantify.it/annotation/template/} based on domain specific patterns. The generated annotations have been used for the annotation of web pages for Search Engine Optimization and as a data source for a chatbot. The annotations created with the help of the domain specific patterns are evaluated qualitatively by observing search engine results. This use case shows a good example of making schema.org to fit a domain and suitable for different tasks such as consumption by chatbots. \subsection{DACH-KG and Schema-Tourism Working Groups} The DACH-KG working group\footnote{In German: https://www.tourismuszukunft.de/2018/11/dach-kg-auf-dem-weg-zum-touristischen-knowledge-graph/} was founded with the primary goal of building a touristic knowledge graph for the region of Austria, Germany and Switzerland (the DACH region). Several stakeholders in the tourism sector in the consortium is currently working on a unified schema to represent their data in the knowledge graph. Hence the current focus of this working group lies on identifying the mappings from their data to schema.org and defining best practices for further use of schema.org. Domain specifications help the DACH-KG to formalize their findings and disseminate their best practice patterns to data providers in their field. The schema-tourism working group was founded as a place for domain experts in tourism and researchers to commonly work on a) a unified way to use schema.org in the tourism domain and b) to identify shortcomings of schema.org and extend the vocabulary when needed. The findings of the working group are published as domain specific patterns and published online \footnote{https://ds.sti2.org}. There are currently 70 patterns created by the working group. The documentation follows the schema.org documentation style and provides a list of all available domain specific patterns including a short description. By clicking the title of a pattern, its description page is shown. This page lists all mandatory and recommended properties with their respective ranges. If a type in the range is restricted in the pattern, then a link leads to the respective description. Otherwise, the link leads to schema.org's description of the type. \subsection{Domain Specification Example} In this section we present the domain specification operator created by schema-tourism working group implemented in SHACL. The operator generates a domain-specific pattern for hotel data based on schema.org\footnote{The full pattern can be found here: https://ds.sti2.org/Sypf3bVG1z/Hotel} (Listing \ref{lst:example-rds}). Syntactically, the domain specification operator is a well-formed SHACL shape, therefore it can also be used as an input to a SHACL validator implementation. The datatypes of schema.org vocabulary are mapped to XSD datatypes in order to ensure the compatibility with existing tooling for SHACL. The example is an implementation of an RDS operator, however it is trivial to convert it to an EDS operator with an addition of a type or a property from an external vocabulary. The example operator in Listing \ref{lst:example-rds} defines five local properties on type Hotel and removes all other properties from the type. All defined properties are required except containsPlace. Then, the local ranges are defined on those locally defined properties in terms of value-type and shape-based constraints. The operator further restricts the ranges location and containsPlace properties by replacing the types in the original ranges. First, it replaces the range of the containsPlace property Place, with a type that is the conjunction of both Product and HotelRoom. Second, it further restricts the range of the location property by replacing it with a type that is based on Place that only allows the address property. The range of the address property is also restricted to allow only the properties addressCountry and addressLocality. The example here demonstrates the motivation for using local ranges. For a given task (e.g. a dialogue system for booking hotel rooms), a hotel contains only hotel rooms. Therefore it makes sense to restrict the range of the containsPlace property on a Hotel to the HotelRoom type. Since hotel rooms can also have offers, the conjunction of HotelRoom and Product types are needed for the range. This allows the usage of all properties of Product, including the offers property. On the domain dimension, generic complexity is reduced by eliminating different ways of representing an address of a Hotel and allowing it only via the location property. \begin{listing}[h] \begin{inputminted} [ fontsize=\scriptsize, bgcolor=white, breaklines, frame=single, ] {turtle} {examples/rds.ttl} \end{inputminted} \caption{An example domain specification operator based on schema:Hotel type for tourism domain} \vspace{-4mm} \label{lst:example-rds} \end{listing} \FloatBarrier \section{Related Work} \label{sec:related-work} Although there are not many tools and approaches targeting specifically restricting schema.org for content annotation, an informal definition of domain specification is made in \cite{10.1007/978-3-319-74313-4_31}. This approach only takes a subset of schema.org by removing types and properties. We define the domain specification process formally, and make clear conceptual distinction between the process of domain specification and resulting domain-specific patterns. Additionally, we do not only restrict but also allow extension of the schema.org vocabulary. In a similar direction a plethora of approaches for validating RDF data have been proposed. A popular direction that has been explored by researchers is defining constraints with SPARQL. The work in \cite{conf/bis/FurberH10} utilizes SPARQL for defining domain independent constraints to check various data quality dimensions. RDFUnit is a framework that mimics the unit tests in software engineering for RDF data by checking an RDF graph against test cases defined with SPARQL. Another direction is to using constraints directly as part of the schema language. OWL Flight \cite{DBLP:conf/www/BruijnLPF05} has been a proposed OWL dialect that expresses cardinality and range constraints on properties. Integrity Constraints in OWL \cite{DBLP:conf/aaai/TaoSBM10} describes an integrity constraint semantics for OWL restrictions to enable validation. As a result of the standardization efforts for RDF validation, SHACL \cite{bibSHACL} has been recommended by the W3C. SHACL facilitates the creation of data shapes for validating RDF data. SHACL specification does not define a formal semantics, even though there are some proposals \cite{BonevaS2016, cormanshacl2018}. SHACL shapes are informally converted into SPARQL queries. Similarly, the Shape Expressions (ShEx) \cite{prud2014shape, DBLP:conf/semweb/BonevaGP17} language is another shape language with an abstract syntax and formal semantics. Domain specific patterns can also be seen from the perspective of Ontology Design Patterns (ODPs). The main goal of ODPs is to improve the process of ontology development and its re-usability, linking data publishing, knowledge extraction, and knowledge engineering \cite{Gangemi_ODBforSWContent2005, hitzler2016ontology}. Content ODPs are used to solve recurrent content modelling problems \cite{hammar2017content}. The ontology design patterns can also be used to generate SHACL shapes for data validation over RDF datasets \cite{panditusing2018}. The domain specification approach proposed in this paper aims to bring a compact, formal solution for customizing a very large and heterogeneous vocabulary, the de-facto content annotation standard schema.org, for specific domains and tasks. Although such endeavor is related to RDF validation, the main focus here is not to validate a graph but rather create machine readable patterns for content and data annotations. The investigation of how the proposed approach can be used for creating Content ODPs is left as future work. We adopt the SHACL syntax in order to benefit its uptake and increasing tool support. \section{Conclusion and Future Work} \label{sec:conclusion} Schema.org is the de-facto industrial standard for annotating content and data. Due to its design, it is not very straight forward for data publishers to pick right types and properties for specific domains and tasks. To overcome this challenge, machine-readable domain specific patterns can guide the knowledge generation process and in a larger scale, the curation of a knowledge graph. In this paper, we proposed a formal approach, the domain specification process for generating aforementioned domain specific patterns. The domain specification process applies an operator implemented in SHACL to schema.org vocabulary, in order to reduce its generic complexity and restrict it for certain tasks. We presented our approach by formalizing different types of domain specification processes and giving an abstract syntax for domain specification operators based on SHACL. We demonstrated the utility of our approach by various use cases and examples. For the future work, we will work on specifying the fourth domain specification process, CDS, for defining more complex constraints such as inter-property value relations. Additionally, we will introduce frame-based semantics for the validation task. We will also improve the tooling for both creating domain specification operators and using them in generation and curation tasks. \bibliographystyle{splncs04}
{'timestamp': '2019-06-18T02:06:09', 'yymm': '1906', 'arxiv_id': '1906.06492', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06492'}
arxiv
\section{Introduction} Among the many uses of diffusion MRI, using tractography methods to depict the underlying white matter fiber tracts of tissues may be the most important. Procedures of identifying tracts are referred as to \textit{fiber tracking}. For clinical practice, fiber tracking provides potential benefits for presurgical planning \citep{chung2011principles}. In neuroscience, understanding the anatomical connection of the brain is an important component of the connectome \citep{sporns2005human}. Many technologies have been developed for fiber tracking in recent years. Among these methods, \code{DiST} (short for \textit{Diffusion Direction Smoothing and Tracking}) \citep{wong2016fiber} is one of the most prominent \citep{kang2016discussion,schwartzman2016discussion,lazar2016discussion}. \code{DiST} is composed of three major steps: In Step 1, voxel-wise diffusion directions are estimated using diffusion-weighted signals; In Step 2, the estimated diffusion directions obtained in Step 1 are smoothed over space; Finally in Step 3, the smoothed diffusion directions are taken as the inputs of a fiber tracking algorithm that determines if some voxels construct a fiber. Although \code{DiST} has many appealing features, it has some limitations \citep{kang2016discussion,lazar2016discussion,schwartzman2016discussion}. A major limitation may be that the separate steps of \code{DiST} make it difficult to properly account for statistical uncertainties. In light of this, we propose a Bayesian hierarchical approach which allows valid statistical inference for fiber tracking. First, we assume that the logarithm signals follow a normal distribution, simplifying the model by avoiding the challenging Rician distribution \citep{wong2016fiber}. Also, we induce spatial smoothness using a random field for spatially dependent positive definite matrices instead of the optimization-based smoothing procedure of \code{DiST}. This avoids the optimization issue raised by Schwartzman \citep{schwartzman2016discussion}. In the rest of the paper, we first introduce our method, referred as to \code{SpDiST} (short for \textit{Spatial Diffusion Direction Smoothing and Tracking}). To demonstrate our proposal, we use both real data analysis and a simulation study. The real data analysis demonstrates that our proposal provides a valid and efficient means to quantify the uncertainties of fiber tracking. Moreover, the simulation study shows that our proposal produces accurate estimation. Finally, we conclude with a discussion. \section{Method: \code{SpDiST}} \label{sec:method} \subsection{Spatial Tensor Model} \label{sec:step1} In this section, we introduce the spatial tensor model based on directed acyclic graph auto-regression for positive definite matrices. The diffusion MRI has $m\in\{1,2,...,M\}$ measurements at voxel $v\in\{1,2,...,n\}$, denoted as $S_{mv}\in\mathbb{R}^+$. The measurements $S_{mv}$ are used to estimate the diffusion tensor $\bm{A}_v$ for voxel $v$. $\bm{A}_v$ is a $3\times 3$ positive definite matrix interpreted as covariance matrix of a local Brownian motion, indicating the local tensor direction. The goal is to use the measurements $S_{mv}$ to obtain tensor direction information from $\bm{A}_v$. The noiseless signal intensity $\bar{S}_{mv}$ can be expressed in terms of $\bm{A}_v$ \citep{mori2007introduction} as $$\bar{S}_{mv}=S_{0v}\exp(-b\bm{g}_m^T\bm{A}_v\bm{g}_m).$$ In this expression, $S_{0v}$, $b$, and $\bm{g}_m$ are non-diffusion weighted intensity, scale parameter, and $3\times1$ unit-norm gradient vector, respectively. A detailed explanation of these three quantities can be found in Soares et al. \citep{soares2013hitchhiker}. Given $\bm{A}_v$, $\bar{S}_{mv}$ can be understood as the probability intensity of the Gaussian motion when measuring at direction $\bm{g}_v$. For statistical modeling, $S_{0v}$, $b$, and $\bm{g}_m$ can simply be understood as fixed and known values. The observations $S_{mv}$ are noisy realizations of $\bar{S}_{mv}$. The Rician distribution \citep{wong2016fiber} is reasonable for modeling $S_{mv}$ but it causes computational issues. Here, we assume that the noise is a multiplier to the $\bar{S}_{mv}$ and it follows a lognormal distribution. The model is \begin{equation} \label{eq:gaussian} \begin{aligned} \log S_{mv}= \log S_{0v}-b\bm{g}_m^T\bm{A}_v\bm{g}_m+\epsilon_{mv},\quad\epsilon_{mv}\stackrel{iid}{\sim}\mathcal{N}(0,\sigma^2), \end{aligned} \end{equation} where $\epsilon_{mv}$ is the noise following a mean-zero normal distribution with variance $\sigma^2$. To induce spatial smoothness, an image is treated as a directed graph whose nodes are voxels and whose directed edges are from node $v$ to nodes in $N(v)$. Following Datta et al. \citep{datta2017spatial}, we use the directed acyclic graph (directed and no loops) to construct to $N(v)$, leading to a valid joint density function of $[\bm{A}_1, \bm{A}_2,..., \bm{A}_n]$. In particular, we assume that the conditional mean of $\bm{A}_v$ is the average of its neighboring tensors, denoted as $\mathbb{E}[\bm{A}_v|\bm{A}_u,u\in N(v)]=\frac{1}{|N(v)|}\sum_{u\in N(v)}\bm{A}_u$, where $N(v)$ is a set containing neighboring voxel indices of voxel $v$, and $|N(v)|$ is the set size. In a directed acyclic graph, we have at least one voxel $v$ whose $N(v)$ is an empty set. For $N(v)$ is an empty set, we assume that $\bm{A}_{v}$ follows a Wishart distribution with mean matrix $\bm{I}$ and degrees of freedom $k$. Otherwise, conditional on $\bm{A}_u,u\in N(v)$, we assume that $\bm{A}_{v}$ follows a Wishart distribution with mean matrix $\bar{\bm{A}}_{v}=\frac{1}{|N(v)|}\sum_{u\in N(v)}\bm{A}_u$ and degrees of freedom $k$. The model is \begin{equation} \label{eq:rdf} \begin{aligned} \bm{A}_{v}|\bm{A}_u,u\in N(v)&\sim\mathcal{W}\left(\bar{\bm{A}}_{v},k\right)&\quad& \text{if $N(v)$ is not empty},\\ \bm{A}_{v}&\sim \mathcal{W}(\bm{I},k)&\quad& \text{if $N(v)$ is empty}. \end{aligned} \end{equation} In Equation (2), to preserve the designed mean realizations, we parameterize the Wishart distribution for $\bm{X}\sim\mathcal{W}(\bm{V},k)$ to have $\mathbb{E}\bm{X}=\bm{V}$. The probability density function is $${\displaystyle f(\mathbf {X} )={\frac {|\mathbf {X} |^{(k-p-1)/2}e^{-\operatorname {tr} ([\mathbf {V}/k] ^{-1}\mathbf {X} )/2}}{2^{\frac {kp}{2}}|{\mathbf {V}/k }|^{k/2}\Gamma _{p}({\frac {k}{2}})}}},$$ where $p$ is the matrix dimension and $\Gamma _{p}({\frac {k}{2}})$ is the multivariate gamma function. Here, we give an approach to construct a directed acyclic graph. For an image, we construct an undirected graph whose voxels are nodes, and the neighboring nodes are connected. We order the voxels by their coordinates, i.e., for a 2D image on a \textit{x-y} axis, we first order the voxels according to their coordinates of the \textit{y}-axis, then next we order the voxels according to their coordinates of the \textit{x}-axis. For each edge of the undirected graph, we modify the undirected edge to a directed edge which is from the node with a smaller rank to a node with a larger rank. The modified graph is a directed acyclic graph whose edges connect neighboring voxels. In Figure \ref{fig:graph}, we give an example describing how a directed acyclic graph for a $5\times 5$ image is constructed. \begin{figure}[t!] \centering \includegraphics[width=0.8\textwidth]{graph_example.png} \caption{The construction of a directed acyclic graph based on an undirected graph. The left panel is the undirected graph of a $5\times5$ image. The right pannel is the corresponding directed acyclic graph after modifying the edges.} \label{fig:graph} \end{figure} \subsubsection{MCMC Algorithm} We use MCMC for model fitting. We give $k\sim\mathcal{U}(3,50)$ and $\sigma^{-2}\sim\mathcal{GA}(0.01,0.01)$. The primary challenge in the MCMC algorithm is to sample the posterior of $\bm{A}_v$. Since the prior of $\bm{A}_v$ is not conjugate, we sample it using single-site Metropolis-Hastings sampling with Wishart distribution $\mathcal{W}(\bm{A}_v'|\bm{A}_v,q)$ as the proposal distribution. The algorithm is described below: \begin{description} \item[Candidate Generation:] Generate a candidate sample $\bm{A}_v'$ using $\bm{A}_v'\sim\mathcal{W}(\bm{A}_v'|\bm{A}_v,q)$; \item[Acceptance Rate:] Calculate the acceptance rate $r(\bm{A}_v',\bm{A}_v)=\frac{\mathcal{L}(\bm{A}_v'|.)\mathcal{W}(\bm{A}_v|\bm{A}_v',q)}{\mathcal{L}(\bm{A}_v|.)\mathcal{W}(\bm{A}_v'|\bm{A}_v,q)}$, where \begin{equation} \begin{aligned} \mathcal{L}(\bm{A}_v^*|.)&\propto\prod_{m=1}^M\mathcal{N}(\log S_{mv}|\log S_{0v}-b\bm{g}_m^T\bm{A}_v^*\bm{g}_m,\sigma^2)\times\\ &\mathcal{W}(\bm{A}_v^*|\bar{\bm{A}}_v^*,q)\prod_{u:v\in N(u)}\mathcal{W}(\bm{A}_u|\bar{\bm{A}}_u^*,q),\\ \end{aligned} \end{equation} where $\bar{\bm{A}}_u^*=\frac{\sum_{u\in N(u)/v} \bm{A}_u+ \bm{A}_v^*}{|N(v)|}$. $\mathcal{W}(.|\bm{A},\nu)$ and $\mathcal{N}(.|\mu,\sigma^2)$ are the density functions of Wishart distribution and normal distribution, respectively. \item[Decision:] Generate $u\sim\mathcal{U}(0,1)$. If $u<r(\bm{A}_v',\bm{A}_v)$, accept $\bm{A}_v'$. \end{description} The acceptance rate can be tuned by the degrees of freedom $q$, where smaller $q$ leads to smaller acceptance rate. We tune $q$ to make the acceptance rate around $0.4$. We use Metropolis-Hastings algorithm with log-normal random walk as proposal distribution to update the degrees of freedom $q$ and use Gibbs sampling to update $\sigma^2$ based on its posterior $[\sigma^{-2}|.]\sim \mathcal{GA}(Mn/2+0.01,\sum_{m,v}(\log S_{mv}-\log S_{0v}+b\bm{g}_m^T\bm{A}_v\bm{g}_m)^2/2+0.01)$. \subsection{Probabilistic Fiber Tracking Algorithm} \label{sec:step2} We collect the $T$ MCMC samples of $\bm{A}_v$, denoted as $\{\bm{A}_v^{(t)}:t=1,2,...,T\}$. For each sample, we compute the principal eigenvector of $\bm{A}_v^{(t)}$, denoted as $\bm{m}_v^{(t)}$. For each posterior draw, we use $\bm{m}_v^{(t)}$ as inputs of a fiber tracking algorithm. In this paper, we continue to use the Fiber Assignment by Continuous Tracking (FACT) \citep{mori1999three}, following Wong et al. \citep{wong2016fiber}. The algorithm can be stated as \begin{itemize} \item \textbf{Initialization:} Starting from \textit{seed voxels}; \item \textbf{Recursive:} Starting with voxel $u$, we search neighboring voxels and compute the two angles: $\delta_{uv}=\text{arccos}\left(\frac{\bm{m}_v^T\bm{m}_u}{|\bm{m}_v||\bm{m}_u|}\right)$ is the angle between the two tensor directions ($\bm{m}_u$ and $\bm{m}_u$) and $\theta_{uv}=\text{arccos}\left(\frac{\bm{m}_u^T\bm{l}_{u,v}}{|\bm{m}_u||\bm{l}_{u,v}|}\right)$ is the angle between the current tensor ($\bm{m}_u$) and between-voxel direction ($\bm{l}_{u,v}$). See Figure \ref{fig:angle} for details. We move to the voxels with $\theta<C$ and $\delta<C$. If there are multiple voxels statisfying this condition, we move to all the voxels and treat each voxel as a current voxel for next iteration.; \item \textbf{Result:} Sequences of voxels constructing \textit{fibers}. \end{itemize} Since we apply the algorithm for each posterior draw, the algorithm returns $T$ possible fibers. We summarize $K$ distinct patterns from the outputs and calculate the associated probability for pattern $k\in\{1,2,...,K\}$ defined as $\frac{T_k}{T}$, where $T_k$ is the frequency of the pattern $k$. This procedure is known as \textit{probabilistic fiber tracking} and quantifies the uncertainties of fiber tracking result. \begin{figure}[t!] \centering \includegraphics[width=0.5\textwidth]{angle.png} \caption{Two angles between two voxels. This figure is modified from Chung et al. \citep[][Figure 3]{chung2011principles}.} \label{fig:angle} \end{figure} \section{Real Data Application} \label{sec:real} In this section, we use a real data example \citep[][Section 6]{dryden2009non} to demonstrate our proposal. In particular, we focus on uncertainty quantification. The real data has $50\times20$ voxels and $M=15$ measurements. A detailed description can be found in Dryden et al. \citep[][Section 6]{dryden2009non}. We sample $2000$ MCMC samples after discarding $3000$ samples as burn-in and thin the MCMC chain by retaining every $100$ iterations of the chain. Since it is more efficient to visualize tensor directions in a 2D environment and the image is 2D, we focus on the first two dimensions of $\bm{A}_v$ and compute the corresponding principal eigenvector $\bm{m}_v$. To quantify the uncertainties of tensor direction estimation in each voxel, we overlay the MCMC samples on a $50\times20$ map (Figure \ref{fig:realfull}). In Figure \ref{fig:realfull}, the voxels with heterogeneous directions have large uncertainties. Otherwise, there are small uncertainties. \begin{figure} \centering \includegraphics[width=1\textwidth]{real_full.png} \caption{For each voxel, the MCMC samples of $\bm{m}_v$ are overlaid on the its location on a $50\times20$ map. For each voxel, we plot . The voxels with heterogeneous directions have large uncertainties. Otherwise, there are small uncertainties.} \label{fig:realfull} \end{figure} Figure \ref{fig:realfull} only provides voxel-wise uncertainties but our fully-Bayesian approach can propagate spatial uncertainties through to uncertainty in fiber tracking. In this way, the MCMC-based \code{SpDiST} also provides a probabilistic approach to quantifying the uncertainties of fiber tracking. To have a concise and representative illustration, we focus on the region in the orange box of Figure \ref{fig:realfull}. We apply the FACT algorithm as described in Section \ref{sec:step2}. In light of the conventions in setting the threshold $C$ \citep{chung2011principles}, we consider $C$ ranging from $18^o$ to $28^o$. There are two distinct patterns (Pattern A and Pattern B) for $C\in [18^o, 28^o]$ (Figure \ref{fig:realpartial}) as dominating the posterior probability of the tract. These two tracts differ only by how far the tract continues vertically in column 18. The probabilities of each pattern vary by different thresholds $C$. \begin{figure}[t!] \centering \includegraphics[width=1\textwidth]{real_partial.png} \caption{The consecutive orange arrows construct a fiber. Two patterns are identified, where the left pattern and the right pattern are denoted as Pattern A and Pattern B, respectively.} \label{fig:realpartial} \end{figure} Kang and Li \citep[][Section 3]{kang2016discussion} show that the FACT algorithm hinges on the tuning parameter $C$. It requires a sensitivity analysis to explore the impact of $C$. Here, we give a sensitivity analysis. We apply the FACT algorithm with $C=18+0.01\times s$ and $s=\{0,1,2,...,1000\}$. Since there are only two distinct patterns, we report the probabilities of Pattern B with different thresholds $C$ (Figure \ref{fig:sensitivity}). We find that the result is sensitive to the choice of $C$ unless it is ranging from $24^o$ to $28^o$. \begin{figure}[t!] \centering \includegraphics[width=1\textwidth]{sensitivity.png} \caption{The probability of Pattern B varies with different threshold $C$. When $C$ is ranging from $24^o$ to $28^o$ the probability is insensitive to $C$.} \label{fig:sensitivity} \end{figure} \section{Numerical Study} \label{sec:sim} \subsection{Data Description} In this section, we use synthetic diffusion-weighted signals in Wong et al. \citep[][S6]{wong2016fiber} and further modify them for our numerical study. In total, we have $8\times7\times2$ voxels where the three digits represent the dimension of $x$-axis, $y$-axis, and $z$-axis, respectively. The underlying tensors and fibers from the synthetic signals are displayed in Figure \ref{fig:sim}. A comprehensive description of example data generation can be found in Wong et al. \citep[][S6]{wong2016fiber} (i.e., generating model, parameters, true tensor directions, etc.). Here, we give a brief description. The fibers are essentially arcs with the center point at right/left bottom points. For voxels composing fibers, its principal eigenvector $\bm{m}_v$ is tangent to the arc. The noiseless signal in the example data is given as $\bar{S}_{mv}=S_{0v}\exp[-b(\bm{g}_m^T\bm{m}_v)^2]$, a reparameterized model of Model \ref{eq:gaussian} \citep{wong2016fiber}. \begin{figure}[t!] \centering \includegraphics[width=0.8\textwidth]{ttt.png} \caption{The tensor directions (left panel) and underlying fibers (right panel) of the example data .} \label{fig:sim} \end{figure} To mimic low-quality images with signal noise, we further add noise on the log scale simulated from a mean-zero normal distribution with standard deviation $\tau=0.1,0.5$. That is, the simulated data for each replication ($r=50$) is \begin{equation} \label{eq:noise} \log S_{mv}^{(r)}=\log \bar{S}_{mv}+E_{mv},\quad E_{mv}\sim\mathcal{N}(0,\tau^2), \end{equation} where $\log S_{mv}^{(r)}$ is the simulated signals for each replication ($r$), $\log S_{mv}$ is the logarithm signal from the example data, and $E_{mv}$ is simulated noise. \subsection{Simulation Details} We construct $N(v)$ as described before. We use the posterior mean estimate of \code{SpDiST} to compare with the estimates of alternatives. We compute posterior mean of $\bm{A}_v$ based on $2000$ MCMC samples after $3000$ samples as burn-in. In comparison, we compare our method to \code{DiST}. In addition, we also compare our method to a non-spatial method: the least squares method \citep{niethammer2006diffusion}. The least squares method \citep{niethammer2006diffusion} is to estimate $\bm{A}_v$ via $$\arg\min_{\bm{A}_v}\sum_m||\log S_{mv}-\log S_{0v}-b\bm{g}_m^T\bm{A}_v\bm{g}_m||^2.$$ For \code{DiST}, the estimates are the principal eigenvectors. To compare to \code{DiST}, for \code{SpDiST}, we compute the principal eigenvectors of the posterior means of diffusion tensor. For comparison, we also compute the principal eigenvector of the diffusion tensor estimate of the least squares method. \subsection{Results} To quantify the performance of the three methods, we introduce two metrics. For voxels with fiber directions, we use \textit{Metric 1} $$d_1(\bm{m}_v,\hat{\bm{m}}_v)=\text{arccos}(|\bm{m}_v^T\hat{\bm{m}}_v|),$$ a metric measuring acute angle between true tensor direction $\bm{m}_v$ and estimated $\hat{\bm{m}}_v$. A small $d_1(\bm{m}_v,\hat{\bm{m}}_v)$ indicates that the fiber direction is estimated accurately. We also introduce \textit{Metric 2} measuring the difference between true between-neighbor angle and estimated between-neighbor angle: $$d_2(\hat{\bm{m}}_v,\hat{\bm{m}}_u)=|\text{arccos}(|\hat{\bm{m}}_v^T\hat{\bm{m}}_u|)-\text{arccos}(|\bm{m}_v^T\bm{m}_u|)|,$$ where $u,v$ are neighbors. A small $d_2(\bm{m}_v,\hat{\bm{m}}_u)$ leads to an accurate decision if two voxels belong to the same fiber. We summarize the results in Table \ref{tab:result}, including the mean estimates by averaging over $50$ replications and the associated standard errors (in parentheses). From the result, we find that \code{SpDiST} and \code{DiST} have an overall better performance in comparison to the non-spatial method. From Table \ref{tab:result}, the \code{SpDiST} is more robust to noise, which may motivate a study on the robustness of tensor direction estimates based on different parameterization. However, the noise may have little effect on \textit{Metric 2}, leading to the same fiber tracking results. Although the \code{SpDiST} and \code{DiST} have similar performance, however, the MCMC-based \code{SpDiST} provides a means to quantify the uncertainties of fiber tracking, unlike \code{DiST}. \begin{table}[ht!] \caption{Summary of simulation results based on \textit{Metric 1} and \textit{Metric 2}. The mean estimates by averaging over $50$ replications and the associated standard errors (in parentheses) are summarized. \label{tab:result}} \centering \begin{tabular}{ccccc} \hline Metric & Noise ($\tau$) & \begin{tabular}[c]{@{}c@{}}Least \\ Square\end{tabular} & \code{SpDiST} & \code{DiST} \\ \hline \multirow{2}{*}{$d_1$}& \textit{0.1} & 0.09(0.007) & 0.08 (0.006) & 0.08(0.010) \\ & \textit{0.5} & 0.20(0.04) & 0.12(0.010) & 0.19(0.020)\\ \hline \multirow{2}{*}{$d_2$} & \textit{0.1} & 0.06 (0.005) & 0.06(0.014) & 0.06(0.012) \\ & \textit{0.5} & 0.24(0.05) & 0.08(0.010) & 0.09(0.015)\\ \hline \end{tabular} \end{table} \section{Discussion} \label{sec:diss} In the numerical study, we find that \code{DiST} and \code{SpDiST} have similar performances. However, the MCMC-based \code{SpDiST} provides a probabilistic means to quantify the result of fiber tracking. This provides some potentially important information for neuroscientists to understand brain anatomical connection. Furthermore, we also give a sensitivity analysis to the tuning parameter $C$, addressing the issue raised by Kang and Li \citep{kang2016discussion}. Although the current methodologies might be sufficient for preliminary fiber tracking, there are still several issues. One problem is that the current methods focus on developing an imaging processing tool but not on scientifically and statistically explaining the outcomes \citep{lazar2016discussion}. However, proposing a statistical approach which characterizes factors affecting the outcomes might be critical in further studies, providing more insightful information in neuroscience. However, this is challenging because to incorporate covariates in the model and to properly combine the model to a fiber tracking algorithm are not straightforward. Another issue is crossing fibers. That is the single tensor model \citep{mori1999three} fails to account for voxels where there are multiple fibers. Although it is assumed that increasing the resolution of the image may handle this issue, Schilling et al. \citep{schilling2017can} give an unexpected result that increasing the resolution is not a solution. This needs to be rigorously studied with close interdisciplinary collaboration. \input{output.bbl} \end{document} \section{Introduction} Among the many uses of diffusion MRI, using tractography methods to depict the underlying white matter fiber tracts of tissues may be the most important. Procedures of identifying tracts are referred as to \textit{fiber tracking}. For clinical practice, fiber tracking provides potential benefits for presurgical planning \citep{chung2011principles}. In neuroscience, understanding the anatomical connection of the brain is an important component of the connectome \citep{sporns2005human}. Many technologies have been developed for fiber tracking in recent years. Among these methods, \code{DiST} (short for \textit{Diffusion Direction Smoothing and Tracking}) \citep{wong2016fiber} is one of the most prominent \citep{kang2016discussion,schwartzman2016discussion,lazar2016discussion}. \code{DiST} is composed of three major steps: In Step 1, voxel-wise diffusion directions are estimated using diffusion-weighted signals; In Step 2, the estimated diffusion directions obtained in Step 1 are smoothed over space; Finally in Step 3, the smoothed diffusion directions are taken as the inputs of a fiber tracking algorithm that determines if some voxels construct a fiber. Although \code{DiST} has many appealing features, it has some limitations \citep{kang2016discussion,lazar2016discussion,schwartzman2016discussion}. A major limitation may be that the separate steps of \code{DiST} make it difficult to properly account for statistical uncertainties. In light of this, we propose a Bayesian hierarchical approach which allows valid statistical inference for fiber tracking. First, we assume that the logarithm signals follow a normal distribution, simplifying the model by avoiding the challenging Rician distribution \citep{wong2016fiber}. Also, we induce spatial smoothness using a random field for spatially dependent positive definite matrices instead of the optimization-based smoothing procedure of \code{DiST}. This avoids the optimization issue raised by Schwartzman \citep{schwartzman2016discussion}. In the rest of the paper, we first introduce our method, referred as to \code{SpDiST} (short for \textit{Spatial Diffusion Direction Smoothing and Tracking}). To demonstrate our proposal, we use both real data analysis and a simulation study. The real data analysis demonstrates that our proposal provides a valid and efficient means to quantify the uncertainties of fiber tracking. Moreover, the simulation study shows that our proposal produces accurate estimation. Finally, we conclude with a discussion. \section{Method: \code{SpDiST}} \label{sec:method} \subsection{Spatial Tensor Model} \label{sec:step1} In this section, we introduce the spatial tensor model based on directed acyclic graph auto-regression for positive definite matrices. The diffusion MRI has $m\in\{1,2,...,M\}$ measurements at voxel $v\in\{1,2,...,n\}$, denoted as $S_{mv}\in\mathbb{R}^+$. The measurements $S_{mv}$ are used to estimate the diffusion tensor $\bm{A}_v$ for voxel $v$. $\bm{A}_v$ is a $3\times 3$ positive definite matrix interpreted as covariance matrix of a local Brownian motion, indicating the local tensor direction. The goal is to use the measurements $S_{mv}$ to obtain tensor direction information from $\bm{A}_v$. The noiseless signal intensity $\bar{S}_{mv}$ can be expressed in terms of $\bm{A}_v$ \citep{mori2007introduction} as $$\bar{S}_{mv}=S_{0v}\exp(-b\bm{g}_m^T\bm{A}_v\bm{g}_m).$$ In this expression, $S_{0v}$, $b$, and $\bm{g}_m$ are non-diffusion weighted intensity, scale parameter, and $3\times1$ unit-norm gradient vector, respectively. A detailed explanation of these three quantities can be found in Soares et al. \citep{soares2013hitchhiker}. Given $\bm{A}_v$, $\bar{S}_{mv}$ can be understood as the probability intensity of the Gaussian motion when measuring at direction $\bm{g}_v$. For statistical modeling, $S_{0v}$, $b$, and $\bm{g}_m$ can simply be understood as fixed and known values. The observations $S_{mv}$ are noisy realizations of $\bar{S}_{mv}$. The Rician distribution \citep{wong2016fiber} is reasonable for modeling $S_{mv}$ but it causes computational issues. Here, we assume that the noise is a multiplier to the $\bar{S}_{mv}$ and it follows a lognormal distribution. The model is \begin{equation} \label{eq:gaussian} \begin{aligned} \log S_{mv}= \log S_{0v}-b\bm{g}_m^T\bm{A}_v\bm{g}_m+\epsilon_{mv},\quad\epsilon_{mv}\stackrel{iid}{\sim}\mathcal{N}(0,\sigma^2), \end{aligned} \end{equation} where $\epsilon_{mv}$ is the noise following a mean-zero normal distribution with variance $\sigma^2$. To induce spatial smoothness, an image is treated as a directed graph whose nodes are voxels and whose directed edges are from node $v$ to nodes in $N(v)$. Following Datta et al. \citep{datta2017spatial}, we use the directed acyclic graph (directed and no loops) to construct to $N(v)$, leading to a valid joint density function of $[\bm{A}_1, \bm{A}_2,..., \bm{A}_n]$. In particular, we assume that the conditional mean of $\bm{A}_v$ is the average of its neighboring tensors, denoted as $\mathbb{E}[\bm{A}_v|\bm{A}_u,u\in N(v)]=\frac{1}{|N(v)|}\sum_{u\in N(v)}\bm{A}_u$, where $N(v)$ is a set containing neighboring voxel indices of voxel $v$, and $|N(v)|$ is the set size. In a directed acyclic graph, we have at least one voxel $v$ whose $N(v)$ is an empty set. For $N(v)$ is an empty set, we assume that $\bm{A}_{v}$ follows a Wishart distribution with mean matrix $\bm{I}$ and degrees of freedom $k$. Otherwise, conditional on $\bm{A}_u,u\in N(v)$, we assume that $\bm{A}_{v}$ follows a Wishart distribution with mean matrix $\bar{\bm{A}}_{v}=\frac{1}{|N(v)|}\sum_{u\in N(v)}\bm{A}_u$ and degrees of freedom $k$. The model is \begin{equation} \label{eq:rdf} \begin{aligned} \bm{A}_{v}|\bm{A}_u,u\in N(v)&\sim\mathcal{W}\left(\bar{\bm{A}}_{v},k\right)&\quad& \text{if $N(v)$ is not empty},\\ \bm{A}_{v}&\sim \mathcal{W}(\bm{I},k)&\quad& \text{if $N(v)$ is empty}. \end{aligned} \end{equation} In Equation (2), to preserve the designed mean realizations, we parameterize the Wishart distribution for $\bm{X}\sim\mathcal{W}(\bm{V},k)$ to have $\mathbb{E}\bm{X}=\bm{V}$. The probability density function is $${\displaystyle f(\mathbf {X} )={\frac {|\mathbf {X} |^{(k-p-1)/2}e^{-\operatorname {tr} ([\mathbf {V}/k] ^{-1}\mathbf {X} )/2}}{2^{\frac {kp}{2}}|{\mathbf {V}/k }|^{k/2}\Gamma _{p}({\frac {k}{2}})}}},$$ where $p$ is the matrix dimension and $\Gamma _{p}({\frac {k}{2}})$ is the multivariate gamma function. Here, we give an approach to construct a directed acyclic graph. For an image, we construct an undirected graph whose voxels are nodes, and the neighboring nodes are connected. We order the voxels by their coordinates, i.e., for a 2D image on a \textit{x-y} axis, we first order the voxels according to their coordinates of the \textit{y}-axis, then next we order the voxels according to their coordinates of the \textit{x}-axis. For each edge of the undirected graph, we modify the undirected edge to a directed edge which is from the node with a smaller rank to a node with a larger rank. The modified graph is a directed acyclic graph whose edges connect neighboring voxels. In Figure \ref{fig:graph}, we give an example describing how a directed acyclic graph for a $5\times 5$ image is constructed. \begin{figure}[t!] \centering \includegraphics[width=0.8\textwidth]{graph_example.png} \caption{The construction of a directed acyclic graph based on an undirected graph. The left panel is the undirected graph of a $5\times5$ image. The right pannel is the corresponding directed acyclic graph after modifying the edges.} \label{fig:graph} \end{figure} \subsubsection{MCMC Algorithm} We use MCMC for model fitting. We give $k\sim\mathcal{U}(3,50)$ and $\sigma^{-2}\sim\mathcal{GA}(0.01,0.01)$. The primary challenge in the MCMC algorithm is to sample the posterior of $\bm{A}_v$. Since the prior of $\bm{A}_v$ is not conjugate, we sample it using single-site Metropolis-Hastings sampling with Wishart distribution $\mathcal{W}(\bm{A}_v'|\bm{A}_v,q)$ as the proposal distribution. The algorithm is described below: \begin{description} \item[Candidate Generation:] Generate a candidate sample $\bm{A}_v'$ using $\bm{A}_v'\sim\mathcal{W}(\bm{A}_v'|\bm{A}_v,q)$; \item[Acceptance Rate:] Calculate the acceptance rate $r(\bm{A}_v',\bm{A}_v)=\frac{\mathcal{L}(\bm{A}_v'|.)\mathcal{W}(\bm{A}_v|\bm{A}_v',q)}{\mathcal{L}(\bm{A}_v|.)\mathcal{W}(\bm{A}_v'|\bm{A}_v,q)}$, where \begin{equation} \begin{aligned} \mathcal{L}(\bm{A}_v^*|.)&\propto\prod_{m=1}^M\mathcal{N}(\log S_{mv}|\log S_{0v}-b\bm{g}_m^T\bm{A}_v^*\bm{g}_m,\sigma^2)\times\\ &\mathcal{W}(\bm{A}_v^*|\bar{\bm{A}}_v^*,q)\prod_{u:v\in N(u)}\mathcal{W}(\bm{A}_u|\bar{\bm{A}}_u^*,q),\\ \end{aligned} \end{equation} where $\bar{\bm{A}}_u^*=\frac{\sum_{u\in N(u)/v} \bm{A}_u+ \bm{A}_v^*}{|N(v)|}$. $\mathcal{W}(.|\bm{A},\nu)$ and $\mathcal{N}(.|\mu,\sigma^2)$ are the density functions of Wishart distribution and normal distribution, respectively. \item[Decision:] Generate $u\sim\mathcal{U}(0,1)$. If $u<r(\bm{A}_v',\bm{A}_v)$, accept $\bm{A}_v'$. \end{description} The acceptance rate can be tuned by the degrees of freedom $q$, where smaller $q$ leads to smaller acceptance rate. We tune $q$ to make the acceptance rate around $0.4$. We use Metropolis-Hastings algorithm with log-normal random walk as proposal distribution to update the degrees of freedom $q$ and use Gibbs sampling to update $\sigma^2$ based on its posterior $[\sigma^{-2}|.]\sim \mathcal{GA}(Mn/2+0.01,\sum_{m,v}(\log S_{mv}-\log S_{0v}+b\bm{g}_m^T\bm{A}_v\bm{g}_m)^2/2+0.01)$. \subsection{Probabilistic Fiber Tracking Algorithm} \label{sec:step2} We collect the $T$ MCMC samples of $\bm{A}_v$, denoted as $\{\bm{A}_v^{(t)}:t=1,2,...,T\}$. For each sample, we compute the principal eigenvector of $\bm{A}_v^{(t)}$, denoted as $\bm{m}_v^{(t)}$. For each posterior draw, we use $\bm{m}_v^{(t)}$ as inputs of a fiber tracking algorithm. In this paper, we continue to use the Fiber Assignment by Continuous Tracking (FACT) \citep{mori1999three}, following Wong et al. \citep{wong2016fiber}. The algorithm can be stated as \begin{itemize} \item \textbf{Initialization:} Starting from \textit{seed voxels}; \item \textbf{Recursive:} Starting with voxel $u$, we search neighboring voxels and compute the two angles: $\delta_{uv}=\text{arccos}\left(\frac{\bm{m}_v^T\bm{m}_u}{|\bm{m}_v||\bm{m}_u|}\right)$ is the angle between the two tensor directions ($\bm{m}_u$ and $\bm{m}_u$) and $\theta_{uv}=\text{arccos}\left(\frac{\bm{m}_u^T\bm{l}_{u,v}}{|\bm{m}_u||\bm{l}_{u,v}|}\right)$ is the angle between the current tensor ($\bm{m}_u$) and between-voxel direction ($\bm{l}_{u,v}$). See Figure \ref{fig:angle} for details. We move to the voxels with $\theta<C$ and $\delta<C$. If there are multiple voxels statisfying this condition, we move to all the voxels and treat each voxel as a current voxel for next iteration.; \item \textbf{Result:} Sequences of voxels constructing \textit{fibers}. \end{itemize} Since we apply the algorithm for each posterior draw, the algorithm returns $T$ possible fibers. We summarize $K$ distinct patterns from the outputs and calculate the associated probability for pattern $k\in\{1,2,...,K\}$ defined as $\frac{T_k}{T}$, where $T_k$ is the frequency of the pattern $k$. This procedure is known as \textit{probabilistic fiber tracking} and quantifies the uncertainties of fiber tracking result. \begin{figure}[t!] \centering \includegraphics[width=0.5\textwidth]{angle.png} \caption{Two angles between two voxels. This figure is modified from Chung et al. \citep[][Figure 3]{chung2011principles}.} \label{fig:angle} \end{figure} \section{Real Data Application} \label{sec:real} In this section, we use a real data example \citep[][Section 6]{dryden2009non} to demonstrate our proposal. In particular, we focus on uncertainty quantification. The real data has $50\times20$ voxels and $M=15$ measurements. A detailed description can be found in Dryden et al. \citep[][Section 6]{dryden2009non}. We sample $2000$ MCMC samples after discarding $3000$ samples as burn-in and thin the MCMC chain by retaining every $100$ iterations of the chain. Since it is more efficient to visualize tensor directions in a 2D environment and the image is 2D, we focus on the first two dimensions of $\bm{A}_v$ and compute the corresponding principal eigenvector $\bm{m}_v$. To quantify the uncertainties of tensor direction estimation in each voxel, we overlay the MCMC samples on a $50\times20$ map (Figure \ref{fig:realfull}). In Figure \ref{fig:realfull}, the voxels with heterogeneous directions have large uncertainties. Otherwise, there are small uncertainties. \begin{figure} \centering \includegraphics[width=1\textwidth]{real_full.png} \caption{For each voxel, the MCMC samples of $\bm{m}_v$ are overlaid on the its location on a $50\times20$ map. For each voxel, we plot . The voxels with heterogeneous directions have large uncertainties. Otherwise, there are small uncertainties.} \label{fig:realfull} \end{figure} Figure \ref{fig:realfull} only provides voxel-wise uncertainties but our fully-Bayesian approach can propagate spatial uncertainties through to uncertainty in fiber tracking. In this way, the MCMC-based \code{SpDiST} also provides a probabilistic approach to quantifying the uncertainties of fiber tracking. To have a concise and representative illustration, we focus on the region in the orange box of Figure \ref{fig:realfull}. We apply the FACT algorithm as described in Section \ref{sec:step2}. In light of the conventions in setting the threshold $C$ \citep{chung2011principles}, we consider $C$ ranging from $18^o$ to $28^o$. There are two distinct patterns (Pattern A and Pattern B) for $C\in [18^o, 28^o]$ (Figure \ref{fig:realpartial}) as dominating the posterior probability of the tract. These two tracts differ only by how far the tract continues vertically in column 18. The probabilities of each pattern vary by different thresholds $C$. \begin{figure}[t!] \centering \includegraphics[width=1\textwidth]{real_partial.png} \caption{The consecutive orange arrows construct a fiber. Two patterns are identified, where the left pattern and the right pattern are denoted as Pattern A and Pattern B, respectively.} \label{fig:realpartial} \end{figure} Kang and Li \citep[][Section 3]{kang2016discussion} show that the FACT algorithm hinges on the tuning parameter $C$. It requires a sensitivity analysis to explore the impact of $C$. Here, we give a sensitivity analysis. We apply the FACT algorithm with $C=18+0.01\times s$ and $s=\{0,1,2,...,1000\}$. Since there are only two distinct patterns, we report the probabilities of Pattern B with different thresholds $C$ (Figure \ref{fig:sensitivity}). We find that the result is sensitive to the choice of $C$ unless it is ranging from $24^o$ to $28^o$. \begin{figure}[t!] \centering \includegraphics[width=1\textwidth]{sensitivity.png} \caption{The probability of Pattern B varies with different threshold $C$. When $C$ is ranging from $24^o$ to $28^o$ the probability is insensitive to $C$.} \label{fig:sensitivity} \end{figure} \section{Numerical Study} \label{sec:sim} \subsection{Data Description} In this section, we use synthetic diffusion-weighted signals in Wong et al. \citep[][S6]{wong2016fiber} and further modify them for our numerical study. In total, we have $8\times7\times2$ voxels where the three digits represent the dimension of $x$-axis, $y$-axis, and $z$-axis, respectively. The underlying tensors and fibers from the synthetic signals are displayed in Figure \ref{fig:sim}. A comprehensive description of example data generation can be found in Wong et al. \citep[][S6]{wong2016fiber} (i.e., generating model, parameters, true tensor directions, etc.). Here, we give a brief description. The fibers are essentially arcs with the center point at right/left bottom points. For voxels composing fibers, its principal eigenvector $\bm{m}_v$ is tangent to the arc. The noiseless signal in the example data is given as $\bar{S}_{mv}=S_{0v}\exp[-b(\bm{g}_m^T\bm{m}_v)^2]$, a reparameterized model of Model \ref{eq:gaussian} \citep{wong2016fiber}. \begin{figure}[t!] \centering \includegraphics[width=0.8\textwidth]{ttt.png} \caption{The tensor directions (left panel) and underlying fibers (right panel) of the example data .} \label{fig:sim} \end{figure} To mimic low-quality images with signal noise, we further add noise on the log scale simulated from a mean-zero normal distribution with standard deviation $\tau=0.1,0.5$. That is, the simulated data for each replication ($r=50$) is \begin{equation} \label{eq:noise} \log S_{mv}^{(r)}=\log \bar{S}_{mv}+E_{mv},\quad E_{mv}\sim\mathcal{N}(0,\tau^2), \end{equation} where $\log S_{mv}^{(r)}$ is the simulated signals for each replication ($r$), $\log S_{mv}$ is the logarithm signal from the example data, and $E_{mv}$ is simulated noise. \subsection{Simulation Details} We construct $N(v)$ as described before. We use the posterior mean estimate of \code{SpDiST} to compare with the estimates of alternatives. We compute posterior mean of $\bm{A}_v$ based on $2000$ MCMC samples after $3000$ samples as burn-in. In comparison, we compare our method to \code{DiST}. In addition, we also compare our method to a non-spatial method: the least squares method \citep{niethammer2006diffusion}. The least squares method \citep{niethammer2006diffusion} is to estimate $\bm{A}_v$ via $$\arg\min_{\bm{A}_v}\sum_m||\log S_{mv}-\log S_{0v}-b\bm{g}_m^T\bm{A}_v\bm{g}_m||^2.$$ For \code{DiST}, the estimates are the principal eigenvectors. To compare to \code{DiST}, for \code{SpDiST}, we compute the principal eigenvectors of the posterior means of diffusion tensor. For comparison, we also compute the principal eigenvector of the diffusion tensor estimate of the least squares method. \subsection{Results} To quantify the performance of the three methods, we introduce two metrics. For voxels with fiber directions, we use \textit{Metric 1} $$d_1(\bm{m}_v,\hat{\bm{m}}_v)=\text{arccos}(|\bm{m}_v^T\hat{\bm{m}}_v|),$$ a metric measuring acute angle between true tensor direction $\bm{m}_v$ and estimated $\hat{\bm{m}}_v$. A small $d_1(\bm{m}_v,\hat{\bm{m}}_v)$ indicates that the fiber direction is estimated accurately. We also introduce \textit{Metric 2} measuring the difference between true between-neighbor angle and estimated between-neighbor angle: $$d_2(\hat{\bm{m}}_v,\hat{\bm{m}}_u)=|\text{arccos}(|\hat{\bm{m}}_v^T\hat{\bm{m}}_u|)-\text{arccos}(|\bm{m}_v^T\bm{m}_u|)|,$$ where $u,v$ are neighbors. A small $d_2(\bm{m}_v,\hat{\bm{m}}_u)$ leads to an accurate decision if two voxels belong to the same fiber. We summarize the results in Table \ref{tab:result}, including the mean estimates by averaging over $50$ replications and the associated standard errors (in parentheses). From the result, we find that \code{SpDiST} and \code{DiST} have an overall better performance in comparison to the non-spatial method. From Table \ref{tab:result}, the \code{SpDiST} is more robust to noise, which may motivate a study on the robustness of tensor direction estimates based on different parameterization. However, the noise may have little effect on \textit{Metric 2}, leading to the same fiber tracking results. Although the \code{SpDiST} and \code{DiST} have similar performance, however, the MCMC-based \code{SpDiST} provides a means to quantify the uncertainties of fiber tracking, unlike \code{DiST}. \begin{table}[ht!] \caption{Summary of simulation results based on \textit{Metric 1} and \textit{Metric 2}. The mean estimates by averaging over $50$ replications and the associated standard errors (in parentheses) are summarized. \label{tab:result}} \centering \begin{tabular}{ccccc} \hline Metric & Noise ($\tau$) & \begin{tabular}[c]{@{}c@{}}Least \\ Square\end{tabular} & \code{SpDiST} & \code{DiST} \\ \hline \multirow{2}{*}{$d_1$}& \textit{0.1} & 0.09(0.007) & 0.08 (0.006) & 0.08(0.010) \\ & \textit{0.5} & 0.20(0.04) & 0.12(0.010) & 0.19(0.020)\\ \hline \multirow{2}{*}{$d_2$} & \textit{0.1} & 0.06 (0.005) & 0.06(0.014) & 0.06(0.012) \\ & \textit{0.5} & 0.24(0.05) & 0.08(0.010) & 0.09(0.015)\\ \hline \end{tabular} \end{table} \section{Discussion} \label{sec:diss} In the numerical study, we find that \code{DiST} and \code{SpDiST} have similar performances. However, the MCMC-based \code{SpDiST} provides a probabilistic means to quantify the result of fiber tracking. This provides some potentially important information for neuroscientists to understand brain anatomical connection. Furthermore, we also give a sensitivity analysis to the tuning parameter $C$, addressing the issue raised by Kang and Li \citep{kang2016discussion}. Although the current methodologies might be sufficient for preliminary fiber tracking, there are still several issues. One problem is that the current methods focus on developing an imaging processing tool but not on scientifically and statistically explaining the outcomes \citep{lazar2016discussion}. However, proposing a statistical approach which characterizes factors affecting the outcomes might be critical in further studies, providing more insightful information in neuroscience. However, this is challenging because to incorporate covariates in the model and to properly combine the model to a fiber tracking algorithm are not straightforward. Another issue is crossing fibers. That is the single tensor model \citep{mori1999three} fails to account for voxels where there are multiple fibers. Although it is assumed that increasing the resolution of the image may handle this issue, Schilling et al. \citep{schilling2017can} give an unexpected result that increasing the resolution is not a solution. This needs to be rigorously studied with close interdisciplinary collaboration. \input{output.bbl} \end{document}
{'timestamp': '2019-06-18T02:04:41', 'yymm': '1906', 'arxiv_id': '1906.06459', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06459'}
arxiv
\section{Introduction}\label{sec:Introduction} Both $k$NN queries and skyline queries are important operators with many applications in computer science. Given a dataset $P$ of multi-dimensional objects or points, $k$NN returns the $k$ points closest to a query point given a scoring function. One commonly used scoring function is \emph{weighted sum} of the attributes, where the weights indicate the importance of attributes. For a point $p$ in a $d$ dimensional space $p=(p[1],p[2],...,p[d])$, given an attribute weight vector $\textbf{w}=\langle w[1],w[2],...,w[d]\rangle$, the weighted sum $S(p)$ is defined as $S(p)=\sum_{i=1}^dp[i]w[i]$ (assuming the origin is the query point). $k$NN returns the $k$ points with smallest $S(p)$. When $k=1$, we also call it $1$NN query. One drawback of $1$NN (and $k$NN in general) is its dependence on the exact scoring function. Skyline query is an alternative solution involving multi-criteria decision making without relying on a specific scoring function. Considering the origin as the query point again, skyline consists all Pareto-nearest points that are not dominated by any other point, and a point $p$ dominates another point $p' (p\neq p')$ if it is at least closer to the query point on one dimension and as close on all the other dimensions. It has been recognized that $1$NN and skyline each has its advantage but also comes with a cost: 1) $1$NN returns the exact nearest neighbor but depends on a predefined attribute weight vector which can be too specific in practice; 2) skyline returns all possible nearest neighbors without requiring any attribute weight vector but the number of returned points can be prohibitively large, in the worst case, the whole data set being returned. It is desirable to have a more flexible and customizable generalization to satisfy users' diverse needs. \partitle{Motivating example} Assume a conference organizer needs to recommend a set of hotels for conference participants based on the distance to the conference site and price. Note that we use two dimensional case in our running examples. Figure \ref{fig:1nn} shows a dataset $P=\{p_1,p_2,...,p_4\}$, each representing a hotel with the two attributes. The organizer can use $k$NN queries and specify an attribute weight vector such as $\textbf{w}=\langle 2,1\rangle$ or attribute weight ratio $r=w[1]/w[2]=2$ indicating distance is twice more important than price. In this case, $p_1$ has the smallest score $S(p_1)=8$ and is the nearest neighbor. We can also visualize $S(p)$ in a two dimensional space. If we draw a score line over a point $p$ with slope $-2$, $S(p)$ is essentially its y-intercept. The nearest neighbor is hence $p_1$ which has the smallest y-intercept as shown in Figure \ref{fig:1nn}(b). \vspace{-1em} \begin{figure}[htb] \centering \includegraphics[width=0.35\textwidth]{1nn} \vspace{-1em} \caption{$1$NN query.} \label{fig:1nn} \end{figure} \vspace{-1em} The organizer can also use skyline queries to retrieve all hotels not dominated by others since the preferences of the participants are unknown. Figure \ref{fig:Skyline} shows the same dataset as in Figure \ref{fig:1nn}. Given a point $p$, any point lying on the upper right corner of $p$ is dominated by $p$. Hence, $p_1$, $p_2$, and $p_3$ are the skyline points as they are not dominated by any other point. \vspace{-1em} \begin{figure}[htb] \centering \includegraphics[width=0.35\textwidth]{skyline} \vspace{-1em} \caption{Skyline query.} \label{fig:Skyline} \end{figure} \vspace{-1em} We can see that both solutions above are inflexible and cannot be customized. The definitions are either too specific to one ranking function (as in $1$NN) or taking no ranking function at all (as in skyline). \emph{If the organizer knows that price is more important than distance to all student participants but the relative importance varies from one student to another, neither $1$NN nor skyline can incorporate this kind of preference ``range''}. One may think that $k$NN provides certain flexibility or relaxation for $1$NN by selecting the top $k$ solutions. However, it only provides flexibility on the ``depth'' in that it selects the next best solutions with respect to the same exact attribute weights. What is desired here is the flexibility on the ``breadth'' of the attribute weights which can capture a user's rough preference among the attributes. \partitle{Contributions} In this paper, we propose a novel notion of eclipse\footnote{``eclipse'' comes from solar eclipse and lunar eclipse, we take its notion of ``partial'' to highlight the customizability of our query definition.} that generalizes the classic 1NN and skyline queries while providing a more flexible and customizable query solution for users. We first show a generalized definition of $1$NN and skyline through the notion of domination and then introduce our eclipse definition. For the $1$NN query, we can say $p$ $1$NN-dominates $p'$, if $S(p)< S(p')$ for a given attribute weight ratio $r=l$ (or $r\in [l,l]$). We assume two dimensional space for example here. For the skyline query, we can easily see that if $p$ dominates (we explicitly say skyline-dominates to differentiate from $1$NN-dominates) $p'$, we have $S(p)\leq S(p')$ for all attribute weight ratio $r\in [0,+\infty)$ given a linear scoring function or any monotonic scoring function. In other words, any point lying on the upper right half of the score line of $p$ (with a flat angle) is $1$NN-dominated by $p$ (Figure \ref{fig:1nn}). Any point lying on the upper right quadrant of $p$ (with a right angle) is skyline-dominated by $p$ (Figure \ref{fig:Skyline}). Both $1$NN and skyline can be defined as those points that are not dominated by any other point. Table \ref{tab:definitions} shows the comparison. \vspace{-1em} \begin{table}[htb]\centering \caption{Definitions.}\label{tab:definitions} \vspace{-1em} {% \begin{tabular}{|c|c|c|} \hline & domination weight ratio & domination range\\ \hline $1$NN & $[l,l]$ & flat angle\\ \hline skyline & $[0,+\infty)$ & right angle \\ \hline eclipse & $[l,h]$ & obtuse angle\\ \hline \end{tabular}} \end{table}% \vspace{-1em} Based on this generalized notion of dominance, we propose the eclipse query. We say $p$ eclipse-dominates $p'$, if $S(p)\leq S(p')$ for all $r \in [l,h]$, where $[l,h]$ is a range for the attribute weight ratio. The eclipse points are those points that are not eclipse-dominated by any other point in $P$. Intuitively, the range of $[l,h]$ for the attribute weight ratio allows users to have a flexible and approximate preference of the relative importance of the attributes rather than an exact value $l$ (as in $1$NN) or an infinite interval $[0,+\infty)$ (as in skyline). As a result, eclipse combines the best of both $1$NN and skyline and returns a subset of points from skyline which are possible nearest neighbors for all scoring functions with attribute weight ratio in the given range. We can easily see that both $1$NN and skyline are instantiations of eclipse queries. Recall our running example. If the conference organizers want to incorporate the preference that price is more important than distance for all student participants, they can set the attribute weight ratio as $r\in [0,1)$. For practical usage, in order to reduce the burden of parameter selection for users, we envision that users can either specify an attribute weight vector as in $k$NN which can be relaxed into ranges with a margin, or specify the relative importance of the attributes in categorical values such as very important, important, similar, unimportant, very unimportant, which correspond to predefined attribute weight ranges. \vspace{-1em} \begin{figure}[htb] \centering \includegraphics[width=0.35\textwidth]{eclipseQ} \vspace{-1em} \caption{Eclipse query.} \label{fig:eclipseQ} \end{figure} \vspace{-1em} Figure \ref{fig:eclipseQ} shows another example of eclipse query with an attribute weight ratio range $r \in [1/4,2]$ which indicates distance is relatively comparable to price. For a point $p$, we can draw two score lines with slopes $-h$ and $-l$, respectively. A point eclipse-dominates other points in its upper right range (with an obtuse angle) between the two score lines. We can see that $p_4$ is eclipse-dominated by $p_1,p_2,p_3$. The eclipse query returns $p_1$, $p_2$, and $p_3$ as they cannot eclipse-dominate each other. Please note that $p_1$ cannot skyline-dominate $p_4$ in skyline, but $p_1$ can eclipse-dominate $p_4$ in eclipse. Therefore, eclipse generally returns fewer points than skyline as the domination range is larger than skyline. It is non-trivial to compute eclipse points efficiently. To determine if point $p$ eclipse-dominates $p'$, we need to check if $S(p)\leq S(p')$ for all $r \in [l,h]$ but there are an infinite number of testings if we do it one by one. We first prove that we only need to check the boundary values $l$ and $h$ rather than the entire range. Given the boundary values, a straightforward algorithm to determine the eclipse-dominance relationship for each pair of points leads to $O(n^22^{d-1})$ time complexity. We propose an algorithm by transforming the eclipse problem to the skyline problem, which leads to much better $O(n\log ^{d-1}n)$ time complexity. In addition, we propose a novel index-based algorithm utilizing duality transform with further improved efficiency. The main idea is to build two index structures, Order Vector Index and Intersection Index, to allow us to quickly compute the dominance relationships between the points based on a given attribute weight ratio range. To implement Intersection Index in high dimensional space, we propose line quadtree and cutting tree with different tradeoffs in terms of average case and worst case performance. We briefly summarize our contributions as follows. \vspace{-0.7em} \begin{itemize} \item We propose a novel operator \emph{eclipse} that generalizes the classic $1$NN and skyline queries while providing a more flexible and customizable query solution for users. We formally show its properties and its relationship with other related notions including $1$NN, convex hull, and skyline. We show that $1$NN and skyline are the special cases of eclipse.\vspace{-0.7em} \item We present an efficient $O(n\log ^{d-1}n)$ time transformation-based algorithm for computing eclipse points by transforming the eclipse problem to the skyline problem.\vspace{-0.7em} \item We present an efficient index-based algorithm by utilizing index structures and duality transform with detailed complexity analysis shown in Section \ref{sec:index-based}.\vspace{-0.7em} \item We conduct comprehensive experiments on the real and synthetic datasets. The experimental results show that eclipse is interesting and useful, and our proposed algorithms are efficient and scalable. \end{itemize} \vspace{-1em} \partitle{Organization} The rest of the paper is organized as follows. Section \ref{sec:definition} introduces the eclipse definition, eclipse properties, and the relationship between the eclipse query and other queries. We present the transformation-based algorithms for computing eclipse points in Section \ref{sec:transformation-based}, and the index-based algorithms in Section \ref{sec:index-based}. We report the experimental results and findings in Section \ref{sec:Experiments}. Section \ref{sec:Related} presents the related work. Section \ref{sec:Conclusion} concludes the paper. \section{Definitions and Properties}\label{sec:definition} In this section, we first show some preliminaries and then give the formal definition of eclipse as well as a few properties of eclipse. Finally, we show the relationship between the eclipse query and others queries. For reference, a summary of notations is given in Table \ref{tab:notations}. \vspace{-2em} \begin{table}[htb]\centering \caption{The summary of notations.}\tiny\label{tab:notations} \vspace{-1em} {% \footnotesize \begin{tabular}{|c|c|} \hline Notation & Definition\\ \hline $p_i$ & $i^{th}$ point in dataset $P$\\ \hline $p_i[j]$ & $j^{th}$ dimension of point $p_i$\\ \hline $p\prec_s p'$ & p skyline-dominates p'\\ \hline $p\prec_e p'$ & p eclipse-dominates p'\\ \hline $p\prec_1 p'$ & p $1$NN-dominates p'\\ \hline $n$ & number of points\\ \hline $u$ & number of skyline points\\ \hline $d$ & number of dimensions\\ \hline $w[j]$ & $j^{th}$ attribute weight\\ \hline $\textbf{w}=\langle w[1],...,w[d]\rangle$ & attribute weight vector\\ \hline $r[j]=w[j]/w[d]$ & $j^{th}$ attribute weight ratio\\ \hline $\textbf{r}=\langle r[1],...,r[d-1]\rangle$ & attribute weight ratio vector\\ \hline $S(p)$ & weighted sum of point $p$\\ \hline $S(p)_{\textbf{r}}$ & weighted sum of point $p$ for $\textbf{r}$ \\ \hline $c_i$ & mapped corresponding point of $p_i$\\ \hline $c_i[j]$ & $c_i$ on the $j^{th}$ dimension\\ \hline \end{tabular}} \end{table}% \vspace{-1em} \subsection{Preliminaries} In the traditional $1$NN definition, $1$NN returns the point closest to a query point according to a given attribute weight vector. In the traditional skyline definition \cite{DBLP:journals/pvldb/LiuXPLZ15}, skyline returns all points that are not dominated by any other point. We can generalize the traditional $1$NN and skyline definitions using the notion of domination. For $1$NN, we say $p$ $1$NN-dominates $p'$, if $S(p)<S(p')$ for a given attribute weight vector. For skyline, we say $p$ skyline-dominates $p'$, if $S(p)\leq S(p')$ for all attribute weight ratio $r\in [0,+\infty)$ given a linear scoring function. We provide the generalized definitions for $1$NN and skyline as follows. \begin{definition}(\textbf{$1$NN}). Given a dataset $P$ of $n$ points in $d$ dimensional space and an attribute weight vector $\textbf{w}=\langle w[1],w[2],...,w[d]\rangle$ or an attribute weight ratio vector $\textbf{r}=\langle r[1],r[2],...,r[d-1]\rangle$, where $r[j]=w[j]/w[d]$. Let $p=(p[1],p[2],...,p[d])$ and $p'=(p'[1], p'[2],..., p'[d])$ be two different points in $P$, we say $p$ $1$NN-dominates $p'$, denoted by $p\prec_1 p'$, if $S(p)< S(p')$ for $\boldsymbol{r[j]\in [l_j,l_j]}$, where $l_j$ is a user-specified value for the $j^{th}$ attribute weight ratio, $S(p)=\sum_{i=1}^dp[i]w[i]$ is the weighted sum\footnote{In this paper, for the purpose of simplicity, we focus on $L_1$ norm. However, we note that the algorithms for $L_1$ norm can be easily extended to $L_p$ norm ($L_p^W(p_i)=(\sum_{i=1}^dw[i]p_i^p)^{1/p}$) for $p\geq2$. The reasons are 1) factor $1/p$ in the exponent part cannot affect the ranking of each point and 2) there is no difference to compute $w[i]p_i^p$ for different $p$.} of $p$, $l_j\in [0,+\infty)$, and $j=1,2,...,d-1$. The $1$NN point is the point that is not dominated by any other point in $P$. \end{definition} \begin{definition}(\textbf{Skyline}). Given a dataset $P$ of $n$ points in $d$ dimensional space and an attribute weight vector $\textbf{w}=\langle w[1],w[2],...,w[d]\rangle$ or an attribute weight ratio vector $\textbf{r}=\langle r[1],r[2],...,r[d-1]\rangle$, where $r[j]=w[j]/w[d]$. Let $p=(p[1],p[2],...,p[d])$ and $p'=(p'[1], p'[2],..., p'[d])$ be two different points in $P$, we say $p$ dominates $p'$, denoted by $p\prec_s p'$, if $S(p)\leq S(p')$ for all $\boldsymbol{r[j]\in [0,+\infty)}$, where $j=1,2,...,d-1$. The skyline points are those points that are not dominated by any other point in $P$. \end{definition} \subsection{Eclipse Definition and Properties} We define a new eclipse query below which allows a user to define an attribute weight ratio range for the domination. \begin{definition}(\textbf{Eclipse}). Given a dataset $P$ of $n$ points in $d$ dimensional space and an attribute weight vector $\textbf{w}=\langle w[1],w[2],...,w[d]\rangle$ or an attribute weight ratio vector $\textbf{r}=\langle r[1],r[2],...,r[d-1]\rangle$, where $r[j]=w[j]/w[d]$. Let $p=(p[1],p[2],...,p[d])$ and $p'=(p'[1], p'[2],..., p'[d])$ be two different points in $P$, we say $p$ eclipse-dominates $p'$, denoted by $p\prec_e p'$, if $S(p)\leq S(p')$ for all $\boldsymbol{r[j]\in [l_{j},h_{j}]}$, where $[l_j,h_j]$ is a user-specified range for the $j^{th}$ attribute weight ratio. The eclipse points are those points that are not dominated by any other point in $P$. \end{definition} \begin{example} In the $1$NN query of Figure \ref{fig:1nn}, given the attribute weight ratio vector $\textbf{r}= \langle 2\rangle$, $p_1$ dominates the points in the flat angle range, i.e., $p_2$, $p_3$, and $p_4$. In the skyline query of Figure \ref{fig:Skyline}, $p_1$ dominates the points in the right angle range, and $p_1$ cannot dominate any point in this example. In the eclipse query of Figure \ref{fig:eclipseQ}, given the attribute weight ratio vector $\textbf{r}=\langle r\rangle$, where $r\in [1/4,2]$, $p_1$ dominates the points in the obtuse angle range, i.e., $p_4$. \end{example} For each point, we call the range that it can dominate as \emph{domination range}, the boundary line as \emph{domination line} (\emph{domination hyperplane} in high dimensional space), and the attribute weight ratio vector that determines the domination line plus $r[d]=w[d]/w[d]=1$ as \emph{domination vector}. For example, for point $p_1$ in Figure \ref{fig:eclipseQ}, given the attribute weight ratio range $r\in [1/4,2]$, the domination lines are $y=-2x+8$ and $y=-1/4x+6.25$, the domination vectors are $\langle 2,1 \rangle$ and $\langle 1/4,1 \rangle$, and the domination range is the obtuse angle range on the upper right corner of the domination lines. We show several properties of eclipse queries below. \begin{property}(\textbf{Asymmetry}).\label{prop:asy} Given two points $p$ and $p'$, if $p\prec _ep'$, then $p'\nprec _ep$. \end{property} \begin{proof} Because $p\prec_ep'$, for any attribute weight ratio vector $\textbf{r}=\langle r[1],r[2],...,r[d-1]\rangle$, where $r[j]\in [l_{j},h_{j}]$ for j=1,2,...,d-1, we have $S(p)_{\textbf{r}}\leq S(p')_{\textbf{r}}$, where $S(p)_{\textbf{r}}$ is the weighted sum for $\textbf{r}$. Therefore, $p'\nprec _ep$. \end{proof} \begin{property}(\textbf{Transitivity}).\label{prop:tran} Given three points $p_1$, $p_2$, and $p_3$, if $p_1\prec _ep_2$ and $p_2\prec _ep_3$, then $p_1\prec _ep_3$. \end{property} \begin{proof} If we have $p_1\prec _ep_2$ and $p_2\prec _ep_3$, for any attribute weight ratio vector $\textbf{r}=\langle r[1],r[2],...,r[d-1]\rangle$, where $r[j]\in [l_{j},h_{j}]$ for j=1,2,...,d-1, we have $S(p_1)_{\textbf{r}}\leq S(p_2)_{\textbf{r}}$ and $S(p_2)_{\textbf{r}}\leq S(p_3)_{\textbf{r}}$. Therefore, we have $S(p_1)_{\textbf{r}}\leq S(p_3)_{\textbf{r}}$, that is $p_1\prec _ep_3$. \end{proof} Furthermore, we show the dominance definition in skyline is stricter than the dominance definition in eclipse by the following two properties. \begin{property}\label{pro:1} If $p\prec_s p'$, then $p\prec_e p'$, vice is not. \end{property} \vspace{-0.5em} \begin{property}\label{pro:2} If $p\nprec_s p'$, it is possible that $p\prec_e p'$. \end{property} \subsection{Relationship with other Definitions} In this subsection, we discuss the relationship between the eclipse query and other classic queries, i.e., $1$NN, convex hull, and skyline. We note that the convex hull query returns the points from origin's view rather than the entire traditional convex hull. For example, in Figure \ref{fig:1nn}, the convex hull query returns $p_1,p_3$ rather than $p_1,p_3,p_4$. The relationship among $1$NN, convex hull, eclipse, and skyline is shown in Figure \ref{fig:relationship}. $1$NN returns the best one point given a linear scoring function with specific weight for each attribute. Convex hull returns the best points given any linear scoring functions, so convex hull contains all possible $1$NN points. Skyline returns the best points given any monotone scoring functions. Eclipse returns the best points given a linear scoring function with a weight range for each attribute. As a result, skyline is the superset of eclipse and convex hull, $1$NN contains a point that belongs to the result set of all other queries. Depending on the range, eclipse ($[l,h]$) can be instantiated to be $1$NN ($[l,l]$) or skyline ($[0,+\infty)$). Therefore, eclipse not only contains some points that belong to convex hull but also some points that do not belong to convex hull. \begin{figure}[htb] \centering \includegraphics[width=0.25\textwidth]{relationship} \caption{Relationship between eclipse and other definitions.} \label{fig:relationship} \end{figure} \vspace{-1em} \section{Transformation-based Algorithms}\label{sec:transformation-based} In this section, we first show a baseline algorithm in Subsection \ref{subsec:baseline} and then show an improved algorithm by transforming the eclipse problem to the skyline problem in two dimensional space in Subsection \ref{subsec:transformation-based2D} and high dimensional space in Subsection \ref{subsec:transformation-basedhighD}. \subsection{Baseline Algorithm}\label{subsec:baseline} In order to check the dominance between a point $p$ and other points in two dimensional space, we observe that instead of computing all the continuous values in the range $[l_j,h_j]$ for $S(p)$, we only need to compute the boundary values of the range for $S(p)$. We note that although \cite{DBLP:journals/pvldb/CiacciaM17} presented a similar algorithm, they did not give any proof for the correctness. \begin{theorem}\label{the:endpoint2D} Given an attribute weight vector $\textbf{r}=\langle r\rangle$, where $r\in [l,h]$, if $S(p)_{\textbf{r}}\leq S(p')_{\textbf{r}}$ for $r=l$ and $r=h$, we have $S(p)_{\textbf{r}}\leq S(p')_{\textbf{r}}$ for all $r\in [l,h]$, where $S(p)_{\textbf{r}}$ is the weighted sum of point $p$ for $\textbf{r}$. \end{theorem} \begin{proof} Because for $r=l$ and $r=h$, $S(p)_{\textbf{r}}\leq S(p')_{\textbf{r}}$, we have $lp[1]+p[2]\leq lp'[1]+p'[2]$ and $hp[1]+p[2]\leq hp'[1]+p'[2]$. That is $l(p[1]-p'[1])+(p[2]-p'[2])\leq 0$ and $h(p[1]-p'[1])+(p[2]-p'[2])\leq 0$. Assume we have a linear function $f(t)=t(p[1]-p'[1])+(p[2]-p'[2])$ where $l< t< h$. Then we have $f(l)\leq 0$ and $f(h)\leq 0$. Because $f(t)$ is a line, therefore, for any value $t$ between the boundary values $l$ and $h$, we have $f(t)\leq 0$ for $l< t< h$. \end{proof} \begin{example} Given $r\in [1/4,2]$, the dominance relationship is shown in Figure \ref{fig:eclipseQ}, we only need to determine if $S(p)\leq S(p')$ for $r=1/4$ and $r=2$ according to Theorem \ref{the:endpoint2D}. We take $p_2$ and $p_4$ as an example, $S(p_2)_{\langle 1/4\rangle}=1/4\times 4+4=5$. Similarly, we have $S(p_2)_{\langle 2\rangle}=12$, $S(p_4)_{\langle 1/4\rangle}=7$, and $S(p_4)_{\langle 2\rangle}=21$. Because $S(p_2)_{\langle 1/4\rangle}<S(p_4)_{\langle 1/4\rangle}$ and $S(p_2)_{\langle 2\rangle}<S(p_4)_{\langle 2\rangle}$, we have $p_2\prec_e p_4$. \end{example} Next, we show how to extend Theorem \ref{the:endpoint2D} from two dimensional space to high dimensional space. \begin{theorem}\label{the:endpointhighD} Given an attribute weight ratio vector $\textbf{r}=\langle r[1], ...,r[d-1]\rangle$, where $r[j]\in [l_j, h_j]$ for $j=1, 2, ..., d-1$, if $S(p)_\textbf{r}\leq S(p')_\textbf{r}$ for $r[j]=l_j$ and $r[j]=h_j$, where $j=1, 2, ...,d-1$, we have $S(p)_\textbf{r}\leq S(p')_\textbf{r}$ for all $r[j]\in [l_j,h_j]$. \end{theorem} \begin{proof} Because the attribute weight ratio on each dimension $j$ can take the value of $l_j$ or $h_j$, we have $2^{d-1}$ domination vectors in $d$ dimensional space. Therefore, we have the following $2^{d-1}$ inequalities for $S(p)\leq S(p')$. $\Sigma_{j=1}^{d-3}l_j(p[j]-p'[j])+\boldsymbol{l_{d-2}} (p[d-2]-p'[d-2])+\boldsymbol{l_{d-1}} (p[d-1]-p'[d-1])+(p[d]-p'[d])\leq 0$, $\Sigma_{j=1}^{d-3}l_j(p[j]-p'[j])+\boldsymbol{l_{d-2}} (p[d-2]-p'[d-2])+\boldsymbol{h_{d-1}} (p[d-1]-p'[d-1])+(p[d]-p'[d])\leq 0$, $\Sigma_{j=1}^{d-3}l_j(p[j]-p'[j])+\boldsymbol{h_{d-2}} (p[d-2]-p'[d-2])+\boldsymbol{l_{d-1}} (p[d-1]-p'[d-1])+(p[d]-p'[d])\leq 0$, $\Sigma_{j=1}^{d-3}l_j(p[j]-p'[j])+\boldsymbol{h_{d-2}} (p[d-2]-p'[d-2])+\boldsymbol{h_{d-1}} (p[d-1]-p'[d-1])+(p[d]-p'[d])\leq 0$, ......, $\Sigma_{j=1}^{d-1}h_j(p[j]-p'[j])+(p[d]-p'[d])\leq 0$. Given the first two inequalities, according to Theorem \ref{the:endpoint2D}, we have $\Sigma_{j=1}^{d-3}l_j(p[j]-p'[j])+\boldsymbol{l_{d-2}} (p[d-2]-p'[d-2])+r[d-1] (p[d-1]-p'[d-1])+(p[d]-p'[d])\leq 0$ (i), where $r[d-1]\in [l_{d-1},h_{d-1}]$. Similarly, given the third and fourth inequalities, we have $\Sigma_{j=1}^{d-3}l_j(p[j]-p'[j])+\boldsymbol{h_{d-2}} (p[d-2]-p'[d-2])+r[d-1] (p[d-1]-p'[d-1])+(p[d]-p'[d])\leq 0$ (ii), where $r[d-1]\in [l_{d-1},h_{d-1}]$. Based on (i) and (ii), we have $\Sigma_{j=1}^{d-3}l_j(p[j]-p'[j])+w[d-2] (p[d-2]-p'[d-2])+r[d-1] (p[d-1]-p'[d-1])+(p[d]-p'[d])\leq 0$, where $r[d-2]\in [l_{d-2},h_{d-2}]$ and $r[d-1]\in [l_{d-1},h_{d-1}]$. Similarly, we iteratively transform $l_j$ and $h_j$ to $r[j]$. Finally, we have $\Sigma_{j=1}^{d-1}r[j](p[j]-p'[j])+(p[d]-p'[d])\leq 0$, where $r[j]\in [l_j,h_j]$, $j=1, 2, ..., d-1$. \end{proof} \begin{algorithm}[h] \scriptsize \caption{Baseline algorithm for computing eclipse points.}\label{Alg:baseline} \SetKwInOut{Input}{input}\SetKwInOut{Output}{output} \Input{a set of $n$ points in $d$ dimensional space.} \Output{eclipse points.} \For{i = 1 to n}{ compute $S(p_i)_{\textbf{r}_k}, k=1,2,...,2^{d-1}$\; flag=1\; \For{j = 1 to n, $\neq i$}{ compute $S(p_j)_{\textbf{r}_k}, k=1,2,...,2^{d-1}$\; \For{k= 1 to $2^{d-1}$}{ \If{$S(p_j)_{\textbf{r}_k}>S(p_i)_{\textbf{r}_k}$}{ goto Line 4\;} } flag=0\; break\; } \If{flag==1}{ add $p_i$ to eclipse points\; } } \end{algorithm} Based on Theorems \ref{the:endpoint2D} and \ref{the:endpointhighD}, the key idea of the baseline algorithm is that we only need to compare the scoring function $S(p_i)$ and $S(p_j)$ for each pair of points $p_i$ and $p_j$ with respect to all the domination vectors. The detailed algorithm is shown in Algorithm \ref{Alg:baseline}. We compute $S(p_i)_{\textbf{r}_k}$ corresponding to the $2^{d-1}$ domination vectors in Line 2 and set the flag as 1. We compute $S(p_j)_{\textbf{r}_k}$ corresponding to the $2^{d-1}$ domination vectors in Line 5. In Line 7, if $S(p_j)_{\textbf{r}_k}>S(p_i)_{\textbf{r}_k}$, it means that $p_j$ cannot eclipse-dominate $p_i$, and then we break from the forloop. If for all $k$ such that $S(p_j)_{\textbf{r}_k}\leq S(p_i)_{\textbf{r}_k}$, it means that $p_j\prec_e p_i$, and then we set the flag as 0. In Line 11, if the flag equals to $1$, it means that there is no other point that can eclipse-dominate $p_i$, so we add $p_i$ to eclipse points. \begin{theorem}\label{the:3} The time complexity of Algorithm \ref{Alg:baseline} is $O(n^22^{d-1})$. \end{theorem} \begin{proof} Algorithm \ref{Alg:baseline} requires three forloops and each forloop iterates $n$, $n$, and $2^{d-1}$ times, respectively. Thus, Algorithm \ref{Alg:baseline} requires $O(n^22^{d-1})$ time in total. \end{proof} \subsection{Transformation-based Algorithm for Two Dimensional Space}\label{subsec:transformation-based2D} In Subsection \ref{subsec:baseline}, we showed how to compute eclipse points in $O(n^2)$ time due to the two forloops. In this subsection, we show how to transform the eclipse problem to the skyline problem, and then we can employ an efficient $O(n\log n)$ time algorithm to solve the eclipse problem. In the eclipse query, for each point $p_i(p_i[1],p_i[2])$, there are two domination lines with slopes $-h$ and $-l$, and $p_i$ eclipse-dominates the points in the domination range. For example, in Figure \ref{fig:transformation-based2D}, $p_1$ eclipse-dominates the points on the upper right of the two domination lines. For any two points $p$ and $p'$, the slopes ($-h$ and $-l$) of their two domination lines are the same. Therefore, if $p$ eclipse-dominates $p'$, the intercepts of $p's$ domination lines should be smaller than the corresponding intercepts of $p'$. Therefore, instead of directly comparing $S(p)$ and $S(p')$ for each pair of points for their eclipse-dominance which requires $O(n^2)$, we can map the intercepts of the two domination lines of each pair of points $p$ and $p'$ into a coordinate space, and compare their dominance utilizing $O(n\log n)$ skyline algorithm. \begin{figure}[htb] \centering \includegraphics[width=0.35\textwidth]{transformation-based2D} \caption{Mapping.} \label{fig:transformation-based2D} \end{figure} Concretely, for each point $p_i$, the two domination lines have two intercepts with each dimension. We map $p_i$ into $c_i$ by taking the smaller intercept on the $j^{th}$ dimension as $c_i[j]$ because the larger intercept is already represented by the smaller intercept on the other dimension. For example, in Figure \ref{fig:transformation-based2D}, for point $p_1$, the two domination lines have two $y$-intercepts, $6.25$ and $8$. We take the smaller $y$-intercept, $6.25$, as $c_1[2]$. Similarly, we have $c_1[1]=4$. Therefore, we map $p_1$ into $c_1(4,6.25)$. Based on this mapping, we can prove that $p\prec_e p'$ if $c\prec_s c'$ in Theorem \ref{the:transform2D}. \begin{algorithm}[h] \scriptsize \caption{Transformation-based algorithm for two dimensional space.}\label{Alg:transformation-based2D} \SetKwInOut{Input}{input}\SetKwInOut{Output}{output} \Input{a set of $n$ points in two dimensional space, an attribute weight ratio vector $\langle r\rangle$, where $r\in [l,h]$.} \Output{eclipse points.} \For{i =1 to n}{ $c_i[1]=p_i[1]+p_i[2]/h$\; $c_i[2]=lp_i[1]+p_i[2]$\; } use $O(n\log n)$ algorithm to compute skyline points of $\{c_1, c_2,...,c_n\}$\; add the corresponding points of skyline points to eclipse points\; \end{algorithm} \begin{theorem}\label{the:transform2D} Given an attribute weight ratio $r\in [l,h]$ and a point $p_i$, we map $p_i$ into $c_i$, where $c_i[j]$ is the smaller intercept on the $j^{th}$ dimension of the two domination lines with slopes $-h$ and $-l$. We have $p\prec_e p'$ if $c\prec_s c'$ in two dimensional space. That is, the eclipse points of dataset $\{p_1, p_2, ..., p_n\}$ equal to the corresponding skyline points of dataset $\{c_1, c_2,...,c_n\}$. \end{theorem} \begin{proof} For $p\prec_e p'$, we have \begin{displaymath} l p[1]+p[2]\leq l p'[1]+p'[2] \end{displaymath} \begin{displaymath} h p[1]+p[2]\leq h p'[1]+p'[2] \end{displaymath} We map $p$ into $c$ \begin{displaymath} c[2]=l p[1]+p[2] \end{displaymath} \begin{displaymath} c[1]=p[1]+\frac{1}{h}p[2] \end{displaymath} Similarly, we map $p'$ into $c'$ \begin{displaymath} c'[2]=l p'[1]+p'[2] \end{displaymath} \begin{displaymath} c'[1]=p'[1]+\frac{1}{h}p'[2] \end{displaymath} Because $c\prec_s c'$, we have \begin{displaymath} l p[1]+p[2]\leq l p'[1]+p'[2] \end{displaymath} \begin{displaymath} p[1]+\frac{1}{h}p[2]\leq p'[1]+\frac{1}{h}p'[2] \end{displaymath} It is easy to see that $p\prec_e p'$ can be equivalent to $c\prec_s c'$. \end{proof} Based on Theorem \ref{the:transform2D}, we show our algorithm for computing eclipse points in Algorithm \ref{Alg:transformation-based2D}. We compute $c_i$ of point $p_i$ in Lines 1-3. We employ the $O(n\log n)$ skyline algorithm to compute the skyline points of $\{c_1, c_2,..., c_n\}$ in Line 4. \begin{example} We show an example based on Figure \ref{fig:transformation-based2D}. Assume the attribute weight ratio $r\in [1/4,2]$. We have $c_1=(4,6.25)$, $c_2=(6,5)$, $c_3=(6.5,2.5)$, and $c_4(10.5,7)$. We compute the skyline points of $\{c_1,c_2,c_3,c_4\}$, and the skyline points are $c_1$, $c_2$, and $c_3$. Therefore, the corresponding eclipse points are $p_1$, $p_2$, and $p_3$. \end{example} \begin{theorem}\label{the:5} The time complexity of Algorithm \ref{Alg:transformation-based2D} is $O(n\log n)$. \end{theorem} \begin{proof} Lines 1-3 requires $O(n)$ time. Line 4 requires $O(n\log n)$ time. Thus, Algorithm \ref{Alg:transformation-based2D} requires $O(n\log n)$ time in total. \end{proof} \subsection{Transformation-based Algorithm for High Dimensional Space}\label{subsec:transformation-basedhighD} In this subsection, we show how to transform the eclipse problem to the skyline problem for the high dimensional case similar to the two dimensional case by carefully choosing $d$ domination vectors, and then we can employ an efficient $O(n\log^{d-1} n)$ time algorithm to solve the eclipse problem. For point $p(p[1],p[2],...,p[d])$, we have the following $2^{d-1}$ domination hyperplanes with respect to $2^{d-1}$ domination vectors as each dimension $j$ of the domination vector can take the boundary values $l_j$ and $h_j$. \begin{displaymath} l_1p[1]+l_2p[2]+...+l_{d-1}p[d-1]+p[d]=S(p)_{\textbf{r}_1}; \end{displaymath} \begin{displaymath} l_1p[1]+l_2p[2]+...+h_{d-1}p[d-1]+p[d]=S(p)_{\textbf{r}_1}; \end{displaymath} ...... \begin{displaymath} h_1p[1]+h_2p[2]+...+l_{d-1}p[d-1]+p[d]=S(p)_{\textbf{r}_{2^{d-1}-1}}; \end{displaymath} \begin{displaymath} h_1p[1]+h_2p[2]+...+h_{d-1}p[d-1]+p[d]=S(p)_{\textbf{r}_{2^{d-1}}}; \end{displaymath} We can write the domination vector function matrix as follows. \[ \begin{bmatrix} l_1 & l_2 & ... & l_{d-1} & 1 \\ l_1 & l_2 & ... & h_{d-1} & 1 \\ ......\\ h_1 & h_2 & ... & l_{d-1} & 1 \\ h_1 & h_2 & ... & h_{d-1} & 1 \\ \end{bmatrix} \] Because there are $d$ variables, the rank of the domination vector function matrix is at most $d$. Therefore, we can carefully choose $d$ domination vectors from these $2^{d-1}$ domination vectors to represent the original matrix. Furthermore, the rank of the new $d$-row matrix should be $d$. We can choose the first row to identify the $d^{th}$ attribute weight ratio and the row with $r[k]=h_j, k=j$ and $r[k]=l_j, j\neq k,k=1,2,...,d-1$ to identify the $j^{th}$ attribute weight ratio. It is easy to see that there are $d-1$ such rows. Therefore, we get a new $d$-row matrix with rank $d$. In fact, each row in the new matrix corresponds to a $c_i[j]$. For example, if we choose $r[1]=h_1$ and $r[j]=l_j$ for $j=2,...,d-1$, the corresponding domination vector is $\textbf{v}_1=\langle h_1,l_2,...,l_{d-1},1 \rangle$. This domination vector $\textbf{v}_1$ corresponds to $c_i[1]$ because we get the smallest $x$-intercept by the domination hyperplane determined by $\textbf{v}_1$. Given the above mapping, we can show that $p\prec_e p'$ if $c\prec_s c'$ in high dimensional space as in the following theorem. \begin{theorem}\label{the:transformHD} Given an attribute weight ratio vector $\textbf{r}=\langle r[1],r[2], ...,r[d-1]\rangle$ and a point $p_i$, we map $p_i$ into $c_i$, where $c_i[j]$ is the smallest intercept on the $j^{th}$ dimension of the $d$ domination hyperplanes. We have $p\prec_e p'$ if $c\prec_s c'$ in high dimensional space. That is, the eclipse points of dataset $\{p_1, p_2,...,p_n\}$ equal to the corresponding skyline points of dataset $\{c_i, c_2,...,c_n\}$. \end{theorem} \begin{proof} If $p\prec_e p'$, for all $r[j]\in \{l_j,h_j\}$, where $j=1,2,...,d-1$, we have $S(p)\leq S(p')$ for $2^{d-1}$ domination vectors. We can carefully choose $d$ domination vectors to represent these $2^{d-1}$ domination vectors as follows. \[ \begin{bmatrix} l_1 & l_2 & ... & l_{d-1} & 1 \\ l_1 & l_2 & ... & \boldsymbol{h_{d-1}} & 1 \\ ......\\ l_1 & \boldsymbol{h_2} & ... & l_{d-1} & 1 \\ \boldsymbol{h_1} & l_2 & ... & l_{d-1} & 1 \\ \end{bmatrix} \] We have $S(p)\leq S(p')$ for these $d$ domination vectors as follows. \begin{displaymath} \sum_{j=1}^{d-1}l_jp[j]+p[d]\leq \sum_{j=1}^{d-1}l_jp'[j]+p'[d] \end{displaymath} and for $j=1,2,...,d-1$ \begin{equation}\label{equ:rank} h_jp[j]+\sum_{k=1,k\neq j}^{d-1}l_kp[k]+p[d]\leq h_jp'[j] \sum_{k=1,k\neq j}^{d-1}l_kp'[k]+p'[d] \end{equation} If $c\prec _sc'$, for all $j=1,2,...,d$, we have $c[j]\leq c'[j]$. That is \begin{displaymath} \frac{p[d]+h_1p[1]+\sum_{k=2,k\neq 1}^{d}l_{k}p[k]}{h_1} \end{displaymath} \begin{displaymath} \leq \frac{p'[d]+h_1p'[1]+\sum_{k=2,k\neq 1}^{d}l_{k}p'[k]}{h_1} \end{displaymath} \begin{displaymath} \frac{p[d]+h_2p[2]+\sum_{k=2,k\neq 2}^{d}l_{k}p[k]}{h_2} \end{displaymath} \begin{displaymath} \leq \frac{p'[d]+h_2p'[2]+\sum_{k=2,k\neq 2}^{d}l_{k}p'[k]}{h_2} \end{displaymath} \begin{displaymath} ...... \end{displaymath} \begin{displaymath} \frac{p[d]+h_{d-1}p[d-1]+\sum_{k=2,k\neq d-1}^{d}l_{k}p[k]}{h_{d-1}} \end{displaymath} \begin{displaymath} \leq \frac{p'[d]+h_{d-1}p'[d-1]+\sum_{k=2,k\neq d-1}^{d}l_{k}p'[k]}{h_{d-1}} \end{displaymath} \begin{displaymath} l_1p[1]+l_2p[2]+...+l_{d-1}p[d-1]+p[d] \end{displaymath} \begin{displaymath} \leq l_1p'[1]+l_2p'[2]+...+l_{d-1}p'[d-1]+p'[d]; \end{displaymath} which is equivalent to Equation \ref{equ:rank}. \end{proof} Based on Theorem \ref{the:transformHD}, the detailed algorithm for computing eclipse points in high dimensional space is shown in Algorithm \ref{Alg:transformation-basedHigherD}. For each point $p_i$, we map it into $c_i$ in Lines 1-4, and then use the $O(nlog^{d-1}n)$ high dimensional skyline algorithm to compute skyline points of $\{c_1,c_2,...,c_n\}$. The corresponding points $p_i,1\leq i\leq n$ are eclipse points. \begin{algorithm}[h] \scriptsize \caption{Transformation-based algorithm for high dimensional space.}\label{Alg:transformation-basedHigherD} \SetKwInOut{Input}{input}\SetKwInOut{Output}{output} \Input{a set of $n$ points in high dimensional space, attribute weight ratio vector $\textbf{r}=\langle r[1], ..., r[d-1]\rangle$, where $r[j]\in [l_j, h_j]$ for $j=1,2,...,d-1$.} \Output{eclipse points.} \For{i =1 to n}{ $c_i[d]=\sum_{j=1}^{d-1}l_jp_i[j]+p_i[d]$\; \For{j = 1 to d-1}{ $c_i[j]=\frac{p_i[d]+h_jp_i[j]+\sum_{k=2,k\neq j}^{d-1}l_{k}p_i[k]}{h_j}$\; } } use the $O(n\log^{d-1} n)$ ECDF algorithm \cite{DBLP:journals/cacm/Bentley80} to compute skyline points of $\{c_1,c_2,...,c_n\}$\; add the corresponding points of skyline points to Eclipse points\; \end{algorithm} \begin{theorem}\label{the:7} The time complexity of Algorithm \ref{Alg:transformation-basedHigherD} is $O(n\log^{d-1} n)$. \end{theorem} \vspace{-1em} \begin{proof} Lines 1-4 require $O(nd)$ time. Line 5 requires $O(n\log^{d-1} n)$ time. Thus, Algorithm \ref{Alg:transformation-basedHigherD} requires $O(n\log^{d-1} n)$ time in total. \end{proof} \section{Index-based Algorithms}\label{sec:index-based} The transformation-based algorithm we presented in Section \ref{sec:transformation-based} is more efficient than the baseline algorithm. However it is still computationally expensive for real time queries, since it computes each query for the entire dataset from scratch. In this section, we show more efficient algorithms utilizing index structures and duality transform. For a better perspective, we transform our problem from the primal space to the dual space by duality transform \cite{de2000computational}. For a point $p=(p[1],p[2],...,p[d])$, its dual hyperplane is $x_d=p[1]x_1+p[2]x_2+...+p[d-1]x_{d-1}-p_d$. For a hyperplane $x_d=p[1]x_1+p[2]x_2+...+p[d-1]x_{d-1}+p[d]$, its dual point is $(p[1],p[2],...,p[d-1],-p[d])$. For example, in Figure \ref{fig:dual2D}, for point $p_1(1,6)$, its corresponding line in the dual space is $y=x-6$. We show how to construct the index structures and process the queries in two dimensional space in Subsection \ref{subsec:index-based2D} and high dimensional space in Subsection \ref{subsec:index-basedhigh}. \subsection{Index-based Algorithm for Two Dimensional Space}\label{subsec:index-based2D} We first show how to compute $1$NN and skyline in the dual space in Figure \ref{fig:dual2D}, and then introduce our algorithm for computing eclipse points. We have four points $p_1,p_2,p_3,p_4$ in the primal space (Figure \ref{fig:dual2D}(a)) and their corresponding lines in the dual space (Figure \ref{fig:dual2D}(b)). $p_4$ cannot be an eclipse point because it is skyline-dominated by $p_2$ and $p_3$, thus, we omit $p_4$ in the dual space. \begin{figure}[htb] \centering \includegraphics[width=0.4\textwidth]{dual2D} \vspace{-1em} \caption{(a): Primal space, (b) Dual space.} \label{fig:dual2D} \end{figure} For all 1NN, skyline, and eclipse queries, we need to find the point that is not in the domination range of any other point. But the domination range differs for each of the queries. For $1$NN, the domination range of each point given attribute weight ratio $r=l$ is determined by the domination line with slope $-l$. Correspondingly, in the dual space, given the $x$-coordinate ($-l$), we need to find the line that is not dominated by any other line, i.e., the closest line to the $x$-axis. For example, in Figure \ref{fig:dual2D}, if $l=2$, the nearest neighbor is $p_1$ in the primal space. Correspondingly, in the dual space, line $p_1$ is the closest line to the $x$-axis when $x=-2$. For skyline, the domination range of each point is determined by the two domination lines with slopes $0$ and $\infty$, i.e., the attribute weight ratio $r\in (-\infty, 0]$. Correspondingly, in the dual space, given the $x$-coordinate range $(-\infty,0]$, we need to find the lines that are not dominated by any other line. We say line $p_a$ dominates $p_b$ if $p_a$ is consistently closer to the $x$-axis than $p_b$ for the entire range. For example, in Figure \ref{fig:dual2D}, in interval $(-\infty,p_2p_3[x]]$ of the $x$-axis, the closest line to the $x$-axis is $p_1$, and in interval $({p_1p_3}[x],0]$ of the $x$-axis, the closest line to the $x$-axis is $p_3$, where ${p_ip_j}[x]$ is the $x$-coordinate of the intersection of lines $p_i$ and $p_j$ in the dual space. However, in the entire query range, there is no line that can dominate $p_2$. Therefore, the skyline query result is $p_1$, $p_2$, and $p_3$. For eclipse, given a ratio range $r\in [l,h]$, the domination range of each point is determined by the two domination lines with slopes $-h$ and $-l$. Correspondingly, in the dual space, given the $x$-coordinate range $[-h,-l]$, we need to find the lines that are not dominated by any other line, i.e., consistently closer to the $x$-axis within the range. Since the order of the lines (in their closeness to the $x$-axis) only changes when the two lines intersect, in order to quickly find the lines that are not dominated by any other line within the query range $[-h,-l]$, we can partition the $x$-axis by intervals where for each interval, the order of the lines does not change. The partitioning points are naturally determined by the intersections between each pair of lines. This motivates us to build 1) an index structure (Order Vector Index) that stores the intervals and their corresponding order of the lines, and 2) an index structure (Intersection Index) that stores the intersections which affect the consistent order of the lines within a range. In this way, given any query range, we can quickly retrieve all the lines that are not dominated by any other line within the range. \subsubsection{Indexing} In this subsection, we show how to build Order Vector Index and Intersection Index. \partitle{Order Vector Index} We build an Order Vector Index which partitions the $x$-axis into ${u\choose 2}+1$ intervals, and each entry $ov_i$ corresponding to an interval stores the order of the lines in their closeness to the $x$-axis, where $u$ is the number of skyline points and $u\choose 2$ is the number of intersections between the $u$ lines in the dual space. For example, in Figure \ref{fig:indexing}, we partition the $x$-axis into four intervals. The last interval is $(-2/3,0]$, and it stores the order of the lines $\textbf{ov}_4=\langle 2,1,0 \rangle$ corresponding to $p_3,p_2,p_1$. \begin{algorithm}[h] \scriptsize \caption{Indexing in two dimensional space.}\label{Alg:index-basedPre2D} \SetKwInOut{Input}{input}\SetKwInOut{Output}{output} \Input{a set of $n$ points in two dimensional space.} \Output{Order Vector Index and Intersection Index.} use the $O(n\log n)$ time complexity algorithm to compute the $u$ skyline points of $n$ points\; \For{i = 1 to u}{ compute the corresponding line $p_i$ in the dual space for point $p_i$ \; } \For{i =1 to u-1}{ \For{j=i+1 to u}{ compute value $p_ip_j[x]$ by eliminating $y$ from two lines $p_i$ and $p_j$\;}} sort those $p_ip_j[x]$ in ascending order $v_1,v_2,...,v_{u\choose 2}$, and record the corresponding two lines for each $v_{i}$, $i=1,2,...,{u\choose 2}$\; \For{i=2 to ${u\choose 2} +1$}{ \For{j =1 to u}{ $startY_j=(v_{i-1}+\epsilon)p_j[1]-p_j[2]$ ($v_1-\epsilon$ if $i=1$)\; } \For{k =1 to u}{ compute $\textbf{ov}_{i-1}[k]$\; } } \end{algorithm} The detailed algorithm is shown in Algorithm \ref{Alg:index-basedPre2D}. Because eclipse points are the subset of skyline points, we find skyline points in Line 1. In Lines 2-3, we compute the corresponding line $p_i$ in the dual space for point $p_i$. In Lines 4-5, we compute value $p_ip_j[x]$ by eliminating $y$ from two lines $p_i$ and $p_j$, where $p_ip_j[x]$ is the $x$-coordinate of the intersection of lines $p_i$ and $p_j$. In Line 7, we sort all $u\choose 2$ intersections' $x$-coordinates. Because the order of the lines in their closeness to the $x$-axis does not change in the same interval, we choose $v_i+\epsilon$ as the $x$-coordinate to compute the $y$-coordinate in Line 10 as $startY_i$ which is used to determine the order of the lines in their closeness to the $x$-axis in the interval, where $\epsilon$ is a very small number. The reason for adding a very small number is that we compute the initial order in the interval rather than on the interval boundary $v_i$. Finally, we obtain the $\textbf{ov}_i$ for each interval in Line 12. $\textbf{ov}_i[k]$ means there are $\text{ov}_i[k]$ lines that can dominate line $p_k$ to the $x$-axis in the $i^{th}$ interval. \partitle{Intersection Index} For two dimensional case, we record the corresponding two lines for each interval boundary $v_i$ in Line 7 in Algorithm \ref{Alg:index-basedPre2D}, and the interval boundaries in Order Vector Index are exactly the $x$-coordinates of the intersections. Therefore, we can use Order Vector Index to index both order vectors and intersections in two dimensional space. \begin{figure}[htb] \centering \includegraphics[width=0.45\textwidth]{indexing} \vspace{-1em} \caption{Indexing example.} \label{fig:indexing} \end{figure} \vspace{-1em} \begin{example} We show how to build the index structures in Figures \ref{fig:dual2D} and \ref{fig:indexing}. In Line 3, we map points $p_1(1,6)$, $p_2(4,4)$, $p_3(6,1)$ in the primal space (shown in Figure \ref{fig:dual2D}(a)) into linear equations $y=x-6$, $y=4 x-4$, $y=6 x-1$ in the dual space (shown in Figure \ref{fig:dual2D}(b)) by duality transform, respectively. In Line 6, taking two lines $p_1$ and $p_2$ as an example, we substitute $y=4 x-4$ into $y=x-6$, and get the $x$-coordinate of the intersection of lines $p_1$ and $p_2$, $p_1p_2[x]=-2/3$. Similarly, we have $p_1p_3[x]=-1$ and $p_2p_3[x]=-1.5$. In Line 7, we sort $-1.5,-1,-2/3$ and record the corresponding two lines for each value, e.g., $-2/3$ is formed by two lines $p_1$ and $p_2$. Therefore, we have four intervals $(-\infty,-1.5]$, $(-1.5,-1]$, $(-1,-2/3]$, and $(-2/3,0]$. Taking the last interval $(-2/3,0]$ as an example, we compute its corresponding $\textbf{ov}_4$ in Lines 9-12. We compute the $y$-coordinate $startY_i$ for lines $p_1$, $p_2$, and $p_3$ in Line 10. We have $startY_1=-1/2-6=-6.5$ by choosing $\epsilon=1/6$. Similarly, we have $startY_2=-6$, and $startY_3=-4$. Therefore, the corresponding $\textbf{ov}_4$ is $ \langle 2,1,0\rangle$. \end{example} \subsubsection{Querying} In this subsection, we show how to process the query. Given an attribute weight ratio $r\in [l,h]$, the corresponding query range in the dual space is $[-h,-l]$. Each interval stores the order of the lines in their closeness to the x-axis within that interval. Our goal is to determine if a line is consistently closer than other lines within the query range $[-h,-l]$. Hence we can start with the order in one of the intervals as the initial order, then determine if the order is consistent by enumerating through the intersection points in the range. The detailed algorithm is shown in Algorithm \ref{Alg:index-basedQuery2D}. We get the initial $\textbf{ov}$ for $-l$ from Order Vector Index and use binary search to find the intersections whose $x$-coordinates lie between $-h$ and $-l$ from Intersection Index in Lines 1-2. We assume there are $m$ intersections within the query range. The worst case for $m$ is $u\choose 2$, i.e., all the intersections lie in the query range, but $m$ is much smaller than $u\choose 2$ in practice given the small query range. For the intersection of lines $p_a$ and $p_b$, if $\textbf{ov}[a]$ is smaller than $\textbf{ov}[b]$, that means line $p_a$ dominates $p_b$ before this intersection (in $[-h,p_ap_b[x]]$). After this intersection, i.e., in $[p_ap_b[x],-l]$, $p_b$ dominates $p_a$. That is, the number of lines that can dominate $p_b$ will be subtracted by one (Line 6). Similarly, if $\textbf{ov}[a]$ is larger than $\textbf{ov}[b]$, we have $\textbf{ov}[a]--$ in Line 8. Finally, if $\textbf{ov}[i]=0$, that is there is no other point that can dominate $p_i$. We add $p_i$ to eclipse points. \vspace{-1em} \begin{algorithm}[h] \scriptsize \caption{Query for two dimensions.}\label{Alg:index-basedQuery2D} \SetKwInOut{Input}{input}\SetKwInOut{Output}{output} \Input{Order Vector Index and Intersection Index, attribute weight ratio $r\in [l,h]$.} \Output{eclipse points.} use binary search to find the interval that contains $-l$ and get the initial $\textbf{ov}$ for $-l$ from Order Vector Index; find these intersections whose $x$-coordinate lying between $-h$ and $-l$ from Intersection Index\; \For{i = 1 to m (number of intersections)}{ assume lines $p_a$ and $p_b$ form the intersection\; \If{$\textbf{ov}[a]<\textbf{ov}[b]$}{ $\textbf{ov}[b]--$; } \Else { $\textbf{ov}[a]--$; } } \For{i =1 to u}{ \If{$\textbf{ov}[i]=0$}{ add $p_i$ to eclipse points\; } } \end{algorithm} \begin{example} Given $r\in [1/4,2]$, we have the corresponding query $[-2,-1/4]$. We search $-l=-1/4$ which belongs to the interval of $(-2/3,0]$ from Order Vector Index, and get the initial $\textbf{ov}_4=\langle 2,1,0\rangle$ in Line 1. In Line 2, we find intersections $p_1p_2$, $p_1p_3$, $p_2p_3$ from Intersection Index because their $x$-coordinates lie in $[-2,-1/4]$. After intersection $p_1p_2$, $p_2$ cannot dominate $p_1$, thus the number of the lines that can dominate $p_1$ should be subtracted by 1. That is $\textbf{ov}_4[1]=2-1=1$. Similarly, after intersection $p_1p_3$, $\textbf{ov}_4[1]=1-1=0$, after intersection $p_2p_3$, $\textbf{ov}_4[2]=1-1=0$. Finally, we get $\textbf{ov}_4=\langle 0,0,0\rangle $. That is, there is no other line that can dominate $p_1, p_2, p_3$ in $[-2,-1/4]$. Thus, we add points $p_1, p_2, p_3$ to eclipse points. \end{example} \begin{table}[htb]\centering\footnotesize \caption{Example of query for $r\in [1/4,2]$.}\label{tab:table} \vspace{-1em} {% \begin{tabular}{|c||c|c|c|} \hline & $p_1$ & $p_2$ & $p_3$\\ \hline $startY_i$ & -6.5 & -6 & -4 \\ \hline initial $\textbf{ov}_4$ & 2 & 1 & 0\\ \hline after $p_1p_2$ $\textbf{ov}_4$ & 1 & 1 & 0\\ \hline after $p_1p_3$ $\textbf{ov}_4$ & 0 & 1 & 0\\ \hline after $p_2p_3$ $\textbf{ov}_4$ & 0 & 0 & 0\\ \hline \end{tabular}} \end{table}% \vspace{-1em} \begin{theorem}\label{the:8} The time complexity of Algorithm \ref{Alg:index-basedQuery2D} is $O(u+m)$. \end{theorem} \begin{proof} Line 1 requires $O(\log u^2)$ time. Line 2 requires $O(\log u^2+m)$ time. Lines 3-8 can be finished in $O(m)$ time. Lines 9-11 can be finished in $O(u)$ time. Thus, Algorithm \ref{Alg:index-basedQuery2D} requires $O(u+m)$ time in total. \end{proof} \subsection{Index-based Algorithm for High Dimensional Space}\label{subsec:index-basedhigh} In this subsection, we show how to build the index structures and process the eclipse query in high dimensional space. The general idea is very similar to two dimensional case. In the dual space of two dimensional space, we need to find the lines that are not dominated by any other line with respect to the $x$-axis (line $y=0$) within the query range $x\in [-h,-l]$. Similarly, in the dual space of high dimensional space, we need to find the hyperplanes that are not dominated by any other hyperplane with respect to the hyperplane $x_d=0$ within the query range $x_1\in [-h_1,-l_1]$,...,$x_{d-1}\in [-h_{d-1},-l_{d-1}]$ for $d$ dimensional space. Therefore, we need Order Vector Index to index the initial order of those hyperplanes in each hypercell with respect to the hyperplane $x_d$=0. In two dimensional space, we want to find the intersections whose $x$-coordinates lying in $[-h,-l]$. Similarly, in high dimensional space, we want to find the $d-1$ dimensional intersecting hyperplanes that are intersecting with range $x_1\in [-h_1,-l_1]$,...,$x_{d-1}\in [-h_{d-1},-l_{d-1}]$ for $d$ dimensional space. Therefore, we need Intersection Index to index the intersecting $d-1$ dimensional hyperplanes for any two $d$ dimensional hyperplanes. \subsubsection{Indexing} In this subsection, we show how to build Order Vector Index and Intersection Index. \partitle{Order Vector Index} We show how to build Order Vector Index in high dimensional space in Algorithm \ref{Alg:index-basedPreHigherD}. We first compute skyline points using $O(n\log ^{d-1}n)$ time skyline algorithm in Line 1. For each skyline point, we compute its corresponding hyperplane $p_i$ for point $p_i$ in $d$ dimensional dual space in Lines 2-3. In Line 6, we compute the intersecting $d-1$ dimensional hyperplane of $d$ dimensional hyperplanes $p_i$ and $p_j$ by eliminating $x_d$. For these $u \choose 2$ intersecting $d-1$ dimensional hyperplanes, we compute the arrangement\footnote{Let $L$ be a set of $n$ lines in the plane. The set $L$ induces a subdivision of the plane that consists of vertices, edges, and faces. This subdivision is usually referred to as the arrangement induced by $L$ \cite{de2000computational}. Similarly, in high dimensional space, let $H$ be a set of $n$ hyperplanes in $d$ dimensional space. The set $H$ induces a subdivision of the space that consists of vertices, edges, faces, facets, and hypercells.} in Line 7. In Line 8, for each hypercell in the arrangement, we compute its initial $\textbf{ov}_i$ which records the order of the hyperplanes in their closeness to hyperplane $x_d=0$. Therefore, in the query phase, we only need to locate any point from the query range to get the corresponding hypercell and then get the corresponding $\textbf{ov}$ of the hypercell in logarithmic time. \begin{algorithm}[h] \scriptsize \caption{Indexing in high dimensional space.}\label{Alg:index-basedPreHigherD} \SetKwInOut{Input}{input}\SetKwInOut{Output}{output} \Input{a set of $n$ points in high dimensional space.} \Output{Order Vector Index.} use the $O(n\log^{d-1} n)$ time complexity algorithm to compute the $u$ skyline points of $n$ points\; \For{i = 1 to u}{ compute the dual $d$ dimensional hyperplane of $p_i$\; } \For{i = 1 to u-1}{ \For{j = i+1 to u}{ compute the $d-1$ dimensional hyperplane of hyperplanes $dh_i$ and $dh_j$ by eliminating $x_d$\; } } compute the arrangement of these $u\choose 2$ hyperplanes in $d-1$ dimensional space\; for each hypercell, compute its initial $\textbf{ov}$\; \end{algorithm} \partitle{Intersection Index} It is easy to see that the dominating part of the query for high dimensional space is to find these pairs of hyperplanes whose intersecting hyperplanes intersect with the query range. If we scan all the $u\choose 2$ intersecting $d-1$ dimensional hyperplanes to determine if they intersect with the $d-1$ dimensional query range, the time cost is prohibitively high. Therefore, we show how to index these $u\choose 2$ intersecting hyperplanes to facilitate the search of intersecting hyperplanes in Intersection Index. We first show a Line Quadtree\footnote{We call line quadtree in two dimensional space or hyperplane octree in high dimensional space, but for the sake of simplicity, we use the term ``line quadtree'' to refer to both two and high dimensional space.} with good average case performance, then show a Cutting Tree with good worst case performance. We note that we are indexing lines/hyperplanes, so the traditional indexes, e.g., R-tree, are not suitable. We use three dimensional space as an example, which corresponds to finding the intersecting lines that are intersecting with rectangle $x_1\in [-h_1,-l_1]$, $x_2\in [-h_2,-l_2]$. (\emph{Line Quadtree}) Line quadtree is a rooted tree in which every internal node has four children in two dimensional space. In genral, a $d$ dimensional hyperplane octree has $2^d$ children in each internal node. Every node in line quadtree corresponds to a square. If a node $t$ has children, then their corresponding squares are the four quadrants of the square of $t$, referred to as NE, NW, SW, and SE. Figure \ref{fig:quadtree} illustrates an example of line quadtree and the corresponding subdivision. We set the maximum capacity for each node as $3$, i.e., we need to partition a square into four subdivisions if there are more than $3$ lines going through this square. \begin{figure}[htb] \centering \includegraphics[width=0.4\textwidth]{quadtree} \caption{Line quadtree with maximum capacity $3$.} \label{fig:quadtree} \end{figure} It is easy to see how to construct line quadtree. The recursive definition of line quadtree is immediately translated into a recursive algorithm: split the current square into four quadrants, partition the line set accordingly, and recursively construct line quadtrees for each quadrant with its associated line set. The recursion stops when the line set contains less than maximum capacity lines. Line quadtree can be constructed in $O(de\times n)$ time with $O(de\times n)$ nodes, where $de$ is the depth of the corresponding line quadtree. To query line quadtree is straightforward. We start at the root node and examine each child node to check if it intersects the range being queried for. If it does, recurse into that child node. Whenever we encounter a leaf node, examine each entry to see if it intersects with the query range, and return it if it does. Finally, we combine all the returned lines. Line quadtree has a very good performance in the average case, however, the worst case is $O(n)$, i.e., the depth for line quadtree is $O(n)$ in the worst case. Therefore, we present an alternative index structure cutting tree which has a good worst case guarantee ($O(\log n)$ time complexity). \vspace{-1em} \begin{figure}[htb] \centering \includegraphics[width=0.4\textwidth]{cuttingtree} \caption{A $(1/3)$-cutting of size seven for a set of seven lines.} \label{fig:cuttingtree} \end{figure} (\emph{Cutting Tree}) Cutting tree partitions the space into a set of possibly unbounded triangles with the property that no triangle is crossed by more than $n/t$ lines, where $n$ is the number of lines and $t\in [1,n]$ is a parameter. For any set $L$ of $n$ lines in the plane, a $(1/t)$-cutting of size $O(t^2)$ exists. Moreover, such a cutting can be constructed in $O(nt)$ time \cite{de2000computational}. We show a $(1/3)$-cutting of size seven for a set of $7$ lines in Figure \ref{fig:cuttingtree}. For each triangle, there are at most ${7/3}$ intersecting lines. We note that cutting tree also can be designed as a tree structure as line quadtree. \begin{theorem}\cite{de2000computational} For any parameter $t$, it is possible to compute a $(1/t)$-cutting of size $O(t^d)$ with a deterministic algorithm that takes $O(nt^{d-1})$ time. The resulting data structure has $O(\log ^dn)$ query time. The query time can be reduced to $O(\log n)$. \end{theorem} We note that the deterministic algorithms for constructing cutting tree based on the arrangement structure are theoretical in nature and involve large constant factors \cite{de2000computational}. Therefore, in this paper, we implement the cutting tree index structure using the probabilistic schemes \cite{DBLP:conf/stoc/Clarkson85}\cite{DBLP:conf/stoc/Clarkson86}, which will be shown in the experimental section. We randomly choose $t$ hyperplanes from $n$ hyperplanes, and the formed arrangement structure will have a high probability satisfying the requirement of cutting tree. However, constructing arrangement is also a prohibitively high cost task with time complexity $O(n^d)$ \cite{DBLP:journals/siamcomp/EdelsbrunnerOS86}. Following the same spirit, the space with more hyperplanes will be chosen. For the space with more hyperplanes, the space will be chosen with a higher probability to be partitioned. Due to the same problem of constructing arrangement, we cannot process the point location in logarithmic time in high dimensional space in practice. Therefore, we compute $\textbf{ov}$ in Line 1 of Algorithm $\ref{Alg:index-basedQueryHigherD}$, which requires $O(u)$ time and does not impact the entire time complexity. \subsubsection{Querying} In this subsection, we show how to process the eclipse query based on Order Vector Index and Intersection Index in Algorithm \ref{Alg:index-basedQueryHigherD}. The idea is very similar to the two dimensional case. In Line 1, we get the initial $\textbf{ov}$ by point location in $O(\log n)$ time. We then quickly find the intersecting $d-1$ dimensional hyperplanes based on Intersection Index in Line 2. For any $d-1$ dimensional hyperplane formed by $d$ dimensional hyperplanes $p_a$ and $p_b$, if $\textbf{ov}[a]<\textbf{ov}[b]$, that means before this intersecting $d-1$ dimensional hyperplane, $p_a$ dominates $p_b$, thus, we have $\textbf{ov}[a]--$. Otherwise, we have $\textbf{ov}[b]--$. Finally, if $\textbf{ov}[i]=0$, we add $p_i$ to eclipse points. \begin{algorithm}[h] \scriptsize \caption{Query for high dimensions.}\label{Alg:index-basedQueryHigherD} \SetKwInOut{Input}{input}\SetKwInOut{Output}{output} \Input{Order Vector Index and Intersection Index, attribute weight ratio vector $\langle r[1], r[2],...,r[d-1]\rangle$, where $r[j]\in [l_j, h_j]$ for $j=1,2,...,d-1$.} \Output{eclipse points.} choose any point from the query range to process the point location to get the initial $\textbf{ov}$ from Order Vector Index\; find these $d-1$ dimensional hyperplanes intersecting with the query range $x_1\in [-h_1,-l_1], x_2\in [-h_2,-l_2]$,...,$x_{d-1}\in [-h_{d-1},-l_{d-1}]$ from Intersection Index\; \For{i = 1 to m (number of intersecting $d-1$ dimensional hyperplanes)}{ assume hyperplanes $p_{a}$ and $p_b$ form this $d-1$ dimensional hyperplane\; \If{$\textbf{ov}[a]<\textbf{ov}[b]$}{ $\textbf{ov}[b]--$; } \Else { $\textbf{ov}[a]--$; } } \For{i =1 to u}{ \If{$\textbf{ov}[i]=0$}{ add $p_i$ to eclipse points\; } } \end{algorithm} \begin{theorem}\label{the:10} The time complexity of Algorithm \ref{Alg:index-basedQueryHigherD} is $O(u+m)$. \end{theorem} \begin{proof} Lines 1 can be finished in $O(\log u^2)$ time based on the arrangement structure \cite{DBLP:journals/comgeo/ChazelleF94}. Line 2 requires $O(\log u^2+m)$ time based on the cutting tree index structure. Lines 3-8 require $O(m)$ time. Lines 9-11 require $O(u)$ time. Thus, Algorithm \ref{Alg:index-basedQueryHigherD} requires $O(u+m)$ time in total. \end{proof} \section{Experiments}\label{sec:Experiments} In this section, we present experimental studies evaluating our algorithms for computing eclipse points. \subsection{Experiment Setup} We implemented the following algorithms in Python and ran experiments on a machine with Intel Core i7 running Ubuntu with 8GB memory. \vspace{-1em} \begin{itemize} \item \textbf{BASE:} Baseline algorithm (Section \ref{sec:transformation-based}).\vspace{-0.7em} \item \textbf{TRAN:} Transformation-based Algorithm (Section \ref{sec:transformation-based}).\vspace{-0.7em} \item \textbf{QUAD:} Index-based Algorithm with Line QuadTree (Section \ref{sec:index-based}).\vspace{-0.7em} \item \textbf{CUTTING:} Index-based Algorithm with Cutting Tree (Section \ref{sec:index-based}). \end{itemize} \vspace{-1em} We used both synthetic datasets and a real NBA dataset in our experiments. To study the scalability of our methods, we generated independent (INDE), correlated (CORR), and anti-correlated (ANTI) datasets following the seminal work \cite{DBLP:conf/icde/BorzsonyiKS01}. We also built a real dataset that contains 2384 NBA players. The data was extracted from http://stats.nba.com/leaders/alltime/?ls=iref:nba:gnav on 04/15/2015. Each player has five attributes that measure the player's performance. These attributes are Points (PTS), Rebounds (REB), Assists (AST), Steals (STL), and Blocks (BLK). The parameter settings are shown in Table \ref{tab:par}. For the sake of simplicity and w.l.o.g., we consider $r[1]=r[2]=...=r[d-1]$ in this paper. \vspace{-1em} \begin{table}[htb]\centering \caption{Parameter settings (defaults are in bold).}\label{tab:par} \vspace{-1em} {% \footnotesize \begin{tabular}{|c|c|} \hline Param. & Settings\\ \hline $n$ & $2^7$, $\mathbf{2^{10}}$, $2^{13}$, $2^{17}$, $2^{20}$\\ \hline $d$ & $2$, $\textbf{3}$, $4$, $5$\\ \hline $r[j]$ & $[0.18,5.67]$, $\mathbf{[0.36,2.75]}$, $[0.58,1.73]$, $[0.84,1.19]$\\ angle & $[100,170]$, ~~$\mathbf{[110,160]}$, ~~$[120,150]$, ~$[130,140]$\\ \hline \end{tabular}} \end{table}% \partitle{Cutting Tree Implementation} Given a dataset of $n$ points in $d$ dimensional space, we map these $n$ points into $n$ hyperplanes in $d$ dimensional dual space correspondingly. For any two $d$ dimensional hyperplanes, they form a $d-1$ dimensional hyperplane by eliminating $x_d$. Therefore, we have $n \choose 2$ intersecting hyperplanes in $d-1$ dimensional space. For any $d-1$ dimensional hyperplanes in $d-1$ dimensional space, they form a $d-1$ dimensional point. Therefore, we have ${n\choose 2} \choose {d-1}$ intersecting points in $d-1$ dimensional space. For these ${n\choose 2} \choose {d-1}$ intersecting points, we randomly choose $t^d$ points. We employ the classic Voronoi algorithm to compute the Voronoi hypercells for these $t^d$ points, i.e., the $d-1$ dimensional space is partitioned into $t^d$ regions. The intuition for this implementation is clear. For a subregion with more hyperplanes, there has more intersecting points. If we randomly sample points, then this region will have more points to be selected with high probability. With more points to be selected, this subregion can be partitioned into more subregions, which leads to the smaller number of hyperplanes intersecting with each subregion. We note that this implementation is better than the cutting tree implementation based on the arrangement structure even from the theoretical perspective because the time complexity for computing Voronoi diagram is $O(n^{d/2})$ \cite{DBLP:conf/focs/Chazelle91} while computing arrangement structure requires $O(n^d)$ time \cite{DBLP:journals/siamcomp/EdelsbrunnerOS86} in $d$ dimensional space. \subsection{Case Study}\label{subsec:caseStudy} We performed a user study using the hotel example (Figure \ref{fig:1nn}). We posted a questionnaire using the conference scenario to ask $38$ students and staff members in our department and $30$ workers from Amazon Mechanical Turk. We asked them to choose the best hotel reservation system. The hotel reservation systems include skyline system, top-$k$ system, eclipse-ratio system, e.g., $r[1]\in [0.3,0.5]$, eclipse-weight system, e.g., $w[1]\in [0.3,0.5]$ and $w[2]=1-w[1]$, and eclipse-category system, e.g., $w[1]$ is very important/important/similar/unimportant/very unimportant compared to $w[2]$, where each category corresponds to a range. We received $61$ responses in total. Table \ref{tab:casestudy} shows the number of answers for each hotel systems. The results show that eclipse-category system attracts more attentions and our algorithms for computing eclipse points can be easily adapted for each of the eclipse systems. \begin{table}[htb]\centering \caption{Results of case study.}\label{tab:casestudy} \vspace{-1em} {% \begin{tabular}{|c|c|c|c|c|c|} \hline skyline & top-$k$ & eclipse-ratio & eclipse-weight & eclipse-category\\ \hline 13 & 7 & 8 & 8 & 25\\ \hline \end{tabular}} \end{table}% \subsection{Average Number of Eclipse Points}\label{subsec:average} In this subsection, we study the average number of eclipse points on the independent and identically distributed datasets, which can be used for designing attribute weight ratio vector. It is easy for a user to set the attribute weight vector, but it is hard for the user to estimate how many eclipse points will be returned. If we compute the expected number of eclipse points in advance, the user can adjust the attribute weight ratio vector according to the desired number of eclipse points. The number of eclipse points for different number of points $n$, different number of dimensions $d$, and different attribute weight ratio vectors $\textbf{r}=\langle r[1],r[2],...,r[d-1]\rangle$ are shown in Tables \ref{tab:diffn}, \ref{tab:diffd}, and \ref{tab:diffAttri}, respectively. We can see that the number of points has very small impact on the number of eclipse points, but the number of dimensions and the attribute weight ratios have significant impact. \begin{table}[htb]\centering \caption{Expected number of eclipse points vs. $n$.}\label{tab:diffn} \vspace{-1em} {% \begin{tabular}{|c|c|c|c|c|c|c|c|} \hline $n$ & $2^7$ & $2^{10}$ & $2^{13}$ & $2^{17}$ & $2^{20}$\\ \hline \# eclipse points & 3.71 & 3.83 & 3.91 & 4.03 & 4.13\\ \hline \end{tabular}} \end{table}% \vspace{-1em} \begin{table}[htb]\centering \caption{Expected number of eclipse points vs. $d$.}\label{tab:diffd} \vspace{-1em} {% \begin{tabular}{|c|c|c|c|c|c|c|c|} \hline $d$ & $2$ & $3$ & $4$ & $5$\\ \hline \# eclipse points & $1.8$ & $3.8$ & $8.5$ & $17.2$\\ \hline \end{tabular}} \end{table}% \begin{table}[htb]\centering \caption{Expected number of eclipse points vs. $r$.}\label{tab:diffAttri} \vspace{-1em} {% \begin{tabular}{|c|c|c|c|c|c|c|c|} \hline $r$ & [0.18,5.67] & [0.36,2.75] & [0.58,1.73] & [0.84,1.19]\\ \hline \# ecl. pts & 7.2 & 3.8 & 2.2 & 1.3\\ \hline \end{tabular}} \end{table}% \begin{figure*}[!htb] \centering \subfigure[\scriptsize{time cost of CORR}]{ \begin{minipage}[b]{0.22\textwidth} \includegraphics[width=1.1\linewidth]{ncorr} \end{minipage} } \subfigure[\scriptsize{time cost of INDE}]{ \begin{minipage}[b]{0.22\textwidth} \includegraphics[width=1.1\linewidth]{ninde} \end{minipage} } \subfigure[\scriptsize{time cost of ANTI}]{ \begin{minipage}[b]{0.22\textwidth} \includegraphics[width=1.1\linewidth]{nanti} \end{minipage} } \subfigure[\scriptsize{time cost of NBA}]{ \begin{minipage}[b]{0.22\textwidth} \includegraphics[width=1.1\linewidth]{nnba} \end{minipage} } \vspace{-1em}\captionsetup{font={scriptsize}}\caption{The impact of $n$.} \label{fig:nAverage} \end{figure*} \begin{figure*}[!htb] \centering \subfigure[\scriptsize{time cost of CORR}]{ \begin{minipage}[b]{0.22\textwidth} \includegraphics[width=1.1\linewidth]{dcorr} \end{minipage} } \subfigure[\scriptsize{time cost of INDE}]{ \begin{minipage}[b]{0.22\textwidth} \includegraphics[width=1.1\linewidth]{dinde} \end{minipage} } \subfigure[\scriptsize{time cost of ANTI}]{ \begin{minipage}[b]{0.22\textwidth} \includegraphics[width=1.1\linewidth]{danti} \end{minipage} } \subfigure[\scriptsize{time cost of NBA}]{ \begin{minipage}[b]{0.22\textwidth} \includegraphics[width=1.1\linewidth]{dnba} \end{minipage} } \vspace{-1em}\captionsetup{font={scriptsize}}\caption{The impact of $d$.} \label{fig:dAverage} \end{figure*} \begin{figure*}[!htb] \centering \subfigure[\scriptsize{time cost of CORR}]{ \begin{minipage}[b]{0.22\textwidth} \includegraphics[width=1.1\linewidth]{rcorr} \end{minipage} } \subfigure[\scriptsize{time cost of INDE}]{ \begin{minipage}[b]{0.22\textwidth} \includegraphics[width=1.1\linewidth]{rinde} \end{minipage} } \subfigure[\scriptsize{time cost of ANTI}]{ \begin{minipage}[b]{0.22\textwidth} \includegraphics[width=1.1\linewidth]{ranti} \end{minipage} } \subfigure[\scriptsize{time cost of NBA}]{ \begin{minipage}[b]{0.22\textwidth} \includegraphics[width=1.1\linewidth]{rnba} \end{minipage} } \vspace{-1em}\captionsetup{font={scriptsize}}\caption{The impact of ratio $r$.} \label{fig:rAverage} \end{figure*} \begin{figure}[t] \begin{minipage}[t]{0.22\textwidth} \centering \includegraphics[width=1.1\linewidth]{worstN} \captionsetup{font={scriptsize}} \caption{Worst case ($d=3$).} \label{fig:worstN} \end{minipage}% \begin{minipage}[t]{0.22\textwidth} \centering \includegraphics[width=1.1\linewidth]{worstD} \captionsetup{font={scriptsize}} \caption{Worst case ($n=2^7$).} \label{fig:worstD} \end{minipage} \end{figure} \subsection{Performances in the Average Case} In this subsection, we report the experimental results for our proposed four algorithms in the average case. \partitle{The impact of $n$} Figures \ref{fig:nAverage}(a)(b)(c)(d) present the time cost of BASE, TRAN, QUAD, and CUTTING with varying number of points $n$ for the three synthetic datasets and the real NBA dataset ($d=3, r[j]\in [0.36,2.75]$). For the baseline algorithm BASE and the transformation-based TRAN, TRAN is significantly faster than BASE, especially on the ANTI dataset. The reason is that BASE is very sensitive to the number of eclipse points and there are more eclipse points for the ANTI dataset. For the index-based algorithms QUAD and CUTTING, QUAD outperforms CUTTING because the index structure of QUAD is much simpler and it is easier to find the intersecting hyperplanes. Comparing all the different algorithms, the index-based algorithms significantly outperform BASE and TRAN, which validates the benefit of our index structures, especially for large n. From the viewpoint of different datasets, the time cost is in increasing order for CORR, INDE, and ANTI, due to the increasing number of eclipse points. \partitle{The impact of $d$} Figures \ref{fig:dAverage}(a)(b)(c)(d) present the time cost of BASE, TRAN, QUAD, and CUTTING with varying number of dimensions $d$ for the three synthetic datasets ($n=2^{10}, r[j]\in [0.36,2.75]$) and the real NBA dataset ($n=1000, r[j]\in [0.36,2.75]$). For the non-index-based algorithms BASE and TRAN, TRAN is significantly faster than BASE. For the index-based algorithms QUAD and CUTTING, QUAD significantly outperforms CUTTING, especially for large $d$. The reason is that it is time-consuming to find the intersecting Voronoi hypercells because the number of the vertexes of each Voronoi hypercell in high dimensional space is too high, while it is very easy to find the intersecting subquadrants in QUAD. Comparing all the different algorithms, QUAD and CUTTING significantly outperform BASE and TRAN again, which validates the benefit of our index structures. Because QUAD and CUTTING employ the same binary search tree structure in two dimensional space, they have the same performance. \partitle{The impact of ratio $r$} Figures \ref{fig:rAverage}(a)(b)(c)(d) present the time cost of QUAD and CUTTING with varying attribute weight ratio vectors for the three synthetic datasets ($n=2^{10}, d=3$) and the real NBA dataset ($n=1000, d=3$). Because the attribute weight ratio vector has no impact on the transformation-based algorithms, we did not report the time cost for them. For the index-based algorithms QUAD and CUTTING, QUAD significantly outperforms CUTTING again. We can observe that the larger ratio range, the higher time cost for both index-based algorithms. The reason is that we need to search for more space for the larger ratio range, which means that we need to compute more intersections. \subsection{Performances in the Worst Case} QUAD has a good performance in the average case, however, QUAD is very sensitive to the dataset distribution because line quadtree can be quite unbalanced if all the lines almost lie in the same quadrant in each layer. We did the experiment with the scenario where all the lines almost lie in the same quadrant. Because the index-based algorithms significantly outperform the transformation-based algorithms, in this subsection, we only report the experimental results for the index-based algorithms in the worst case. Figure \ref{fig:worstN} presents the worst case time cost of QUAD and CUTTING on different number of points $n$. It is easy to see that CUTTING always outperforms QUAD because the depth for the line quadtree index structure is $O(n)$ in the worst case, i.e., we need to scan all the lines. Figure \ref{fig:worstD} presents the worst case time cost of QUAD and CUTTING on different number of dimensions $d$. It is easy to see that CUTTING outperforms QUAD again, however, with the increasing of the number of dimensions $d$, the difference becomes small because there are too many vertexes for each Voronoi hypercell in high dimensional space. \section{Related Work}\label{sec:Related} The $k$NN query is the most well-known similarity query. Furthermore, $k$NN has been extensively used in the machine learning field, such as $k$NN classification \cite{DBLP:journals/tit/CoverH67} and $k$NN regression \cite{altman1992introduction}. The most disadvantage of $k$NN query is that it is hard to set the exact and appropriate attribute weight vector. Skyline is a fundamental problem in computational geometry because skyline is an interesting characterization of the boundary of a set of points. Since the introduction of the skyline operator by Borzsonyi et al. \cite{DBLP:conf/icde/BorzsonyiKS01}, Skyline has been extensively studied in database. \cite{DBLP:journals/ipl/LiuXX14} presented state-of-the-art algorithm for computing skyline from the theoretical aspect. To facilitate the skyline query, skyline diagram was defined in \cite{DBLP:conf/icde/LiuY0PL18}. To protect data privacy and query privacy, secure skyline query was studied in \cite{DBLP:conf/icde/LiuY0P17}. \cite{DBLP:journals/tkde/CuiCXLSX09} studied the skyline in P2P systems. \cite{DBLP:conf/vldb/PeiJLY07, DBLP:conf/cikm/LiuZXLL15, DBLP:journals/www/ZhangLCZC15} studied the skyline on the uncertain dataset. \cite{DBLP:conf/ssdbm/LuZH10} studied the continuous skyline over distributed data streams. \cite{DBLP:journals/pvldb/LiuXPLZ15, DBLP:conf/cikm/YuQL0CZ17} generalized the original skyline definition for individual points to permutation group-based skyline for groups. \cite{ehrgott2005multicriteria} detailedly discussed the multicriteria optimization problem subjected to a weighted sum range. \cite{zitzler2002performance} presented the quantitative comparison of the performance of different approximate algorithms for skyline. The drawback of skyline is that the number of skyline points can be prohibitively high. There are lots of existing works trying to alleviate this problem \cite{DBLP:conf/icde/LinYZZ07, DBLP:conf/icde/TaoDLP09, DBLP:conf/icde/SarmaLNLX11, DBLP:journals/vldb/MagnaniAM14, DBLP:conf/edbt/SoholmCA16, DBLP:journals/tkde/BaiXWZZYW16, DBLP:journals/tkde/LuJZ11, DBLP:journals/vldb/ZhangLOT10}. Lin et al. \cite{DBLP:conf/icde/LinYZZ07} studied the problem of selecting $k$ skyline points to maximize the number of points dominated by at least one of these $k$ skyline points. Tao et al. \cite{DBLP:conf/icde/TaoDLP09} proposed a new definition of representative skyline that minimizes the distance between a non-representative skyline point and its nearest representative. Sarma et al. \cite{DBLP:conf/icde/SarmaLNLX11} formulated the problem of displaying $k$ representative skyline points such that the probability that a random user would click on one of them is maximized. Magnani et al. \cite{DBLP:journals/vldb/MagnaniAM14} proposed a new representative skyline definition which is not sensitive to rescaling or insertion of non-skyline points. Soholm et al. \cite{DBLP:conf/edbt/SoholmCA16} defined the maximum coverage representative skyline which maximizes the dominated data space of $k$ points. Lu et al. \cite{DBLP:journals/tkde/LuJZ11} proposed the top-$k$ representative skyline based on skyline layers. Zhang et al.\cite{DBLP:journals/vldb/ZhangLOT10} showed a cone dominance definition which can control the size of returned points. All those works are focused on static data, while Bai et al. \cite{DBLP:journals/tkde/BaiXWZZYW16} studied the representative skyline definition over data streams. Another related direction to our work is dynamic preferences \cite{DBLP:journals/tkde/WongPFW09, DBLP:journals/pvldb/WongFPHWL08, DBLP:conf/kdd/WongFPW07}. Taking the weather as an example, we only consider sunny and raining here. We may prefer sunny for hiking but we may prefer raining for sleeping because raining makes you feel more comfortable. Mindolin et al. \cite{DBLP:journals/pvldb/MindolinC09, DBLP:journals/vldb/MindolinC11} proposed a framework ``p-skyline'' which incorporates relative attribute importance in skyline allows for reduction in the corresponding query result size. In this paper, we formally generalize the $1$NN and skyline queries with eclipse using the notion of dominance. The most related to our work is \cite{DBLP:journals/pvldb/CiacciaM17}. They defined a query similar to the eclipse query we initially presented in \cite{DBLP:journals/corr/Liu0ZL17} without studying the formal properties with respect to the domination. In addition, they only presented one algorithm for which we formally proved the correctness and used as a baseline algorithm. We then presented significantly more efficient transformation-based algorithms and new index-based eclipse query algorithms for computing eclipse points. \section{Conclusion}\label{sec:Conclusion} In this paper, we proposed a novel eclipse definition which provides a more flexible and customizable definition for the classic $1$NN and skyline. We first illustrated a baseline $O(n^22^{d-1})$ algorithm to compute eclipse points, and then presented an efficient $O(n\log^{d-1} n)$ algorithm by transforming the eclipse problem to the skyline problem. For different users with different attribute weight vectors, we showed how to process the eclipse query based on the index structures and duality transform in $O(u+m)$ time. A comprehensive experimental study is reported demonstrating the effectiveness and efficiency of our eclipse algorithms. {\tiny \bibliographystyle{abbrv}\tiny
{'timestamp': '2019-06-17T02:18:11', 'yymm': '1906', 'arxiv_id': '1906.06314', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06314'}
arxiv
\section*{Acknowledgements}
{'timestamp': '2019-06-18T02:03:00', 'yymm': '1906', 'arxiv_id': '1906.06425', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06425'}
arxiv
\section{Introduction} \label{sec:intro} Natural language inference (NLI), also known as recognizing textual entailment (RTE), has been proposed as a benchmark task for natural language understanding. Given a premise $P$ and a hypothesis $H$, the task is to determine whether the premise semantically entails the hypothesis~\cite{series/synthesis/2013Dagan}. A number of recent works attempt to test and analyze what type of inferences an NLI model may be performing, focusing on various types of lexical inferences~\cite{glockner-shwartz-goldberg:2018:Short,naik-EtAl:2018:C18-1,poliak-EtAl:2018:S18-2} and logical inferences~\cite{Bowman2015,Evans2018CanNN}. Concerning logical inferences, monotonicity reasoning~\cite{10.2307/25001141,moss2014}, which is a type of reasoning based on word replacement, requires the ability to capture the interaction between lexical and syntactic structures. Consider examples in (\ref{ex:1}) and (\ref{ex:2}). {\footnotesize \begin{exe} \ex \label{ex:1} \begin{xlist} \ex \label{ex:1a} \textit{\textbf{All}} [\,\negative{\textit{\underline{workers}}}] [\positive{\textit{joined for a \underline{French dinner}}}] \ex \label{ex:1b} \textit{All workers joined for a \underline{dinner}} \ex \label{ex:1c} \textit{All \underline{new workers} joined for a French dinner} \end{xlist} \ex \label{ex:2} \begin{xlist} \ex \label{ex:2a} \textit{\textbf{Not all}} [\positive{\textit{\underline{new workers}}}] \textit{joined for a dinner} \ex \label{ex:2b} \textit{Not all \underline{workers} joined for a dinner} \end{xlist} \end{exe} } \noindent A context is \textbf{upward entailing} (shown by [...\positive{}]) that allows an inference from (\ref{ex:1a}) to (\ref{ex:1b}), where \textit{French dinner} is replaced by a more general concept \textit{dinner}. On the other hand, a \textbf{downward entailing} context (shown by [...\negative{}]) allows an inference from (\ref{ex:1a}) to (\ref{ex:1c}), where \textit{workers} is replaced by a more specific concept \textit{new workers}. Interestingly, the direction of monotonicity can be reversed again by embedding yet another downward entailing context (e.g., \textit{not} in (\ref{ex:2})), as witness the fact that (\ref{ex:2a}) entails (\ref{ex:2b}). To properly handle both directions of monotonicity, NLI models must detect monotonicity operators (e.g., \textit{all}, \textit{not}) and their arguments from the syntactic structure. For previous datasets containing monotonicity inference problems, FraCaS~\cite{cooper1994fracas} and the GLUE diagnostic dataset~\cite{wang2018glue} are manually-curated datasets for testing a wide range of linguistic phenomena. However, monotonicity problems are limited to very small sizes (FraCaS: 37/346 examples and GLUE: 93/1650 examples). The limited syntactic patterns and vocabularies in previous test sets are obstacles in accurately evaluating NLI models on monotonicity reasoning. To tackle this issue, we present a new evaluation dataset\footnote{The dataset will be made publicly available at https://github.com/verypluming/MED.} that covers a wide range of monotonicity reasoning that was created by crowdsourcing and collected from linguistics publications (Section~\ref{sec:data}). Compared with manual or automatic construction, we can collect naturally-occurring examples by crowdsourcing and well-designed ones from linguistics publications. To enable the evaluation of skills required for monotonicity reasoning, we annotate each example in our dataset with linguistic tags associated with monotonicity reasoning. We measure the performance of state-of-the-art NLI models on monotonicity reasoning and investigate their generalization ability in upward and downward reasoning (Section~\ref{sec:result}). The results show that all models trained with SNLI~\cite{Bowman2015} and MultiNLI~\cite{DBLP:journals/corr/WilliamsNB17} perform worse on downward inferences than on upward inferences. \final{In addition, we analyzed the performance of models trained with an automatically created monotonicity dataset, HELP~\cite{yanaka2019}.} The analysis with monotonicity data augmentation shows that models tend to perform better in the same direction of monotonicity with the training set, while they perform worse in the opposite direction. This indicates that the accuracy on monotonicity reasoning depends solely on the majority direction in the training set, and models might lack the ability to capture the structural relations between monotonicity operators and their arguments. \section{Monotonicity} \label{sec:background} As an example of a monotonicity inference, consider the example with the determiner \textit{every} in (\ref{ex:3}); here the premise $P$ entails the hypothesis $H$. {\footnotesize \begin{exe} \ex \label{ex:3} \begin{xlist} \exi{$P$:} \label{ex:3a} \textit{Every} \np{\negative{\textit{\underline{person}}}} \vp{\positive{\textit{bought a \underline{movie ticket}}}} \exi{$H$:} \label{ex:3b} \textit{Every \underline{young person} bought a \underline{ticket}} \end{xlist} \end{exe} } \noindent \textit{Every} is downward entailing in the first argument ($\mathsf{NP}$) and upward entailing in the second argument ($\mathsf{VP}$), and thus the term \textit{person} can be more specific by adding modifiers (\textit{person} $\sqsupseteq$ \textit{young person}), replacing it with its hyponym (\textit{person} $\sqsupseteq$ \textit{spectator}), or adding conjunction (\textit{person} $\sqsupseteq$ \textit{person and alien}). On the other hand, the term \textit{buy a ticket} can be more general by removing modifiers (\textit{bought a movie ticket} $\sqsubseteq$ \textit{bought a ticket}), replacing it with its hypernym (\textit{bought a movie ticket} $\sqsubseteq$ \textit{bought a show ticket}), or adding disjunction (\textit{bought a movie ticket} $\sqsubseteq$ \textit{bought or sold a movie ticket}). Table~\ref{tab:downex} shows determiners modeled as binary operators and their polarities with respect to the first and second arguments. \begin{table}[bt] \scalebox{0.75}{ \begin{tabular}{lll} \hline Determiners&First argument&Second argument\\ \hline \hline \textit{every, each, all}&downward&upward\\ \hline \textit{some, a, a few, many,}&\multirow{2}{*}{upward}&\multirow{2}{*}{upward}\\ \textit{several}, proper noun&&\\ \hline \textit{any, no, few, at most X,}&\multirow{2}{*}{downward}&\multirow{2}{*}{downward}\\ \textit{fewer than X, less than X}&&\\ \hline \textit{the, both, most, this, that}&non-monotone&upward\\ \hline \textit{exactly}&non-monotone&non-monotone\\ \hline \end{tabular} } \caption{\label{tab:downex} Determiners and their polarities.} \end{table} \begin{table}[bt] \scalebox{0.81}{ \begin{tabular}{ll} \hline Category&Examples\\ \hline \hline determiners & \textit{every, all, any, few, no}\\ \hline negation & \textit{not, n't, never} \\ \hline verbs & \textit{deny, prohibit, avoid} \\ \hline nouns & \textit{absence of, lack of, prohibition} \\ \hline adverbs & \textit{scarcely, hardly, rarely, seldom} \\ \hline prepositions & \textit{without, except, but} \\ \hline conditionals & \textit{if, when, in case that, provided that, unless}\\ \hline \end{tabular} } \caption{\label{tab:downex2} Examples of downward operators.} \end{table} There are various types of downward operators, not limited to determiners (see Table~\ref{tab:downex2}). As shown in (\ref{ex:4}), if a propositional object is embedded in a downward monotonic context (e.g., \textit{when}), the polarity of words over its scope can be reversed. {\footnotesize \begin{exe} \ex \label{ex:4} \begin{xlist} \exi{$P$:} \textit{When} [\textit{every} \np{\positive{\textit{young person}}} \vp{\negative{\textit{bought a ticket}}}], [\textit{that shop was open}] \exi{$H$:} \textit{When} [\textit{every} \np{\textit{person}} \vp{\textit{bought a movie ticket}}], [\textit{that shop was open}] \end{xlist} \end{exe} } \noindent Thus, the polarity (\positiveI{} and \negativeI{}), where the replacement with more general (specific) phrases licenses entailment, needs to be determined by the interaction of monotonicity properties and syntactic structures; polarity of each constituent is calculated based on a monotonicity operator of functional expressions (e.g., \textit{every}, \textit{when}) and their function-term relations. \section{Dataset} \label{sec:data} \subsection{Human-oriented dataset} To create monotonicity inference problems, we should satisfy three requirements: (a) detect the monotonicity operators and their arguments; (b) based on the syntactic structure, induce the polarity of the argument positions; and (c) replace the phrase in the argument position with a more general or specific phrase in natural and various ways (e.g., by using lexical knowledge or logical connectives). For (a) and (b), we first conduct polarity computation on a syntactic structure for each sentence, and then select premises involving upward/downward expressions. For (c), we use crowdsourcing to narrow or broaden the arguments. The motivation for using crowdsourcing is to collect naturally alike monotonicity inference problems that include various expressions. One problem here is that it is unclear how to \final{instruct workers to} create monotonicity inference problems without knowledge of natural language syntax and semantics. We must make tasks simple for workers to comprehend and provide sound judgements. Moreover, recent studies~\cite{gururangan-EtAl:2018:N18-2,poliak-EtAl:2018:S18-2,DBLP:conf/lrec/Tsuchiya18} point out that previous crowdsourced datasets, such as SNLI~\cite{snli:emnlp2015} and MultiNLI~\cite{DBLP:journals/corr/WilliamsNB17}, include hidden biases. As these previous datasets are motivated by approximated entailments, workers are asked to freely write hypotheses given a premise, which does not strictly restrict them to creating logically complex inferences. Taking these concerns into consideration, we designed two-step tasks to be performed via crowdsourcing for creating a monotonicity test set; (i) a hypothesis creation task and (ii) a validation task. The task (i) is to create a hypothesis by making some polarized part of an original sentence more specific. Instead of writing a complete sentence from scratch, workers are asked to rewrite only a relatively short sentence. By restricting workers to rewrite only a polarized part, we can effectively collect monotonicity inference examples. The task (ii) is to annotate an entailment label for the premise-hypothesis pair generated in (i). \final{Figure~\ref{tab:fig2} summarizes the overview of our human-oriented dataset creation.} We used the crowdsourcing platform Figure Eight for both tasks. \begin{figure} \includegraphics[width=8cm, bb=0 0 497 320]{overview.png} \caption{\label{tab:fig2}\final{Overview of our human-oriented dataset creation. E: entailment, NE: non-entailment.}} \end{figure} \subsubsection{Premise collection} As a resource, we use declarative sentences with more than five tokens from the Parallel Meaning Bank (PMB)~\cite{abzianidze-EtAl:2017:EACLshort}. The PMB contains syntactically correct sentences annotated with its syntactic category in Combinatory Categorial Grammar (CCG;~\modelcite{Steedman00}) format, which is suitable for our purpose. To get a whole CCG derivation tree, we parse each sentence by the state-of-the-art CCG parser, depccg~\cite{yoshikawa-noji-matsumoto:2017:Long}. Then, we add a polarity to every constituent of the CCG tree by the polarity computation system ccg2mono~\cite{humoss2018} and make the polarized part a blank field. We ran a trial rephrasing task on 500 examples and detected 17 expressions that were too general and thus difficult to rephrase them in a natural way (e.g., \textit{every one}, \textit{no time}). We removed examples involving such expressions. To collect more downward inference examples, we select examples involving determiners in Table~\ref{tab:downex} and downward operators in Table~\ref{tab:downex2}. As a result, we selected 1,485 examples involving expressions having arguments with upward monotonicity and 1,982 examples involving expressions having arguments with downward monotonicity. \subsubsection{Hypothesis creation} We present crowdworkers with a sentence whose polarized part is underlined, and ask them to replace the underlined part with more specific phrases in three different ways. In the instructions, we showed examples rephrased in various ways: by adding modifiers, by adding conjunction phrases, and by replacing a word with its hyponyms. Workers were paid US\$0.05 for each set of substitutions, and each set was assigned to three workers. To remove low-quality examples, we set the minimum time it should take to complete each set to 200 seconds. The entry in our task was restricted to workers from native speaking English countries. 128 workers contributed to the task, and we created 15,339 hypotheses (7,179 upward examples and 8,160 downward examples). \subsubsection{Validation} The gold label of each premise-hypothesis pair created in the previous task is automatically determined by monotonicity calculus. That is, a downward inference pair is labeled as \textit{entailment}, while an upward inference pair is labeled as \textit{non-entailment}. However, workers sometimes provided some ungrammatical or unnatural sentences such as the case \final{where a rephrased phrase does not satisfy the selectional restrictions (e.g., original: \textit{Tom doesn't live in \underline{Boston}}, rephrased: \textit{Tom doesn't live in \underline{yes}})}, making it difficult to judge their entailment relations. Thus, we performed an annotation task to ensure accurate labeling of gold labels. We asked workers about the entailment relation of each premise-hypothesis pair as well as how natural it is. Worker comprehension of an entailment relation directly affects the quality of inference problems. To avoid worker misunderstandings, we showed workers the following definitions of labels and five examples for each label: \begin{enumerate} \item \textit{entailment}: the case where the \final{hypothesis} is true under any situation that the premise describes. \item \textit{non-entailment}: the case where the \final{hypothesis} is not always true under a situation that the premise describes. \item \textit{unnatural}: the case where either the premise and/or the \final{hypothesis} is ungrammatical or does not make sense. \end{enumerate} Workers were paid US\$0.04 for each question, and each question was assigned to three workers. To collect high-quality annotation results, we imposed ten test questions on each worker, and removed workers who gave more than three wrong answers. We also set the minimum time it should take to complete each question to 200 seconds. 1,237 workers contributed to this task, and we annotated gold labels of 15,339 premise-hypothesis pairs. Table~\ref{tab:result2} shows the numbers of cases where answers matched gold labels automatically determined by monotonicity calculus. This table shows that there exist inference pairs whose labels are difficult even for humans to determine; there are 3,354 premise-hypothesis pairs whose gold labels as annotated by polarity computations match with those answered by all workers. We selected these \final{naturalistic monotonicity inference} pairs for the candidates of the final test set. To \final{make the distribution of gold labels symmetric,} we checked these pairs to determine if we can swap the premise and the hypothesis, reverse their gold labels, and create another monotonicity inference pair. In some cases, shown below, the gold label cannot be reversed if we swap the premise and the hypothesis. \begin{table} \centering \scalebox{0.63}{ \begin{tabular}{lrrr} \hline & Upward /cases(\%)& Downward /cases(\%)&Total /cases(\%)\\ \hline \hline 3 labels match & 1,069 (7.0)& 2,285 (14.9) & 3,354 (21.9)\\ 2 labels match& 1,814 (11.8)& 2,301 (15.0) & 4,115 (26.8)\\ 1 labels match& 2,295 (15.0)& 1,915 (12.5) & 4,210 (27.5)\\ no match& 1,998 (27.8)& 1,652 (10.8) & 3,650 (37.8)\\ \hline \end{tabular} } \caption{\label{tab:result2} Numbers of cases where answers matched automatically determined gold labels.} \vspace{-1.0em} \end{table} \begin{table*} \begin{center} \scalebox{0.72}{ \begin{tabular}{lllll} \hline Genre&Tags& Premise & Hypothesis&Gold \\ \hline \hline \multirow{10}{*}{Crowd}&up& \textit{There is a cat on the chair}&\textit{There is a cat sleeping on the chair}&NE \\ \cline{2-5} &up:& \textit{If you heard her speak English, you would take her} & \textit{If you heard her speak English, you would take her}& \\ &cond& \textit{for a native American} &\textit{for an American}&E \\ \cline{2-5} &up:rev:&\textit{Dogs and cats have all the good qualities of people} & \textit{Dogs have all the good qualities of people without}& \\ &conj& \textit{without at the same time possessing their weaknesses} & \textit{at the same time possessing their weaknesses}&E \\ \cline{2-5} &up:lex&\textit{He approached the boy reading a magazine}&\textit{He approached the boy reading a book}&E\\ \cline{2-5} &down:lex& \textit{Tom hardly ever listens to music} & \textit{Tom hardly ever listens to rock 'n' roll}&E \\ \cline{2-5} &down:conj& \textit{You don't like love stories and sad endings} & \textit{You don't like love stories}&NE \\ \cline{2-5} &down:cond& \textit{If it is fine tomorrow, we'll go on a picnic} & \textit{If it is fine tomorrow in the field, we'll go on a picnic}&E\\ \cline{2-5} &down& \textit{I never had a girlfriend before} & \textit{I never had a girlfriend taller than me before}&E \\ \hline \multirow{7}{*}{Paper} &up:rev& \textit{Every cook who is not a tall man ran}&\textit{Every cook who is not a man ran}&E \\ \cline{2-5} &up:disj& \textit{Every man sang} &\textit{Every man sang or danced}&E \\ \cline{2-5} &up:lex:& \textit{None of the sopranos sang with fewer than three of} &\textit{None of the sopranos sang with fewer than three of}& \\ &rev& \textit{the tenors} &\textit{the male singers}&E \\ \cline{2-5} &non&\textit{Exactly one man ran quickly} &\textit{Exactly one man ran}&NE \\ \cline{2-5} &down&\textit{At most three elephants are blue}&\textit{At most three elephants are navy blue}&E\\ \hline \end{tabular} } \caption{\label{tab:ex} Examples in the MED dataset. Crowd: problems collected through crowdsourcing, Paper: problems collected from linguistics publications, up: upward monotone, down: downward monotone, non: non-monotone, cond: condisionals, rev: reverse, conj: conjunction, disj: disjunction, lex: lexical knowledge, E: entailment, NE: non-entailment.} \end{center} \end{table*} \begin{table} \centering \scalebox{0.72}{ \begin{tabular}{llrrr} \hline Type&Label&Crowd&Paper&Total\\ \hline \hline \multirow{2}{*}{Upward (1,820)}&Entailment&323&305&628\\ &Non-entailment&893&299&1,192\\ \hline \multirow{2}{*}{Downward (3,270)}&Entailment&1,871&201&2,072\\ &Non-entailment&979&219&1,198\\ \hline \multirow{2}{*}{Non-monotone (292)}&Entailment&0&15&15\\ &Non-entailment&2&275&277\\ \hline Total&&4,068&1,314&5,382\\ \hline \end{tabular} } \caption{\label{tab:ling} \final{Statistics for the MED dataset.}} \vspace{-1.0em} \end{table} \paragraph{(a) Replacement with synonyms} In (\ref{ex:7}), \textit{child} and \textit{kid} are not hyponyms but synonyms, and the premise $P$ and the hypothesis $H$ are paraphrases. {\footnotesize \begin{exe} \ex \label{ex:7} \begin{xlist} \exi{$P$:} \label{ex:7a} \textit{Tom is no longer a child} \exi{$H$:} \label{ex:7b} \textit{Tom is no longer a kid} \end{xlist} \end{exe} } \noindent These cases are not strict downward inference problems, in the sense that a phrase is not replaced by its hyponym/hypernym. \paragraph{(b) Non-constituents} Consider the example (\ref{ex:8}). {\footnotesize \begin{exe} \ex \label{ex:8} \begin{xlist} \exi{$P$:} \label{ex:8a} \textit{The moon has no atmosphere} \exi{$H$:} \label{ex:8b} \textit{The moon has no atmosphere, and the gravity force is too low} \end{xlist} \end{exe} } \noindent The hypothesis $H$ was created by asking workers to make \textit{atmosphere} in the premise $P$ more specific. However, the additional phrase \textit{and the gravity force is too low} does not form constituents with \textit{atmosphere}. Thus, such examples are not strict downward monotone inferences. In such cases as (a) and (b), we do not swap the premise and the hypothesis. In the end, we collected 4,068 examples from crowdsourced datasets. \subsection{Linguistics-oriented dataset} We also collect monotonicity inference problems from previous manually curated datasets and linguistics publications. The motivation is that previous linguistics publications related to monotonicity reasoning are expected to contain well-designed inference problems, which might be challenging problems for NLI models. We collected 1,184 examples from 11 linguistics publications~\cite{BarwiseCooper81,Hoeksema,HeimKratzer98,Asher,fyodorov03,Geurts03,GeurtsSlik,Zamansky06,Szabolcsi05,Winter,denic2019}. Regarding previous manually-curated datasets, we collected 93 examples for monotonicity reasoning from the GLUE diagnostic dataset, and 37 single-premise problems from FraCaS. Both the GLUE diagnostic dataset and FraCaS categorize problems by their types of monotonicity reasoning, but we found that each dataset has different classification criteria.\footnote{FraCaS categorizes each problem by whether its replacement broadens an argument (upward monotone) or narrows it (downward monotone).} Thus, following GLUE, we reclassified problems into three types of monotone reasoning (upward, downward, and non-monotone) by checking if they include (i) the target monotonicity operator in both the premise and the hypothesis and (ii) the phrase replacement in its argument position. In the GLUE diagnostic dataset, there are several problems whose gold labels are \textit{contradiction}. We regard them as \textit{non-entailment} in that the premise does not semantically entail the hypothesis. \subsection{Statistics} We merged the human-oriented dataset created via crowdsourcing and the linguistics-oriented dataset created from linguistics publications to create the current version of the monotonicity entailment dataset (MED). Table~\ref{tab:ex} shows some examples from the MED dataset. We can see that our dataset contains various phrase replacements (e.g., conjunction, relative clauses, and comparatives). Table~\ref{tab:ling} reports the statistics of the MED dataset, including 5,382 premise-hypothesis pairs (1,820 upward examples, 3,270 downward examples, and 292 non-monotone examples). Regarding non-monotone problems, gold labels are always \textit{non-entailment}, whether a hypothesis is more specific or general than its premise, and thus almost all non-monotone problems are labeled as \textit{non-entailment}.\footnote{15 non-monotone problems which include the replacement with synonyms are labeled as \textit{entailment}.} The size of the word vocabulary in the MED dataset is 4,023, and overlap ratios of vocabulary with previous standard NLI datasets is 95\% with MultiNLI and 90\% with SNLI. We assigned a set of annotation tags for linguistic phenomena to each example in the test set. These tags allow us to analyze how well models perform on each linguistic phenomenon related to monotonicity reasoning. We defined 6 tags \final{(see Table~\ref{tab:ex} for examples):} \begin{enumerate} \item \textit{lexical knowledge} (2,073 examples): inference problems that require lexical relations (i.e., hypernyms, hyponyms, or synonyms) \item \textit{reverse} (240 examples): inference problems where a propositional object is embedded in a downward environment more than once \item \textit{conjunction} (283 examples): inference problems that include the phrase replacement by adding conjunction (\textit{and}) to the hypothesi \item \textit{disjunction} (254 examples): inference problems that include the phrase replacement by adding disjunction (\textit{or}) to the hypothesis \item \textit{conditionals} (149 examples): inference problems that include conditionals (e.g., \textit{if, when, unless}) in the hypothesis \footnote{\final{\textit{When}-clauses can have temporal and non-temporal interpretations~\cite{steedman1988}. We assign the conditional tag to those cases where \textit{when} is interchangeable with \textit{if}, thus excluding those cases where \textit{when}-clauses have temporal episodic interpretation (e.g., \textit{When she came back from the trip, she bought a gift}).}} \item \textit{negative polarity items} (NPIs) (338 examples): inference problems that include NPIs (e.g., \textit{any, ever, at all, anything, anyone, anymore, anyhow, anywhere}) in the hypothesis \end{enumerate} \section{Results and Discussion} \label{sec:result} \subsection{Baselines} To test the difficulty of our dataset, we checked the majority class label and the accuracies of five state-of-the-art NLI models adopting different approaches: BiMPM (Bilateral Multi-Perspective Matching Model;~\modelcite{Wang:2017:BMM:3171837.3171865}), ESIM (Enhanced Sequential Inference Model;~\modelcite{chen-EtAl:2017:Long3}), Decomposable Attention Model~\cite{D16-1244}, KIM (Knowledge-based Inference Model;~\modelcite{P18-1224}), and BERT (Bidirectional Encoder Representations from Transformers model;~\modelcite{BERT2018new}). Regarding BERT, we checked the performance of a model pretrained on Wikipedia and BookCorpus for language modeling and trained with SNLI and MultiNLI. For other models, we checked the performance trained with SNLI. In agreement with our dataset, we regarded the prediction label \textit{contradiction} as \textit{non-entailment}. Table~\ref{tab:perform} shows that the accuracies of all models were better on upward inferences, in accordance with the reported results of the GLUE leaderboard. The overall accuracy of each model was low. In particular, all models underperformed the majority baseline on downward inferences, despite some models having rich lexical knowledge from a knowledge base (KIM) or pretraining (BERT). This indicates that downward inferences are difficult to perform even with the expansion of lexical knowledge. In addition, it is interesting to see that if a model performed better on upward inferences, it performed worse on downward inferences. We will investigate these results in detail below. \begin{table}[bt] \begin{center} \scalebox{0.82}{ \begin{tabular}{llrrrr} \hline Model&Train&Upward&Downward&Non&All\\ \hline \hline \multicolumn{2}{c}{Majority}&65.5&63.3&99.3&50.4\\ \hline BiMPM&SNLI&53.5&\textbf{57.6}&27.4&\textbf{54.6}\\ ESIM&SNLI&71.1&45.2&41.8&53.8\\ DeComp&SNLI&66.1&42.1&\textbf{64.4}&51.4\\ KIM&SNLI&78.8&30.3&53.1&48.0\\ BERT&SNLI&50.1&46.8&7.5&45.8\\ BERT&MNLI&\textbf{82.7}&22.8&52.7&44.7\\ \hline \end{tabular} } \caption{\label{tab:perform} Accuracies (\%) for different models and training datasets.} \end{center} \end{table} \subsection{Data augmentation for analysis} To explore whether the performance of models on monotonicity reasoning depends on the training set or the model themselves, we conducted further analysis performed by data augmentation with the automatically generated monotonicity dataset HELP~\cite{yanaka2019}. HELP contains 36K monotonicity inference examples (7,784 upward examples, 21,192 downward examples, and 1,105 non-monotone examples). The size of the HELP word vocabulary is 15K, and the overlap ratio of vocabulary between HELP and MED is 15.2\%. We trained BERT on MultiNLI only and on MultiNLI augmented with HELP, and compared their performance. Following \final{\citet{poliak-EtAl:2018:S18-2}}, we also checked the performance of a hypothesis-only model trained with each training set to test whether our test set contains undesired biases. \begin{table}[bt] \begin{center} \scalebox{0.80}{ \begin{tabular}{l|rrrr} \hline Training set&Upward&Downward&Non&All\\ \hline \hline MNLI&\textbf{82.7}&22.8&52.7&44.7\\ MNLI--Hyp&34.3&18.3&31.5&24.4\\ MNLI+HELP&76.0&\textbf{70.3}&\textbf{59.9}&\textbf{71.6}\\ MNLI+HELP--Hyp&61.3&30.5&34.9&41.1 \\ \hline \end{tabular} } \caption{\label{tab:eval1} Evaluation results on types of monotonicity reasoning. --Hyp: Hypothesis-only model.} \end{center} \end{table} \begin{figure*} \includegraphics[width=16cm, bb=0.000000 0.000000 8876.000000 2498.000000]{figure.jpg} \caption{\label{tab:fig1} Accuracy throughout training BERT (i) with only upward examples and (ii) with only downward examples. We checked the accuracy at sizes [50, 100, 200, 500, 1000, 2000, 5000] for each direction. (iii) Performance on different ratios of upward/downward training sets. The total size of the training sets was 5,000 examples.} \end{figure*} \subsubsection{Effects of data augmentation} Table~\ref{tab:eval1} shows that the performance of BERT with the hypothesis-only training set dropped around 10-40\% as compared with the one with the premise-hypothesis training set, even if we use the data augmentation technique. This indicates that the MED test set does not allow models to predict from hypotheses alone. Data augmentation by HELP improved the overall accuracy to 71.6\%, but there is still room for improvement. In addition, while adding HELP increased the accuracy on downward inferences, it slightly decreased accuracy on upward inferences. The size of downward examples in HELP is much larger than that of upward examples. This might improve accuracy on downward inferences, but might decrease accuracy on upward inferences. To investigate the relationship between accuracy on upward inferences and downward inferences, we checked the performance throughout training BERT with only upward and downward inference examples in HELP (Figure~\ref{tab:fig1} (i), (ii)). These two figures show that, as the size of the upward training set increased, BERT performed better on upward inferences but worse on downward inferences, and vice versa. Figure~\ref{tab:fig1} (iii) shows performance on a different ratio of upward and downward inference training sets. When downward inference examples constitute more than half of the training set, accuracies on upward and downward inferences were reversed. As the ratio of downward inferences increased, BERT performed much worse on upward inferences. This indicates that a training set in one direction (upward or downward entailing) of monotonicity might be harmful to models when learning the opposite direction of monotonicity. Previous work using HELP~\cite{yanaka2019} reported that the BERT trained with MultiNLI and HELP containing both upward and downward inferences improved accuracy on both directions of monotonicity. \final{MultiNLI rarely comes from downward inferences (see Section~\ref{sec:discuss}), and its size is large enough to be immune to the side-effects of downward inference examples in HELP.} This indicates that MultiNLI might act as a \textit{buffer} against side-effects of the monotonicity-driven data augmentation technique. \subsubsection{Linguistics-oriented versus human-oriented} Table~\ref{tab:eval4} shows the evaluation results by genre. This result shows that inference problems collected from linguistics publications are more challenging than crowdsourced inference problems, even if we add HELP to training sets. As shown in Figure~\ref{tab:fig1}, the change in performance on problems from linguistics publications is milder than that on problems from crowdsourcing. This result also indicates the difficulty of problems from linguistics publications. Regarding non-monotone problems collected via crowdsourcing, there are very few non-monotone problems, so accuracy is 100\%. Adding non-monotone problems to our test set is left for future work. \begin{table}[bt] \begin{center} \scalebox{0.75}{ \begin{tabular}{lr|rrr} \hline Genre&&$-$HELP&$+$HELP&$\triangle$\\ \hline \hline \multirow{4}{*}{Crowd}&Up&87.1&83.6&$-$3.5\\ &Down&21.2&70.3&$+$49.1\\ &Non&100.0&100.0&$\pm$0.0\\ \cline{2-5} &All&40.9&74.3&$+$33.4\\ \hline \multirow{4}{*}{Paper}&Up&74.5&60.8&$-$13.7\\ &Down&33.8&69.5&$+$35.7\\ &Non&52.4&59.7&$+$7.3\\ \cline{2-5} &All&56.6&63.3&$+$6.7\\ \hline \end{tabular} } \caption{\label{tab:eval4} Evaluation results by genre. Paper: problems collected from linguistics publications, Crowd: problems via crowdsourcing.} \end{center} \end{table} \subsubsection{Linguistic phenomena} Table~\ref{tab:eval3new} shows the evaluation results by type of linguistic phenomenon. While accuracy on problems involving NPIs and conditionals was improved on both upward and downward inferences, accuracy on problems involving conjunction and disjunction was improved on only one direction. In addition, it is interesting to see that the change in accuracy on conjunction was opposite to that on disjunction. Downward inference examples involving disjunction are similar to upward inference ones; that is, inferences from a sentence to a shorter sentence are valid (e.g., \textit{Not many campers have had a sunburn or caught a cold} $\Rightarrow$ \textit{Not many campers have caught a cold}). Thus, these results were also caused by addition of downward inference examples. Also, accuracy on problems annotated with \textit{reverse} tags was apparently better without HELP because all examples are upward inferences embedded in a downward environment twice. Table~\ref{tab:eval3new} also shows that accuracy on conditionals was better on upward inferences than that on downward inferences. This indicates that BERT might fail to capture the monotonicity property that conditionals create a downward entailing context in their scope while they create an upward entailing context out of their scope. Regarding lexical knowledge, the data augmentation technique improved the performance much better on downward inferences which do not require lexical knowledge. However, among the 394 problems for which all models provided wrong answers, 244 problems are non-lexical inference problems. This indicates that some non-lexical inference problems are more difficult than lexical inference problems, though accuracy on non-lexical inference problems was better than that on lexical inference problems. \begin{table}[bt] \begin{center} \scalebox{0.75}{ \begin{tabular}{llr|rrr} \hline Tag&&&$-$HELP&$+$HELP&$\triangle$\\ \hline \hline \multirow{7}{*}{Up}&Lexical&(743)&81.0&70.8&$-$10.2\\ &non-Lexical&(1,077)&84.1&79.6&$-$4.5\\ &NPIs&(64)&20.3&35.9&$+$15.6\\ &Conditionals&(29)&51.7&62.1&$+$9.4\\ &Conjunction&(175)&94.3&88.0&$-$6.3\\ &Disjunction&(96)&4.2&32.3&$+$28.1\\ &Reverse&(240)&74.2&28.7&$-$45.5\\ \hline \multirow{6}{*}{Down}&Lexical&(477)&46.1&64.6&$+$18.5\\ &non-Lexical&(2,793)&18.8&71.2&$+$52.4\\ &NPIs&(266)&44.0&60.2&$+$16.2\\ &Conditionals&(120)&15.8&20.0&$+$4.2\\ &Conjunction&(106)&24.5&40.6&$+$16.1\\ &Disjunction&(138)&80.4&40.6&$-$39.8\\ \hline \multirow{4}{*}{Non}&Lexical&(182)&58.2&64.3&$+$6.1\\ &non-Lexical&(110)&43.6&52.7&$+$9.1\\ &NPIs&(8)&0.0&0.0&$\pm$0.0\\ &Disjunction&(20)&10.0&15.0&$+$5.0\\ \hline \end{tabular} } \caption{\label{tab:eval3new} Evaluation results by linguistic phenomenon type. (non-)Lexical: problems that (do not) require lexical relations. Numbers in parentheses are numbers of problems.} \end{center} \end{table} \subsection{Discussion} \label{sec:discuss} One of our findings is that there is a type of downward inferences to which every model fails to provide correct answers. One such example is concerned with the contrast between \textit{few} and \textit{a few}. Among 394 problems for which all models provided wrong answers, 148 downward inference problems were problems involving the downward monotonicity operator \textit{few} such as in the following example: {\footnotesize \begin{exe} \ex \label{ex:9} \begin{xlist} \exi{$P$:} \textit{Few of the books had typical or marginal readers} \exi{$H$:} \textit{Few of the books had some typical readers} \end{xlist} \end{exe} } We transformed these downward inference problems to upward inference problems in two ways: (i) by replacing the downward operator \textit{few} with the upward operator \textit{a few}, and (ii) by removing the downward operator \textit{few}. We tested BERT using these transformed test sets. The results showed that BERT predicted the same answers for the transformed test sets. This suggests that BERT does not understand the difference between the downward operator \textit{few} and the upward operator \textit{a few}. The results of crowdsourcing tasks in Section 3.1.3 showed that some downward inferences can naturally be performed in human reasoning. However, we also found that the MultiNLI training set~\cite{DBLP:journals/corr/WilliamsNB17}, which is one of the dataset created from naturally-occurring texts, contains only 77 downward inference problems, including the following one.\footnote{ The MultiNLI training set has 1,700 inference problems where the downward entailing operators \textit{no} and \textit{never} occur in both the premise and the hypothesis, but most of them are not an instance of downward inferences.} {\footnotesize \begin{exe} \ex \label{ex:10} \begin{xlist} \exi{$P$:} \textit{No racin' on the Range} \exi{$H$:} \textit{No horse racing is allowed on the Range} \end{xlist} \end{exe} } \noindent One possible reason why there are few downward inferences is that certain pragmatic factors can block people to draw a downward inference. For instance, in the case of the inference problem in (\ref{ex:11}), unless the added disjunct in $H$, i.e., \textit{a small cat with green eyes}, is salient in the context, it would be difficult to draw the conclusion $H$ from the premise $P$. {\footnotesize \begin{exe} \ex \label{ex:11} \begin{xlist} \exi{$P$:} \textit{I saw a dog} \exi{$H$:} \textit{I saw a dog or a small cat with green eyes} \end{xlist} \end{exe} } \noindent Such pragmatic factors would be one of the reasons why it is difficult to obtain downward inferences in naturally occurring texts. \section{Conclusion} \label{sec:conc} We introduced a large monotonicity entailment dataset, called MED. To illustrate the usefulness of MED, we tested state-of-the-art NLI models, and found that performance on the new test set was substantially worse for all state-of-the-art NLI models. In addition, the accuracy on downward inferences was inversely proportional to the one on upward inferences. An experiment with the data augmentation technique showed that accuracy on upward and downward inferences depends on the proportion of upward and downward inferences in the training set. This indicates that current neural models might have limitations on their generalization ability in monotonicity reasoning. We hope that the MED will be valuable for future research on more advanced models that are capable of monotonicity reasoning in a proper way. \section*{Acknowledgement} This work was partially supported by JST AIP- PRISM Grant Number JPMJCR18Y1, Japan, and JSPS KAKENHI Grant Number JP18H03284, Japan. We thank our three anonymous reviewers for helpful suggestions. We are also grateful to Koki Washio, Masashi Yoshikawa, and Thomas McLachlan for helpful discussion. \bibliographystyle{acl_natbib}
{'timestamp': '2019-06-28T02:13:28', 'yymm': '1906', 'arxiv_id': '1906.06448', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06448'}
arxiv
\section{Introduction} There has been much recent work on learning deep generative models of discrete data, in both the case where all the modeled variables are observed~\citep[\textit{inter alia}]{Mikolov2011,pixelrnn}, and in the case where they are not~\citep[\textit{inter alia}]{Mnih2014,Mnih2016}. Most of this recent work has focused on directed graphical models, and when approximate inference is necessary, on variational inference. Here we consider instead undirected models, that is, Markov Random Fields (MRFs), which we take to be interesting for at least two reasons: first, some data are more naturally modeled using MRFs~\citep{koller2009probabilistic}. Second, unlike their directed counterparts, many intractable MRFs of interest admit a learning objective which both approximates the log marginal likelihood, and which can be computed exactly (i.e., without sampling). In particular, log marginal likelihood approximations that make use of the Bethe Free Energy (BFE)~\citep{bethe1935statistical} can be computed in time that effectively scales linearly with the number of factors in the MRF, provided that the factors are of low degree. Indeed, loopy belief propagation (LBP)~\citep{mceliece1998turbo}, the classic approach to approximate inference in MRFs, can be viewed as minimizing the BFE~\citep{yedidia2001generalized}. However, while often quite effective, LBP is also an iterative message-passing algorithm, which can significantly slow down the training of deep generative models, which rely on parallel GPU computation to train quickly. To address these shortcomings of LBP in the context of training deep models, we propose to train MRFs by minimizing the BFE directly during learning, without message passing, using inference networks trained to output approximate minimizers. This scheme gives rise to a saddle-point learning problem, and we show that learning in this way allows for quickly training MRFs that are competitive with or outperform those trained with LBP. We also consider the setting where the discrete latent variable model to be learned admits both directed and undirected variants. For example, we might be interested in learning an HMM-like model, but we are free to parameterize transition factors in a variety of ways, including such that all the transition factors are unnormalized and of low-degree (see Figure~\ref{fig:mrfs}). Such a parameterization makes BFE minimization particularly convenient, and indeed we show that learning such an undirected model with BFE minimization allows for outperforming the directed variant learned with amortized variational inference in terms of both held out log likelihood and speed. Thus, when possible, it may in fact be advantageous to consider transforming a directed model into an undirected variant, and learning it with BFE minimization. \section{Background} \label{sec:background} Let $\mathcal{G} = (\mathcal{V} \cup \mathcal{F}, \mathcal{E})$ be a factor graph~\citep{frey1997factor,kschischang2001factor}, with $\mathcal{V}$ the set of variable nodes, $\mathcal{F}$ the set of factor nodes, and $\mathcal{E}$ the set of undirected edges between elements of $\mathcal{V}$ and elements of $\mathcal{F}$; see Figure~\ref{fig:mrfs} for examples. We will refer collectively to variables in $\mathcal{V}$ that are always observed as $\mathbf{x}$, and to variables which are never observed as $\mathbf{z}$. We will take all variables to be discrete. In a Markov Random Field (MRF), the joint distribution over $\mathbf{x}$ and $\mathbf{z}$ factorizes as $P(\mathbf{x}, \mathbf{z} ; \boldsymbol{\theta}) = \frac{1}{Z(\btheta)} \prod_{\alpha} \Psi_{\alpha}(\mathbf{x}_{\alpha}, \mathbf{z}_{\alpha} ; \boldsymbol{\theta}),$ where the notation $\mathbf{x}_{\alpha}$ and $\mathbf{z}_{\alpha}$ is used to denote the (possibly empty) subvectors of $\mathbf{x}$ and $\mathbf{z}$ that participate in factor $\Psi_\alpha$, the factors $\Psi_{\alpha}$ are assumed to always be positive and are parameterized by $\boldsymbol{\theta}$, and where $Z(\btheta)$ is the partition function: $Z(\btheta) = \sum_{\mathbf{x}'} \sum_{\mathbf{z}'} \prod_{\alpha} \Psi_{\alpha}(\mathbf{x}'_{\alpha}, \mathbf{z}'_{\alpha} ; \boldsymbol{\theta})$. In order to simplify the exposition we will assume all factors are either unary (functions of a single variable in $\mathcal{V}$) or pairwise (functions of two variables in $\mathcal{V}$), and we lose no generality in doing so~\citep{yedidia2003understanding,wainwright2008graphical}. Thus, if a node $v_1 \in \mathcal{V}$ may take on one of $K_1$ discrete values, we view a unary factor $\Psi_{\alpha}(\mathbf{x}_{\alpha}, \mathbf{z}_{\alpha} ; \boldsymbol{\theta}) = \Psi_{\alpha}(v_1 ; \boldsymbol{\theta})$ as a function $\Psi_{\alpha}: \{1, \ldots, K_1\} \rightarrow \mathbb{R}_{+}^{K_1}$. Similarly, if nodes $v_1$ and $v_2$ may take on $K_1$ and $K_2$ discrete values respectively, we view a binary factor $\Psi_{\beta}(\mathbf{x}_{\beta}, \mathbf{z}_{\beta} ; \boldsymbol{\theta}) = \Psi_{\beta}(v_1, v_2 ; \boldsymbol{\theta})$ as a function $\Psi_{\beta}: \{1, \ldots, K_1\} \times \{1, \ldots, K_2\} \rightarrow \mathbb{R}_{+}^{K_1 \cdot K_2}$. Going forward, we will use the notation $|\Psi_{\alpha}|$ to refer to the length of the vector output by a factor $\Psi_{\alpha}.$ In this work we consider both scalar and neural parameterizations of factors. When the model involves unobserved variables $\mathbf{z}$, we will also make use of the ``clamped'' partition function $Z(\boldx, \btheta) = \sum_{\mathbf{z}'} \prod_{\alpha} \Psi_{\alpha}(\mathbf{x}_{\alpha}, \mathbf{z}'_{\alpha} ; \boldsymbol{\theta})$, where $\mathbf{x}$ is ``clamped'' to a particular value. The clamped partition function corresponds to the unnormalized marginal probability of $\mathbf{x}$, the partition function of $P(\mathbf{z} \,|\, \mathbf{x} ; \boldsymbol{\theta})$. \begin{figure}[t] \begin{center} \begin{subfigure}[b]{0.49\textwidth} \centering \includegraphics[width=0.55\linewidth]{uhmm.pdf} \caption{} \end{subfigure} \begin{subfigure}[b]{0.49\textwidth} \centering \includegraphics[width=0.5\linewidth]{upwhmm.pdf} \caption{} \end{subfigure} \end{center} \caption{Factor graphs of (a) a full 3rd order HMM, and (b) a 3rd order HMM-like model with only pairwise factors.} \label{fig:mrfs} \end{figure} \subsection{The Bethe Free Energy} Because calculation of either $Z(\btheta)$ or $Z(\boldx, \btheta)$ may be intractable, maximum likelihood learning of MRFs often makes use of approximations to these quantities. One such approximation makes use of the Bethe free energy (BFE), due to~\citet{bethe1935statistical} and popularized by \citet{yedidia2001generalized}, which is defined in terms of the factor and node marginals of the corresponding factor graph. In particular, let $\boldsymbol{\tau}_{\alpha}(\mathbf{x}_{\alpha}, \mathbf{z}_{\alpha}) \in [0, 1]$ be the marginal probability of the event $\mathbf{x}_{\alpha}$ and $\mathbf{z}_{\alpha}$, which are again the (possibly empty) subvectors associated with factor $\Psi_\alpha$. We will refer to the vector consisting of the concatenation of \textit{all} possible marginals for each factor in $\mathcal{G}$ as $\boldsymbol{\tau} \in [0,1]^{M(\mathcal{G})}$, where $M(\mathcal{G}) = \sum_{\alpha \in \mathcal{F}} |\Psi_{\alpha}|$, the total number of values output by all factors associated with the graph. As a concrete example, consider the 10 factors in Figure~\ref{fig:mrfs} (b): if each variable can take on only two possible values, then since each factor is pairwise (i.e., considers only two variables), there are $2^2$ possible settings for each factor, and thus $2^2$ corresponding marginals. In total, we then have $10 \times 4$ marginals and so $M(\mathcal{G})=40$ and $\boldsymbol{\tau} \in [0,1]^{40}$. Following \citet{yedidia2003understanding}, the BFE is then defined as \begin{align} \label{eq:bethe} F(\btau, \btheta) &= \sum_{\alpha} \sum_{\mathbf{x}'_{\alpha}, \mathbf{z}'_{\alpha}} \boldsymbol{\tau}_{\alpha}(\mathbf{x}'_{\alpha}, \mathbf{z}'_{\alpha}) \log \frac{\boldsymbol{\tau}_{\alpha}(\mathbf{x}'_{\alpha}, \mathbf{z}'_{\alpha})}{\Psi_{\alpha}(\mathbf{x}'_{\alpha}, \mathbf{z}'_{\alpha})} - \sum_{v \in \mathcal{V}} (|\mathcal{\nu}(v)|-1) \sum_{v'} \boldsymbol{\tau}_v(v') \log \boldsymbol{\tau}_v(v'), \end{align} where $\mathcal{\nu}(v)$ gives the set of factor-neighbors node $v$ has in the factor graph, and $\boldsymbol{\tau}_v(v')$ is the marginal probability of node $v$ taking on the value $v'$. Importantly, in the case of a distribution $P_{\boldsymbol{\theta}}$ representable as a tree-structured model, we have $\min_{\boldsymbol{\tau}} F(\btau, \btheta) = -\log Z(\btheta)$, since~\eqref{eq:bethe} is precisely $\KL[Q||P_{\boldsymbol{\theta}}] - \log Z(\btheta)$, where $Q$ is another tree representable distribution with marginals $\boldsymbol{\tau}$~\citep{heskes2003stable,wainwright2008graphical,gormley2014structured}. In the case where $P_{\boldsymbol{\theta}}$ is \textit{not} tree-structured (i.e., it has a loopy factor graph), we no longer have a KL divergence, and $\min_{\boldsymbol{\tau}} F(\btau, \btheta)$ will in general give only an approximation, but not a bound, on the partition function: $\min_{\boldsymbol{\tau}} F(\btau, \btheta) \approx -\log Z(\btheta)$~\citep{wainwright2008graphical,willsky2008loop,weller2014approximating,weller2014understanding}. Despite the fact that minimizing the BFE only provides an approximation to the log partition function, it is attractive for our purposes because while the BFE is exponential in the \textit{degree} of each factor (since it sums over all assignments), it is only linear in the number of factors. Thus, evaluating~\eqref{eq:bethe} for a factor graph with a large number of small-degree (e.g., pairwise) factors remains tractable. Moreover, while this restriction to models with low-degree factors severely limits the expressiveness of \textit{directed} graphical models, it does not limit the expressiveness of MRFs in the same way, since MRFs are free to have arbitrary pairwise dependence, as in Figure~\ref{fig:mrfs} (b). Indeed, the idea of establishing complex dependencies through many pairwise factors in an MRF is what underlies product-of-experts style modeling~\citep{hinton2002training}. \vspace{-2mm} \subsection{Minimizing the Bethe Free Energy}\vspace{-2mm} \label{sec:historically} Historically, the BFE has been minimized during learning with loopy belief propagation (LBP)~\citep{pearl1986fusion,mceliece1998turbo}. Indeed, \citet{yedidia2001generalized} show that the fixed points found by LBP correspond to stationary points of the optimization problem $\min_{\boldsymbol{\tau} \in \mathcal{C}} F(\btau, \btheta)$, where $\mathcal{C}$ contains vectors of length $M(\mathcal{G})$, and in particular the concatenation of ``pseudo-marginal'' vectors $\boldsymbol{\tau}_{\alpha}(\mathbf{x}_{\alpha}, \mathbf{z}_{\alpha})$ for each factor, subject to each pseudo-marginal vector being positive and summing to 1, and the pseudo-marginal vectors being locally consistent with each other. Local consistency requires that the pseudo-marginal vectors associated with any two factors $\alpha, \beta$ sharing a variable $v$ agree: $\sum_{\mathbf{x}'_{\alpha}, \mathbf{z}'_{\alpha} \setminus v} \boldsymbol{\tau}_{\alpha}(\mathbf{x}'_{\alpha}, \mathbf{z}'_{\alpha}) = \sum_{\mathbf{x}'_{\beta}, \mathbf{z}'_{\beta} \setminus v} \boldsymbol{\tau}_{\beta}(\mathbf{x}'_{\beta}, \mathbf{z}'_{\beta})$; see also \citet{heskes2003stable}. Note that even if $\boldsymbol{\tau}$ satisfies these conditions, for loopy models it may still not correspond to the marginals of any distribution~\citep{wainwright2008graphical}. While LBP is quite effective in practice~\citep{mceliece1998turbo,murphy1999loopy,yedidia2003understanding,meshi2009convexifying}, it does not integrate well with the current GPU-intensive paradigm for training deep generative models, since it is a typically sequential message passing algorithm (though see~\citet{gonzalez2009residual}), which may require a variable number of iterations and a particular message passing scheduling to converge~\citep{elidan2012residual,gormley2014structured}. We therefore propose to drop the message passing metaphor, and instead directly minimize the constrained BFE during learning using inference networks~\citep{srikumar2012amortizing,Kingma2014,johnson2016perceptual,tu2018learning}, which are trained to output approximate minimizers. This style of training gives rise to a saddle-point objective for learning, detailed in the next section. \vspace{-2mm} \section{Learning with Amortized Bethe Free Energy Minimization}\vspace{-2mm} Consider learning an MRF consisting of only observed variables $\mathbf{x}$ via maximum likelihood, which requires minimizing $- \log P(\mathbf{x} ; \boldsymbol{\theta}) = - \log \tilde{P}(\mathbf{x} ; \boldsymbol{\theta}) + \log Z(\btheta)$, where $\log \tilde{P}(\mathbf{x} ; \boldsymbol{\theta}) = \sum_{\alpha} \log \Psi_{\alpha}(\mathbf{x}_{\alpha} ; \boldsymbol{\theta})$. Using the Bethe approximation to $\log Z(\btheta)$ from the previous section, we then arrive at the objective: \begin{align} \label{eq:loss} \ell_F(\boldsymbol{\theta}) &= - \log \tilde{P}(\mathbf{x} ; \boldsymbol{\theta}) - \min_{\boldsymbol{\tau} \in \mathcal{C}} F(\boldsymbol{\tau}) \approx -\log \tilde{P}(\mathbf{x} ; \boldsymbol{\theta}) + \log Z(\btheta), \end{align} and thus the saddle-point learning problem: \begin{align} \label{eq:saddle} \min_{\boldsymbol{\theta}} \ell_F(\boldsymbol{\theta}) &= \min_{\boldsymbol{\theta}} \left[ -\log \tilde{P}(\mathbf{x} ; \boldsymbol{\theta}) - \min_{\boldsymbol{\tau} \in \mathcal{C}} F(\btau, \btheta) \right] = \min_{\boldsymbol{\theta}} \max_{\boldsymbol{\tau} \in \mathcal{C}} \left[ -\log \tilde{P}(\mathbf{x} ; \boldsymbol{\theta}) - F(\btau, \btheta) \right]. \end{align} While $\ell_F$ is neither an upper nor lower bound on $- \log P(\mathbf{x} ; \boldsymbol{\theta})$, it is an approximation, and indeed its gradients are precisely those that arise from approximating the true gradient of $- \log P(\mathbf{x} ; \boldsymbol{\theta})$ by replacing the true factor marginals which appear in the gradient with approximate ones; see~\citet{sutton2012introduction}. In the case where our MRF contains unobserved variables $\mathbf{z}$, we wish to learn by minimizing $-\log Z(\boldx, \btheta) + \log Z(\btheta)$. Here we can additionally approximate the clamped partition function $-\log Z(\boldx, \btheta)$ using the BFE. In particular, we have $\min_{\boldsymbol{\tau}_{\mathbf{x}} \in \mathcal{C}_{\mathbf{x}}} F(\btau_{\boldx}, \btheta) \approx -\log Z(\boldx, \btheta)$, where $\boldsymbol{\tau}_{\mathbf{x}}$ contains the marginals of the MRF with its observed variables clamped to $\mathbf{x}$ (which is equivalent to replacing these variables with unary factors, and so $\boldsymbol{\tau}_{\mathbf{x}}$ will in general be smaller than $\boldsymbol{\tau}$). We thus arrive at the following saddle point learning problem for MRFs with latent variables: \begin{align} \label{eq:saddlelatent} \min_{\boldsymbol{\theta}} \ell_{F,\mathbf{z}}(\boldsymbol{\theta}) &= \min_{\boldsymbol{\theta}} \left[ \min_{\boldsymbol{\tau}_{\mathbf{x}} \in \mathcal{C}_{\mathbf{x}}} F(\btau_{\boldx}, \btheta) - \min_{\boldsymbol{\tau} \in \mathcal{C}} F(\btau, \btheta) \right] = \min_{\boldsymbol{\theta}, \boldsymbol{\tau}_{\mathbf{x}}} \max_{\boldsymbol{\tau} \in \mathcal{C}} \left[ F(\btau_{\boldx}, \btheta) - F(\btau, \btheta) \right]. \end{align} \vspace{-2mm} \subsection{Inference Networks} \vspace{-2mm} Optimizing $\ell_F$ and $\ell_{F, \mathbf{z}}$ require tackling a constrained, saddle-point optimization problem. While we could in principle optimize over $\boldsymbol{\tau}$ or $\boldsymbol{\tau}_{\mathbf{x}}$ directly, we found this optimization to be difficult, and we instead follow recent work~\citep{srikumar2012amortizing,Kingma2014,johnson2016perceptual,tu2018learning} in replacing optimization over the variables of interest with optimization over the parameters $\boldsymbol{\phi}$ of an inference network $f(\cdot ; \boldsymbol{\phi})$ outputting the variables of interest. Thus, an inference network consumes a graph $\mathcal{G}$ and predicts a pseudo-marginal vector, as we make more precise below. We also note that because our inference networks consume graphs they are similar to graph neural networks~\citep[\textit{inter alia}]{scarselli2009graph,li2015gated,kipf2016semi,yoon2018inference}. However, because we are interested in being able to quickly learn deep MRFs, our inference networks do not do any message-passing style updates, and they are run once either over a symbolic representation of the graph, or (in the case of predicting marginals in the ``clamped'' case) over a symbolic representation of the graph together with the observed variables. We provide further details of our inference network parameterizations in Section~\ref{sec:experiments} and in the Supplementary Material. \paragraph{Handling Constraints on Predicted Marginals} The predicted pseudo-marginals output by our inference network $f$ must respect the positivity, normalization, and local consistency constraints described in Section~\ref{sec:historically}. Since the normalization and local consistency constraints are linear equality constraints, it is possible to optimize only in the subspace defined by them. However, such an approach requires the explicit calculation of a basis for the null space of the constraint matrix, which becomes unwieldy as the graph gets large. We accordingly adopt the much simpler and more scalable approach of handling the positivity and normalization constraints by optimizing over the ``softmax basis'' (i.e., over logits), and we handle the local consistency constraints by simply adding a term to our objective that penalizes this constraint violation~\citep{courant1943variational,nocedal2006numerical}. In particular, let $f(\mathcal{G}, \alpha, \mathbf{x}_{\alpha}, \mathbf{z}_{\alpha} ; \boldsymbol{\phi}) \in \mathbb{R}^{K_1 \cdot K_2}$ be scores given by an inference network to all configurations of the variables associated with factor $\alpha$. We then define the predicted factor marginals to be \begin{align} \label{eq:predfac} \boldsymbol{\tau}_{\alpha}(\mathbf{x}_{\alpha}, \mathbf{z}_{\alpha} ; \boldsymbol{\phi}) = \softmax(f(\mathcal{G}, \alpha, \mathbf{x}_{\alpha}, \mathbf{z}_{\alpha} ; \boldsymbol{\phi})). \end{align} We obtain predicted node marginals for each node $v$ by averaging all the associated factor-level marginals: \begin{align} \label{eq:prednode} \boldsymbol{\tau}_v(v ; \boldsymbol{\phi}) = \frac{1}{|\mathcal{\nu}(v)|} \sum_{\alpha \in \mathcal{\nu}(v)} \sum_{\mathbf{x}'_{\alpha}, \mathbf{z}'_{\alpha} \setminus v} \boldsymbol{\tau}_{\alpha}(\mathbf{x}'_{\alpha}, \mathbf{z}'_{\alpha} ; \boldsymbol{\phi}). \end{align} We obtain our final learning objective by adding a term penalizing the distance between the marginal associated with node $v$ according to a \textit{particular} factor, and $\boldsymbol{\tau}_v(v ; \boldsymbol{\phi})$. Thus, the optimization problem~\eqref{eq:saddle} becomes \begin{align} \label{eq:amortsaddle} \min_{\boldsymbol{\theta}} \max_{\boldsymbol{\phi}} \Big[ {-}\log \tilde{P}(\mathbf{x} ; \boldsymbol{\theta}) - F(\boldsymbol{\tau}(\boldsymbol{\phi}), \boldsymbol{\theta}) - \frac{\lambda}{|\mathcal{F}|} \sum_{v \in \mathcal{V}} \sum_{\alpha \in \mathcal{\nu}(v)} d \Big(\boldsymbol{\tau}_v(v; \boldsymbol{\phi}), \sum_{\mathbf{x}'_{\alpha}, \mathbf{z}'_{\alpha} \setminus v} \boldsymbol{\tau}_{\alpha}(\mathbf{x}'_{\alpha}, \mathbf{z}'_{\alpha} ; \boldsymbol{\phi}) \Big) \Big], \end{align} where $d(\cdot, \cdot)$ is a non-negative distance or divergence calculated between the marginals (typically $L_2$ distance in experiments), $\lambda$ is a tuning parameter, and the notation $\boldsymbol{\tau}(\boldsymbol{\phi})$ refers to the entire vector of concatenated predicted marginals. We note that the number of penalty terms in~\eqref{eq:amortsaddle} scales with $|\mathcal{F}|$, since we penalize agreement with node marginals; an alternative objective that penalizes agreement between factor marginals is possible, but would scale with $|\mathcal{F}|^2$, which is likely too expensive for large models. Finally, we note that we can obtain an analogous objective for the latent variable saddle-point problem~\eqref{eq:saddlelatent} by introducing an additional inference network $f_{\mathbf{x}}(\mathcal{G}, \alpha, \mathbf{x}, \mathbf{x}_{\alpha}, \mathbf{z}_{\alpha} ; \boldsymbol{\phi}_{\mathbf{x}})$ and adding an additional set of penalty terms. \vspace{-2mm} \subsection{Learning} \vspace{-2mm} We learn by alternating $I_1$ steps of gradient ascent on \eqref{eq:amortsaddle} with respect to $\boldsymbol{\phi}$ with one step of gradient descent on \eqref{eq:amortsaddle} with respect to $\boldsymbol{\theta}$. When the MRF contains latent variables, we take $I_2$ gradient descent steps to minimize the objective with respect to $\boldsymbol{\phi}_{\mathbf{x}}$ before updating $\boldsymbol{\theta}$. We show pseudo-code describing this procedure for a single minibatch in Algorithm~\ref{alg:alg}. \begin{algorithm}[t!] \small \begin{algorithmic} \For{$i=1, \ldots, I_{1}$} \State{Obtain $\boldsymbol{\tau}(\boldsymbol{\phi})$ from $f(\cdot ; \boldsymbol{\phi})$ using Equations \eqref{eq:predfac} and \eqref{eq:prednode}} \State{$\boldsymbol{\phi} \gets \boldsymbol{\phi} + \nabla_{\boldsymbol{\phi}}[ -F(\boldsymbol{\tau}(\boldsymbol{\phi}), \boldsymbol{\theta}) - \frac{\lambda}{|\mathcal{F}|} \sum_{v \in \mathcal{V}} \sum_{\alpha \in \mathcal{\nu}(v)} d (\boldsymbol{\tau}_v(v; \boldsymbol{\phi}), \sum_{\mathbf{x}'_{\alpha}, \mathbf{z}'_{\alpha} \setminus v} \boldsymbol{\tau}_{\alpha}(\mathbf{x}'_{\alpha}, \mathbf{z}'_{\alpha}; \boldsymbol{\phi}))]$} \EndFor \If{there are latents} \For{$i=1, \ldots, I_{2}$} \State{Obtain $\boldsymbol{\tau}_{\mathbf{x}}(\boldsymbol{\phi}_{\mathbf{x}})$ from $f_{\mathbf{x}}(\cdot ; \boldsymbol{\phi}_{\mathbf{x}})$ using Equations \eqref{eq:predfac} and \eqref{eq:prednode}} \State{$\boldsymbol{\phi}_{\mathbf{x}} \gets \boldsymbol{\phi}_{\mathbf{x}} - \nabla_{\boldsymbol{\phi}_{\mathbf{x}}}[F(\boldsymbol{\tau}_{\mathbf{x}}(\boldsymbol{\phi}_{\mathbf{x}}), \boldsymbol{\theta}) + \frac{\lambda}{|\mathcal{F}|} \sum_{v \in \mathbf{z}} \sum_{\alpha \in \mathcal{\nu}(v)} d (\boldsymbol{\tau}_{\mathbf{x}}(v; \boldsymbol{\phi}_{\mathbf{x}}), \sum_{\mathbf{x}'_{\alpha}, \mathbf{z}'_{\alpha} \setminus v} \boldsymbol{\tau}_{\mathbf{x}, \alpha}(\mathbf{x}'_{\alpha}, \mathbf{z}'_{\alpha}; \boldsymbol{\phi}_{\mathbf{x}}))]$} \EndFor \State{$\boldsymbol{\theta} \gets \boldsymbol{\theta} - \nabla_{\boldsymbol{\theta}}[F(\boldsymbol{\tau}_{\mathbf{x}}(\boldsymbol{\phi}_{\mathbf{x}}), \boldsymbol{\theta}) - F(\boldsymbol{\tau}(\boldsymbol{\phi}), \boldsymbol{\theta}) ]$} \Else \State{$\boldsymbol{\theta} \gets \boldsymbol{\theta} - \nabla_{\boldsymbol{\theta}}[- \log \tilde{P}(\mathbf{x} ; \boldsymbol{\theta}) - F(\boldsymbol{\tau}(\boldsymbol{\phi}), \boldsymbol{\theta}) ]$} \EndIf \end{algorithmic} \caption{Saddle-point MRF Learning} \label{alg:alg} \end{algorithm} Before moving on to experiments we emphasize two of the attractive features of the learning scheme described in \eqref{eq:amortsaddle} and Algorithm~\ref{alg:alg}, which are verified empirically in the next section. First, because there is no message passing and because minimization with respect to the $\boldsymbol{\tau}$ and $\boldsymbol{\tau}_{\mathbf{x}}$ pseudo-marginals is amortized over the training set using inference networks, we are often able to reap the benefits of training MRFs with LBP but do so much more quickly. Second, we emphasize that the objective \eqref{eq:amortsaddle} and its gradients can be calculated exactly, which stands in contrast to much recent work in variational inference for both directed models~\citep{Rezende2015,Kingma2014} and undirected models~\citep{kuleshov2017neural}, where the ELBO and its gradients must be approximated with sampling. As the variance of ELBO gradient estimators is known to be an issue when learning models with discrete latent variables~\citep{Mnih2014}, if it is possible to develop undirected analogs of the models of interest it may be beneficial to do so and then learn these models with the exact $\ell_F$ or $\ell_{F,\mathbf{z}}$ objective, rather than approximating the ELBO. We consider one such case in the next section. \section{Experiments} \label{sec:experiments} Our experiments are designed to verify that amortizing BFE minimization is an effective way of performing inference, that it allows for learning models that generalize, and that we can do this quickly. We accordingly consider learning and performing inference on three different kinds of popular MRFs, comparing amortized BFE minimization with standard baselines. We provide additional experimental details in the Supplementary Material, and code for duplicating experiments is available at \url{https://github.com/swiseman/bethe-min}. \subsection{Ising Models} We first study our approach as applied to Ising models. An $n\times n$ grid Ising model gives rise to a distribution over binary vectors $\mathbf{x} \in \{-1, 1\}^{n^2}$ via the following parameterization: $P(\mathbf{x} ; \boldsymbol{\theta}) = \frac{1}{Z(\boldsymbol{\theta})}\exp (\sum_{(i,j) \in \mathcal{E}}J_{ij}x_{i} x_{j} + \sum_{i \in \mathcal{V}} h_i x_i)$, where $J_{ij}$ are the pairwise log potentials and $h_i$ are the node log potentials. The generative model parameters are thus given by $\boldsymbol{\theta} = \{J_{ij}\}_{(i,j) \in \mathcal{E}} \cup \{h_i\}_{i \in \mathcal{V}}$. While Ising models are conceptually simple, they are in fact quite general since any binary pairwise MRF can be transformed into an equivalent Ising model \cite{sontag2007cutting}. In these experiments, we are interested in quantifying how well we can approximate the true marginal distributions with approximate marginal distributions obtained from the inference network. We therefore experiment with model sizes for which exact inference is reasonably fast on modern hardware (up to $15 \times 15$).\footnote{The calculation of the partition function in grid Ising models is exponential in $n$, but it is possible to reduce the running time from $O(2^{n^2})$ to $O(2^n)$ with dynamic programming (i.e., variable elimination).} Our inference network associates a learnable embedding vector $\mathbf{e}_i$ with each node and applies a single Transformer layer \cite{vaswani2017attention} to obtain a new node representation $\mathbf{h}_i$, with $[\mathbf{h}_{1}, \dots, \mathbf{h}_{n^2}] = \transformer([\mathbf{e}_1, \dots, \mathbf{e}_{n^2}])$. The distribution over $x_i, x_j$ for $(i, j) \in \mathcal{E}$ is given by concatenating $\mathbf{h}_{i}, \mathbf{h}_{j}$ and applying an affine layer followed by a softmax: $\boldsymbol{\tau}_{ij}(x_i, x_j ; \boldsymbol{\phi}) = \softmax(\mathbf{W} [\mathbf{h}_i ; \mathbf{h}_j] + \mathbf{b})$, where the softmax is over the four possible events (i.e., $\mathbf{b} \in \mathbb{R}^4$) The parameters of the inference network $\boldsymbol{\phi}$ are given by the node embeddings and the parameters of the Transformer/affine layers. The node marginals $\boldsymbol{\tau}_i(x_i ; \boldsymbol{\phi})$ then are obtained from averaging the pairwise factor marginals (Eq~\eqref{eq:prednode}).\footnote{As there are no latent variables in these experiments, inference via the inference network is not amortized in the traditional sense (i.e., across different data points as in Eq~\eqref{eq:saddlelatent}) since it does not condition on $\mathbf{x}$. However, inference is still amortized across each optimization step, and thus we still consider this to be an instance of amortized inference.} \begin{table} \small \caption{Correlation and Mean $L_1$ distance between the true vs. approximated marginals for the various methods.} \label{tab:ising_corr} \centering \begin{tabular}{lccccccc} \toprule & \multicolumn{3}{c}{Correlation} &&\multicolumn{3}{c}{Mean $L_1$ distance} \\ $n$ & Mean Field & Loopy BP & Inference Network & & Mean Field & Loopy BP & Inference Network \\ \midrule 5 & 0.835 & 0.950 & 0.988 & & 0.128 & 0.057 & 0.032 \\ 10 & 0.854 & 0.946 & 0.984 & & 0.123 & 0.064 & 0.037 \\ 15 & 0.833 & 0.942 & 0.981 & & 0.132 & 0.065 & 0.040 \\ \bottomrule \end{tabular} \end{table} \begin{figure} \caption{For each method, we plot the approximate marginals (x-axis) against the true marginals (y-axis) for a $15 \times 15$ Ising model. Top shows the node marginals while bottom shows the pairwise factor marginals, and $\rho$ denotes the Pearson correlation coefficient.} \centering \vspace{-2mm} \includegraphics[scale=0.23]{marginals} \label{fig:ising_fig} \vspace{-4mm} \end{figure} We first experiment to see whether learning the marginals via minimizing the Bethe free energy with gradient descent yields reasonable marginal distributions. Concretely, for a fixed $\boldsymbol{\theta}$ (sampled from spherical Gaussian), we perform gradient descent on the Bethe free energy $F(\boldsymbol{\tau}(\boldsymbol{\phi}), \boldsymbol{\theta})$ (Eq~\eqref{eq:bethe}) with respect to $\boldsymbol{\phi}$, where we use $\boldsymbol{\tau}(\boldsymbol{\phi})$ to denote the full set of marginal distributions obtained from the inference network. Table~\ref{tab:ising_corr} shows the correlation and the mean $L_1$ distance between the true marginals and the approximated marginals, where the numbers are averaged over 100 samples of $\boldsymbol{\theta}$. We find that compared to approximate marginals obtained from mean field and loopy belief propagation, the inference network produces marginal distributions that are more accurate. Figure~\ref{fig:ising_fig} shows a scatter plot of approximate marginals ($x$-axis) against the true marginals ($y$-axis) for a randomly sampled $15 \times 15$ Ising model. Interestingly, we observe that both loopy belief propagation and the inference network produce accurate node marginals (top), but the pairwise factor marginals from the inference network are much better (bottom). Encouraged by these results, we focus in Table~\ref{tab:ising_learn} on learning the generative model alongside the inference network. For a randomly generated Ising model, we obtain 1000 samples each for train, validation, and test sets, using a version of the forward-filtering backward-sampling algorithm to obtain exact samples in $O(2^n)$. We then train a (randomly-initialized) Ising model via the saddle point learning problem in Eq~\eqref{eq:amortsaddle}. While models trained with exact inference perform best, models trained with an inference network's approximation to the log partition function perform almost as well, and outperform both those trained with mean field and even with loopy belief propagation. See the Supplementary Material for additional training details. \begin{table}[t] \small \caption{Held out NLL of learned Ising models. True entropy refers to NLL under the true model (i.e. $\mathbb{E}_{P(\mathbf{x} ; \boldsymbol{\theta})}[-\log P(\mathbf{x} ; \boldsymbol{\theta})]$), and `Exact' refers to an Ising model trained with the exact partition function.} \label{tab:ising_learn} \centering \begin{tabular}{lccccccc} \toprule $n$ & True Entropy & Rand. Init. & Exact & & Mean Field & Loopy BP & Inference Network \\ \midrule 5 & 6.27 & 45.62 & 6.30 & & 7.35 & 7.17 & 6.47 \\ 10 & 25.76 & 162.53 & 25.89 & & 29.70 & 28.34 & 26.80 \\ 15 & 51.80 & 365.36 & 52.24 & & 60.03 & 59.79 & 54.91\\ \bottomrule \end{tabular} \vspace{-5mm} \end{table} \subsection{Restricted Boltzmann Machines (RBMs)} We next consider learning Restricted Boltzmann Machines~\citep{smolensky1986information}, a classic MRF model with latent variables. A binary RBM parameterizes the joint distribution over observed variables $\mathbf{x} \in \{0,1\}^V$ and latent variables $\mathbf{z} \in \{0,1\}^H$ as $P(\mathbf{x}, \mathbf{z} ; \boldsymbol{\theta}) = \frac{1}{Z(\btheta)} \exp(\mathbf{x}^{\top} \mathbf{W} \mathbf{z} + \mathbf{x}^\top \mathbf{b} + \mathbf{z}^\top \mathbf{a})$. Thus, there is a pairwise factor for each $(x_i, z_j)$ pair, and a unary factor for each $x_i$ and $z_j$. It is standard when learning RBMs to marginalize out the latent variables, which can be done tractably due to the structure of the model, and so we may train with the objective in ~\eqref{eq:amortsaddle}. Our inference network is similar to that used in our Ising model experiments: we associate a learnable embedding vector with each node in the model, which we concatenate with an embedding corresponding to an indicator feature for whether the node is in $\mathbf{x}$ or $\mathbf{z}$. These $V + H$ embeddings are then consumed by a bidirectional LSTM~\citep{hochreiter1997long, graves2013hybrid}, which outputs vectors $\mathbf{h}_{\mathbf{x}, i}$ and $\mathbf{h}_{\mathbf{z}, j}$ for each node. Finally, we obtain $\boldsymbol{\tau}_{ij}(x_i, z_j ; \boldsymbol{\phi}) = \softmax(\MLP [\mathbf{h}_{\mathbf{x}, i} ; \mathbf{h}_{\mathbf{z}, j}])$. We follow the experimental setting of \citet{kuleshov2017neural}, who recently introduced a neural variational approach to learning MRFs, and train RBMs with 100 hidden units on the UCI digits dataset~\citep{alimoglu1996combining}, which consists of $8 \times 8$ images of digits. We compare with persistent contrastive divergence (PCD)~\citep{tieleman2008training} and LBP, as well as with the best results reported in \citet{kuleshov2017neural}.\footnote{The corresponding NLL number reported in Table~\ref{tab:rbms} is derived from a figure in \citet{kuleshov2017neural}.} We used a batch size of 32 and selected hyperparameters for all models by monitoring validation expected pseudo-likelihood~\citep{besag1975statistical} over a random hyperparameter search; see the Supplementary Material for additional details. Table~\ref{tab:rbms} reports the held out average NLL as estimated with annealed importance sampling (AIS)~\citep{neal2001annealed,salakhutdinov2008quantitative}, using 10 chains and $10^3$ intermediate distributions. We see that while amortized BFE minimization is able to outperform all results except PCD, it does lag behind PCD. These results are consistent with previous claims in the literature~\citep{salakhutdinov2008quantitative} that LBP and its variants do not work well on RBMs. Amortizing BFE minimization does, however, appear to again outperform LBP. We also emphasize that PCD relies on being able to do fast block Gibbs updates during learning, which will not be available in general, whereas amortized BFE minimization has no such requirement. \begin{table} \small \caption{Held out NLL of learned RBMs, as estimated by AIS~\citep{salakhutdinov2008quantitative}. Neural Variational Inference results are taken from \citet{kuleshov2017neural}.} \label{tab:rbms} \centering \begin{tabular}{lcccc} \toprule & NLL & $\ell_F$ & Epochs to Converge & Seconds/Epoch \\ \midrule Loopy BP & 28.98 & 159.49 & 11 & 5242.5 \\ Inference Network & 23.79 & 18.25 & 23 & 15.0 \\ PCD & 21.24 & N/A & 29 & 1.0 \\ \midrule Neural Variational Inference~\citep{kuleshov2017neural} & $\geq$ 24.5 & & & \\ \bottomrule \end{tabular} \end{table} \subsection{High-order HMMs} Finally, we consider a scenario where both $Z(\btheta)$ and $Z(\boldx, \btheta)$ must be approximated, namely, that of learning 3rd order neural HMMs~\citep{tran2016} (as in Figure~\ref{fig:mrfs}) with \textit{approximate} inference. We consider this setting in particular because it allows for the use of dynamic programs to compare the true NLL attained when learning with approximate inference. However, because these dynamic programs scale as $O(TK^{L+1})$, where $T, L, K$ are the sequence length, Markov order, and number of latent state values, respectively, considering even higher-order models becomes difficult. A standard 3rd order neural HMM parameterizes the joint distribution over observed sequence $\mathbf{x} \, {\in} \, \{1, \ldots, V \}^T$ and latent sequence $\mathbf{z} \, {\in} \, \{1, \ldots, K \}^T$ as $P(\mathbf{x}, \mathbf{z} ; \boldsymbol{\theta}) \, {=} \, \frac{1}{Z(\btheta)} \exp(\sum_{t=1}^T \log \Psi_{t,1}(z_{t-3:t} ; \boldsymbol{\theta}) + \log \Psi_{t,2}(z_t, x_t; \boldsymbol{\theta}))$. The $\Psi_{t,1}$ and $\Psi_{t,2}$ factors are parameterized with feed forward networks; see \citet{tran2016} and the Supplementary Material. To further motivate the results of this section let us begin by considering using approximate inference techniques to learn \textit{directed} 3rd order neural HMMs, which are obtained from the joint distribution above by having each factor output a normalized distribution, making $Z(\btheta) = 1$. In particular, we attempt to learn a $K=30$ state 3rd order neural HMM on sentences from the Penn Treebank~\citep{Marcus1993} (using the standard splits and preprocessing by \citet{Mikolov2011}) of length at most 30. The top part of Table~\ref{tab:hmms} compares the NLL on the validation set obtained by learning such an HMM with exact inference against learning it with several variants of discrete VAE~\citep{Rezende2015,Kingma2014} and the REINFORCE~\citep{Williams1992} gradient estimator, namely: (1) using a fully factorized (i.e., mean field) approximate posterior over the $z_t$ obtained by running a bidirectional LSTM over $\mathbf{x}$ and feeding the hidden state at each time step to an affine layer followed by a softmax, together with an input dependent baseline~\citep{Mnih2014} for variance reduction; (2) the 10-sample IWAE~\citep{Burda2015} version of (1); (3) using a \textit{first-order} neural HMM conditioned on $\mathbf{x}$ as the variational distribution, which is sampled from exactly using quantities calculated with the forward algorithm~\citep{rabiner1989tutorial,chib1996calculating,scott2002bayesian,zucchini2016hidden}. We provide more details on these architectures and approaches in the Supplementary Material. As we can see, exact inference significantly outperforms the approximate methods, perhaps due to the difficulty in controlling the variance of the ELBO gradient estimators. An alternative to learning a 3rd order HMM with variational inference, then, is to consider an analogous \textit{undirected} model, which can be learned using BFE approximations, and therefore requires no sampling. In particular, we will consider the 3rd order undirected product-of-experts style HMM in Figure~\ref{fig:mrfs} (b), which contains only pairwise factors, and parameterizes the joint distribution of $\mathbf{x}$ and $\mathbf{z}$ as $P(\mathbf{x}, \mathbf{z} ; \boldsymbol{\theta}) \, {=} \, \frac{1}{Z(\btheta)} \exp(\sum_{t=1}^T \sum_{s=\max(t-3,1)}^{t-1} \log \Psi_{t,1,s}(z_s, z_t ; \boldsymbol{\theta}) + \sum_{t=1}^T \log \Psi_{t,2}(z_t, x_t; \boldsymbol{\theta}))$. Note that while this variant captures only a subset of the distributions that can be represented by the full parameterization (Figure~\ref{fig:mrfs} (a)), it still captures 3rd order dependencies using pairwise factors. We will keep the $\Psi_{t,2}$ emission factors locally normalized as in the directed case, and in order to fairly compare with standard directed HMMs (where the transition distribution is homogeneous), the unnormalized $\Psi_{t,1,s}$ factors will only be a function of the distance between $z_s$ and $z_t$; see the Supplementary Material. We train inference networks $f$ and $f_{\mathbf{x}}$ to output pseudo-marginals $\boldsymbol{\tau}$ and $\boldsymbol{\tau}_{\mathbf{x}}$ as in Algorithm~\ref{alg:alg}, using $I_1=1$ and $I_2=1$ gradient updates per minibatch. Because $Z(\btheta)$ and $Z(\boldx, \btheta)$ depend only on the latent variables (since factors involving the $x_t$ remain locally normalized), $f$ and $f_{\mathbf{x}}$ are bidirectional LSTMs consuming embeddings corresponding to the $z_t$, where $f_{\mathbf{x}}$ also consumes $\mathbf{x}$. As the bottom of Table~\ref{tab:hmms} shows, this amortized approach manages to outperform all the VAE variants both in terms of held out NLL and speed. It performs less well than true LBP, but is significantly faster. \begin{table} \small \caption{NLL of 3rd Order HMM variants learned with approximate and exact inference.} \label{tab:hmms} \centering \begin{tabular}{llcccr} \toprule & & NLL & ELBO/$\ell_{F,\mathbf{z}}$ & Epochs to Converge & Seconds/Epoch \\ \midrule \multirow{4}{*}{Directed} & Exact & 105.66 & 105.66 & 20 & 137.2\\ & Mean-Field VAE + BL & 119.27 & 175.46 & 14 & 81.8 \\ & Mean-Field IWAE-10 & 119.20 & 167.71 & 5 & 876.1\\ & 1st Order HMM VAE & 118.35 & 118.88 & 12 & 187.1 \\ \midrule \multirow{4}{*}{Undirected} & Exact & 104.07 & 104.07 & 20 & 122.1 \\ & LBP & 108.74 & 99.89 & 20 & 246.6 \\ & Inference Network & 115.89 & 115.87 & 7 & 70.2 \\ \bottomrule \end{tabular} \end{table} \section{Related Work} Using neural networks to perform approximate inference is a popular way to learn deep generative models, leading to a family of models called variational autoencoders \cite{Kingma2014,Rezende2014,Mnih2014}. However, such methods have generally been employed in the context of learning directed graphical models. Moreover, applying amortized inference to learn discrete latent variable models has proved challenging due to potentially high-variance gradient estimators that arise from sampling, though there have been some recent advances \cite{Jang2017,Maddison2017,Tucker2017,Grathwohl2018}. Outside of directed models, several researchers have proposed to incorporate deep networks directly into message-passing inference operations, mostly in the context of computer vision applications. \citet{heess2013learning} and \citet{lin2015deeply} train neural networks that learn to map input messages to output messages, while inference machines \cite{Ross2011,deng2016struct} also directly estimate messages from inputs. In contrast, \citet{li2014meanfield} and \citet{dai2016disc} instead approximate iterations of mean field inference with neural networks. Closely related to our work, \citet{yoon2018inference} employ a deep network over an underlying graphical model to obtain node-level marginal distributions. However, their inference network is trained against the true marginal distribution (i.e., not Bethe free energy as in the present work), and is therefore not applicable to settings where exact inference is intractable (e.g. RBMs). Also related is the early work of ~\citet{welling2001belief}, who also consider direct (but unamortized) minimization of the BFE, though only for inference and not learning. Finally, \citet{kuleshov2017neural} also learn undirected models via a variational objective, cast as an upper bound on the partition function. \section{Conclusion} We have presented an approach to learning MRFs which amortizes the minimization of the Bethe free energy by training inference networks to output approximate minimizers. This approach allows for learning models that are competitive with loopy belief propagation and other approximate inference schemes, and yet takes less time to train. { \bibliographystyle{plainnat} \small
{'timestamp': '2019-06-18T02:02:41', 'yymm': '1906', 'arxiv_id': '1906.06399', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06399'}
arxiv
\section{Introduction} Surveys and empirical studies have long been a cornerstone of psychological, sociological and medical research, but each of these traditional methods pose challenges for researchers. They are time-consuming, costly, may introduce a bias or suffer from bad experiment design. With the advent of big data and the increasing popularity of the internet and social media, larger amounts of data are now available to researchers than ever before. This offers strong promise new avenues of research using analytic procedures, obtaining a more fine-grained and at the same time broader picture of communities and populations as a whole~\cite{salathe2018digital}. Such methods allow for faster and more automated investigation of demographic variables. It has been shown that Twitter data can predict atherosclerotic heart-disease risk at the community level more accurately than traditional demographic data~\cite{eichstaedt2015psychological}. The same method has also been used to capture and accurately predict patterns of excessive alcohol consumption~\cite{curtis2018can}. In this study, we utilize Twitter data to predict various health target variables (AHD, diabetes, various types of cancers) to see how well language patterns on social media reflect the geographic variations of those targets. Furthermore, we propose a new method to study social media content by characterizing disease-related correlations of language, by leveraging available demographic and disease information on the community level. In contrast to~\cite{eichstaedt2015psychological}, our method is not relying on word-based topic models, but instead leverages modern state-of-the-art text representation methods, in particular sentence embeddings, which have been in increasing use in the Natural Language Processing, Information Retrieval and Text Analytics fields in the past years. We demonstrate that our approach helps capturing the semantic meaning of tweets as opposed to features merely based on word frequencies, which come with robustness problems \cite{brown2018does,schwartz2018more}. We examine the effectiveness of sentence embeddings in modeling language correlates of the medical target variables (disease outcome). Section~\ref{sec:method} gives a generalized description of our method. We apply the previously described method to the tweets and health data in Section~\ref{sec:datasources} The system's performance is evaluated in Section~\ref{sec:results} followed by the discussion in Section~\ref{sec:discussion}. Our code is available on \href{https://github.com/epfml/correlating-tweets}{github.com/epfml/correlating-tweets}. \section{Method}\label{sec:method} We are given a large quantity of text (sentences or tweets) in the form of social media messages by individuals. Each individual---and therefore each sentence---is assigned to a predefined category, for example a geographic region or a population subset. We assume the number of sentences to be significantly larger than the number of communities. Furthermore, we assume that the target variable of interest, for example disease mortality or prevalence rate, is available for each community (but not for each individual). Our system consists of two subsystems: \begin{enumerate} \item \emph{(Prediction)} The predictive subsystem makes predictions of target variables (e.g. AHD mortality rate) based on aggregated language features. The resulting linear predictions are applicable on the community level (e.g. counties) or on the individual level, and are trained using k-fold cross-validated Ridge regression. \item \emph{(Interpretability)} The averaged regression weights from the prediction system allow for interpretation of the system: We use a fixed clustering (which was obtained from all sentences without any target information), and then rank each topic cluster with respect to a prediction weight vector from point 1). The top and bottom ranked topic clusters for each target variable give insights into known and potentially novel correlations of topics with the target medical outcome. \end{enumerate} In summary, the community association is used as a proxy or weak labelling to correlate individual language with community-level target variables. The following subsections give a more detailed description of the two subsystems. \subsection{System Description} Let $\mathcal{S}$ be the set of sentences (e.g. tweets), with their total number denoted as $|\mathcal{S}| = S$. Each sentence is associated to exactly one of the $A$ communities $\mathcal{A}=\{a_1,\dots,a_A\}$ (e.g. geographic regions). The function $\delta: \mathcal{S} \rightarrow \mathcal{A}$ defines this mapping. Let $\mathbf{y} \in \mathbb{R}^{A}$ be the target vector for an arbitrary target variable, so that each community $a_j$ has a corresponding target value $y_{a_j}\in\mathbb{R}$. \begin{figure} \includegraphics[width=7.5cm]{images/health_twitter_paper_diagram.pdf} \caption{System Description.} \label{fig:systemDescription} \end{figure} \paragraph{Preprocessing and Embeddings.} The complete linguistic preprocessing pipeline of a sentence is incorporated by the function $\rho(s_i), \ \forall \ i \in \{1,\dots,S\}$, which represents an arbitrary sentence~$s_i$ as a sequence of tokens. Each sentence~$s_i$ then is represented by a $D$-dimensional embedding vector providing a numerical representation of the semantics for the given short text: \begin{equation} \mathbf{x}_i = \textit{Sent2Vec}(\rho(s_i)) \in \mathbb{R}^{D}. \end{equation} While our method is generic for any text representation method, here Sent2Vec \cite{pgj2017unsup} was chosen for its computational efficiency and scalability to large datasets. \subsection{Feature Aggregation} We use averaging of the sentence embedding vectors over each community to obtain the language features for each community. Formally, the complete feature matrix of all sentences is denoted as~$\textbf{X} \in \mathbb{R}^{S\times D}$. For our approach, the sentence embedding features are averaged over each community $a_j$. Formally, an individual feature $\overline{x}_{{a_j},d}$ of the averaged embedding $\overline{\mathbf{x}}_{a_j} \in \mathbb{R}^{1 \times D}$ for a given community~$a_j$ is defined as \begin{equation} \overline{x}_{{a_j},d} = \frac{1}{N_{a_j}} \sum_{x_i : s_i \in \mathcal{S} \ \ \land \ \ \delta(s_i) = a_j} x_{i,d}, \end{equation} where $N_{a_j} = |\{s_i: s_i \in S \land \delta(s_i) = a_j\}|$ is the number of sentences belonging to community $a_j$. Consequently, the aggregated community-level embedding matrix is given by \begin{equation} \overline{\mathbf{X}} = \begin{bmatrix} \overline{\mathbf{x}}_{a_1}^{\top} \\ \vdots \\ \overline{\mathbf{x}}_{a_A}^{\top} \end{bmatrix} \in \mathbb{R}^{A \times D}. \end{equation} \subsection{Train-Test Split} Leveraging the targets available for each community, our regression method is applied to the aggregated features $\overline{\mathbf{X}}$ and the target $\mathbf{y}$. We employ $K$-fold cross-validation: the previously defined set $\mathcal{A}$ is split into K as equally sized pairwise disjoint subsets $\mathcal{A}_k$ as possible such that: $\mathcal{A}=\bigcup_{k=1}^K \mathcal{A}_k$, $\mathcal{A}_i \cap \mathcal{A}_j = \emptyset \ \forall i,j \in {1,\dots, K}, i \neq j$ and $|\mathcal{A}_1| \approx \dots \approx|\mathcal{A}_K|$. The training set for a fold~$k$ is $\text{TR}_k = \left(\bigcup_{i=1}^K \mathcal{A}_i \right)\setminus \mathcal{A}_k$ with the corresponding test set $\text{TE}_k = \mathcal{A}_k$, where $N^{\theta}_k = |\text{TR}_k|$ and $N^{\Lambda}_k=|\text{TE}_k|$. The operators $\theta_k: \{1,\dots,N^{\theta}_k\} \rightarrow \text{TR}_k$ and $\Lambda_k: \{1,\dots,N^{\Lambda}_k\} \rightarrow \text{TE}_k$ uniquely map the indexes to the corresponding communities $a_j$ for the $k^{th}$ train-test split. For each split $k$ the train and test embedding matrices respectively are defined as \begin{equation} \overline{\mathbf{X}}_{\theta_k} = \left[\overline{\mathbf{x}}_{\theta_k(1)},\dots,\mathbf{\overline{x}}_{\theta_k(N_k^{\theta})} \right]^{\top}, \vspace{-2mm} \end{equation} \begin{equation} \overline{\mathbf{X}}_{\Lambda_k} = \left[\overline{\mathbf{x}}_{\Lambda_k(1)},\dots,\mathbf{\overline{x}}_{\Lambda_k(N_k^{\Lambda})} \right]^{\top}. \end{equation} Accordingly, we define the target vectors \begin{equation} \mathbf{y}_{\theta_k} = \left[y_{\theta_k(1)}, \dots, y_{\theta_k(N_k^{\theta})} \right]^{\top},\vspace{-3mm} \end{equation} \begin{equation} \mathbf{y}_{\Lambda_k} = \left[ y_{\Lambda_k(1)}, \dots, y_{\Lambda_k(N_k^{\Lambda})} \right]^{\top}. \end{equation} \subsection{Ridge Regression} For each train-test split $k$ we perform linear regression from the community-level textual features $\overline{\mathbf{X}}_{\theta_k}$ to the health target variable $\mathbf{y}_{\theta_k}$. We employ Ridge regression \cite{hoerl1970ridge}. In our context, the Ridge regression is defined as the following optimization problem: \begin{equation} \underset{\bm{\omega}_k\in \mathbb{R}^D}{\min} \ \frac{1}{2A}\sum_{i=1}^{N^\theta_k} \big[y_{\theta_k(i)} - \mathbf{\overline{x}}_{\theta_k}^\top\bm{\omega}_k\big]^2 + \lambda\|\bm{\omega}_k\|_2^2, \end{equation} where the optimal solution is \begin{equation} \bm{\omega}_k^\star = \big(\bm{\overline{X}}_{\theta_k}^{\top}\mathbf{\overline{X}}_{\theta_k} + 2N_{k}^\theta\lambda\mathbf{I}\big)^{-1}\mathbf{\overline{X}}_{\theta_k}^{\top} \quad \in \mathbb{R}^D. \end{equation} Within each each fold we tune the regularization parameter $\lambda$. \subsection{Prediction Subsystem}\label{sec:predsystem} Let $\bm{\overline{y}}_{\Lambda_k} = \mathbf{\overline{X}}_{\Lambda_k} \bm{\omega}_k^\star = [\overline{y}_{\Lambda_k(1)}, \dots, \overline{y}_{\Lambda_k(N^{\Lambda}_k)}]^{\top}$ be the predicted values for the test set of the split~$k$. The concatenated prediction vector for all splits is \begin{equation} \mathbf{\overline{y}}_\Lambda = \begin{bmatrix} \overline{\mathbf{y}}_{\Lambda_1}^{\top} \\ \vdots \\ \overline{\mathbf{y}}_{\Lambda_K}^{\top} \end{bmatrix} \in \mathbb{R}^A \end{equation} Accordingly, we define the concatenated true target vector as \begin{equation} \mathbf{y}_\Lambda = \begin{bmatrix} \mathbf{y}_{\Lambda_1}^{\top} \\ \vdots \\ \mathbf{y}_{\Lambda_K}^{\top} \end{bmatrix} \in \mathbb{R}^A, \end{equation} i.e., the set of individual scalars is identical to the entries in the original target vector~$\bm{y}$. The predictive performance of the system can be assessed through the following metrics: \begin{itemize} \item Pearson Correlation Coefficient \item Mean Average Error of prediction (MAE) \item Classification Accuracy for Quantile Prediction \end{itemize} The first two metrics are evaluated with the vectors $\overline{\mathbf{y}}_\Lambda$ and $\mathbf{y}_\Lambda$ from all folds. In the quantile-based assessment we independently bin the true values $\mathbf{y}_\Lambda$ and the predicted values $\overline{\mathbf{y}}_\Lambda$ into $C$ different quantiles. Each individual true and predicted value is assigned to a quantile $c_j \in \{c_1, \dots, c_C\}$. These assignments can be used to visually compare results on a heat-map or as regular evaluation scores in terms of accuracy. \subsubsection{Ridge-Weight Aggregation} For the final prediction model, the regression weights $\bm{\omega}^\star_k$ from Ridge regression are averaged over the $K$ folds, i.e. $\bm{\overline{\omega}} = \frac{1}{K} \sum_{k=1}^K \bm{\omega}^\star_k$. For every sentence embedding $\mathbf{x}_q$, the prediction is computed as $\overline{y}_q = \mathbf{x}_q^{\top} \bm{\overline{\omega}} \in \mathbb{R}$. \subsection{Interpretation Subsystem: Cluster Ranking} We employ predefined textual topic clusters---which are independent of any target values---in order to enable interpretation of the textual correlates. Each cluster is a collection of sentences and should, intuitively, be interpretable as a topic, e.g. separate topics about indoor and outdoor activities as shown in Fig.~\ref{fig:melanoma}. For each cluster $m$ a ranking score can be computed with respect to a linear prediction model $\bm{\overline{\omega}}$ such as defined above. Let $\mathcal{Q}_m = \{ q: \zeta(q) = m \ \land \ q \ \in \mathcal{Q}\}$ be the set of sentences assigned to cluster $m$. The score $\iota_m$ for the cluster $m$ is the average of all predictions $\overline{y}_q = \mathbf{x}_q^{\top} \bm{\overline{\omega}}$ within the cluster $m$: \begin{equation} \iota_m = \frac{1}{|\mathcal{Q}_m|} \sum_{\overline{y}_q:\ q \in \mathcal{Q}_m} \overline{y}_q \end{equation} By ordering the scores $\iota_m$ of all clusters, we obtain the final ranking sequence of all clusters, with respect to the target-specific model $\bm{\overline{\omega}}$. \\ \emph{Clustering Preprocessing.} For obtaining the fixed clustering, as $\mathbf{X}$ is a very large matrix, clustering might require subsampling to reduce computational complexity. Hence, $Q$ out of the $S$ embeddings in $\mathcal{S}$ are randomly subsampled into the set $\mathcal{Q}$. The mapping $\Phi(Q) = [\phi(1), \dots, \phi(Q)]^{\top}$ is a uniformly random selection of row indexes in $\mathbf{X}$ out of $\binom{N}{Q}$. We define the subsampled data matrix as $\mathbf{X}_Q = \left [ \mathbf{x}_{\phi (1)}, \dots, \mathbf{x}_{\phi (Q)} \right]^{\top} \in \mathbb{R}^{Q \times D}$. The subset $\mathbf{X}_Q$ is clustered with the Yinyang K-Means algorithm \cite{kmeans}. We use~$M$ centroids and the cosine similarity as a distance function. The cluster assignment vector $\mathbf{M} \in [1,\dots,M]^{\top}$ assigns one cluster for each embedding in $\mathbf{X}_Q$. Accordingly, the operator $\zeta:~\{1,\dots,Q\}~\rightarrow~\{1,\dots,M\}$ indicates the assigned cluster $m$ for a given sentence $s$ in $\mathcal{Q}$ (see cluster ranking above). The cluster centers are defined in $\mathbf{M}_Q \in \mathbb{R}^{Q \times D}$. \section{Data sources}\label{sec:datasources} We apply the method described in Section~\ref{sec:method} to the following setting: The pool of sentences $\mathcal{S}$ consists of geotagged Tweets. The assigned locations are in the United States. The geotags are categorized into US-counties which represent the set of communities $\mathcal{A}$. The target variables~$\mathbf{y}$ are health-related variables, for example normalized mortality or prevalence rates. We focus on cancer and AHD mortality as well as on diabetes prevalence. Hence, the quantile-based predictions give a categorization of the Ridge regression predictions on a US-county level. The ranked topics assess what language might relate to higher or lower rates of the corresponding disease. Table~\ref{tab:datasources} provides an overview of the size of the data sources, the year the data was collected in and the mean $\mu$ and standard deviation $\sigma$ of the target variables. Not all counties are covered in the publicly available datasets, usually being limited to more populous counties. The collected Tweets are from 2014 and 2015. The target variables are the union-averaged values from 2014 and 2015: if the target variable is available for both years the two values are averaged. Conversely, if a county data point is only available for one, but not both years, we use this standalone value. \begin{table}[h] \setlength{\tabcolsep}{5pt} \vspace{2mm} \centering \begin{tabular}{ |l|r|r|c| } \hline \textbf{Name} & \textbf{\# tweets} & \textbf{Year} & \\ \hline \hline Datorium & 147M & 14/15 & \\ \hline \hline \textbf{Name} & \textbf{\# counties} & \textbf{Year} & $\bm{\mu}$, $\bm{\sigma}$\\ \hline \hline AHD & 803 & 14/15 & 43.0, 16.1 \\ \hline Diabetes & 3129 & 13 & 9.7, 2.2 \\ \hline Breast & 487 & 13/14 & 12.4, 2.8 \\ \hline Colon & 490 & 13/14 & 12.1, 3.0 \\ \hline Liver & 293 & 13/14 & 7.5, 2.4 \\ \hline Lung & 1612 & 13/14 & 52.4, 16.2 \\ \hline Melanoma & 162 & 13/14 & 3.8, 1.2 \\ \hline Prostate & 351 & 13/14 & 8.5, 2.0 \\ \hline Stomach & 136 & 13/14 & 3.6, 0.9 \\ \hline \end{tabular} \caption{Overview of data sources. } \label{tab:datasources} \end{table} \subsection{Datorium Tweets} Tweets are short messages of no more than 140 characters\footnote{Twitter increased the limit to 280 characters in 2017, which doesn't affect our data.} published by users of the Twitter platform. They reflect discussions, thoughts and activities of its users. We use a dataset of approximately 144 million tweets collected from first of June 2014 to first of June 2015 \cite{datorium}. Each tweet was geotagged by the submitting user with exact GPS coordinates and all tweets are from within the US, allowing accurate county-level mapping of individual tweets. \subsection{AHD \& Cancer Mortality} Our source of the statistical county-level target variables is the CDC WONDER\footnote{US Centers for Disease Control and Prevention - Wide-ranging Online Data for Epidemiologic Research.} database \cite{wonder} for AHD and cancer. Values are given as deaths per capita (100'000). \subsection{Diabetes Prevalence} We use county-wise age-adjusted diabetes prevalence data from the year 2013 \cite{diabetes}, provided as percent of the population afflicted with type II diabetes. The data is available for almost all the 3144 US counties, making it a valuable target to use. \section{Results}\label{sec:results} The results of our method for the various target variables are listed in Table~\ref{tab:results} along with the performance of the baseline model outlined in Section~\ref{sec:baseline}. We provide the Pearson correlation ($\bm{\rho}$) and the mean absolute error (MAE) of our system along with the baseline model's Pearson correlation. \subsection{LDA Baseline Model}\label{sec:baseline} We reimplemented the approach proposed by \citet{eichstaedt2015psychological} as a baseline for comparison, and were able to reproduce their findings about AHD with recent data: similar results were found with the Datorium Twitter dataset \cite{datorium} and CDC AHD data from 2014 and 2015. Their approach averages topics generated with Latent Dirichlet Allocation (LDA) of tweets per county as features for Ridge regression. We do not use any hand-curated emotion-specific dictionaries, as these did not impact performance in our experiments. We used the predefined \textit{Facebook} LDA coefficients of \citet{eichstaedt2015psychological}, updated them with the word frequencies of our collected Twitter data \cite{datorium}. Our results are computed with a 10-fold cross-validation and without any feature selection. \begin{table}[h] \centering \begin{tabular}{ |l|c|c|c| } \hline \textit{Type} & $\bm{\rho}$ & $\bm{\rho}$ \textit{LDA} & \textit{MAE} \\ \hline \hline AHD & \textbf{0.46} & 0.31 & 13.4 \\ \hline \hline Diabetes & \textbf{0.73} & 0.72 & 1.1 \\ \hline \hline Breast & \textbf{0.44} & 0.42 & 1.80 \\ \hline Colon & \textbf{0.55} & 0.51 & 1.87 \\ \hline Liver & 0.29 & \textbf{0.40} & 1.59 \\ \hline Lung & \textbf{0.68} & 0.63 & 8.44 \\ \hline Melanoma & \textbf{0.72} & 0.61 & 0.68 \\ \hline Prostate & \textbf{0.39} & 0.38 & 1.34 \\ \hline Stomach & 0.44 & \textbf{0.51} & 0.72 \\ \hline \end{tabular} \caption{Results of predictions on different health targets. $\bm{\rho}$: our system (Section~\ref{sec:predsystem}), $\bm{\rho}$ LDA: topic model baseline (\citet{eichstaedt2015psychological}, Section~\ref{sec:baseline}), MAE: mean absolute error of our system (Section~\ref{sec:predsystem}).} \label{tab:results} \end{table} \begin{figure*}[!htb] \centering \vspace{2mm} \subfloat[]{ \includegraphics[width=0.45\linewidth]{images/diabetes_target_cropped_smaller.png} } ~ \subfloat[]{ \includegraphics[width=0.45\linewidth]{images/diabetes_pred_cropped_smaller.png}\vspace{-2mm} } \caption[Diabetes]{Quantiles of the prevalence of \textbf{diabetes}. (a) Target values (b) Predicted values from tweets} \label{fig:diabMap} \end{figure*} \begin{figure}[!htb] \subfloat[]{ \includegraphics[width=0.45\linewidth]{images/diabetes/cluster_rank_0_id_1396.png} } \subfloat[]{ \includegraphics[width=0.45\linewidth]{images/diabetes/cluster_rank_5_id_125.png} } \subfloat[]{ \includegraphics[width=0.45\linewidth]{images/diabetes/cluster_rank_1969_id_674.png} } \subfloat[]{ \includegraphics[width=0.45\linewidth]{images/diabetes/cluster_rank_1972_id_165.png} } \caption[Diabetes]{Word clouds of topics correlating with \textbf{diabetes}: (a) (b) strongest positive correlation (c) (d) strongest negative correlation among $M=2000$ clusters.\vspace{-2mm}} \label{fig:diabeteswords} \end{figure} \begin{figure}[!htb] \subfloat[]{ \includegraphics[width=0.45\linewidth]{images/melanoma/cluster_rank_0_id_1006.png} } \subfloat[]{ \includegraphics[width=0.45\linewidth]{images/melanoma/cluster_rank_3_id_646.png} } \subfloat[]{ \includegraphics[width=0.45\linewidth]{images/melanoma/cluster_rank_1973_id_1295.png} } \subfloat[]{ \includegraphics[width=0.45\linewidth]{images/melanoma/cluster_rank_1957_id_1398.png} } \caption[Melanoma]{Word clouds of topics correlating with \textbf{melanoma}: (a) (b) strongest positive correlation (c) (d) strongest negative correlation among $M=2000$ clusters.} \label{fig:melanoma} \end{figure} \subsection{Detailed Results} In this section we discuss a selection of our results in detail, with additional information available in~Appendix~\ref{sec:addCharts}. Diabetes has a strong demographic bias, with a higher prevalence in the south-east of the US, the so called \textit{diabetes belt}. Compared to the national average, the african-american population in the diabetes belt has a higher risk of diabetes by a factor of more than 2 \cite{barker2011geographic} and the south-east of the US has a large african-american population. Therefore, linguistic features~\cite{green2002african} common in african-american are a strong predictor of diabetes rates. The model learns these linguistic features, as seen in Figure~\ref{fig:diabeteswords}, and its predictions closely match the actual geographic distribution, as seen in Figure~\ref{fig:diabMap}. A moderate alcohol consumption is linked to a low risk of type II diabetes compared to no or excessive consumption \cite{koppes2005moderate}. The strongest negatively correlated word clouds in Figure \ref{fig:diabeteswords} support this finding. The most positively related word clouds for melanoma in Figure~\ref{fig:melanoma} are related to outdoor activities \cite{elwood1985cutaneous}. Conversely, the strongest negatively correlated word clouds suggest indoor activity related language. \section{Discussion}\label{sec:discussion} In this paper, we introduced a novel approach for language-based predictions and correlation of community-level health variables. For various health-related demographic variables, our approach outperforms in most cases (Table~\ref{tab:results}) similar models based on traditional demographic data by using only geolocated tweets. Our approach provides a method for discovering novel correlations between open-vocabulary topics and health variables, allowing researchers to discover yet unknown contributing factors based on large collections of data with minimal effort. Our findings, when applying our method to AHD risk, diabetes prevalence and the risk of various types of cancers, using geolocated tweets from the US only, show that a large variety of health-related variables can be predicted with surprisingly high precision based solely on social media data. Furthermore, we show that our model identifies known and novel risk or protective factors in the form of topics. Both aspects are of interest to researchers and policy makers. Our model proved to be robust for the majority of targets it was applied to. For AHD risk, we show that our approach significantly outperforms previous models based on topic models such as LDA or traditional statistical models \cite{eichstaedt2015psychological}, achieving a $\rho$-value of 0.46, an increase of 0.09 over previous approaches. For diabetes prevalence our model correctly predicts its geographic distribution by identifying linguistic features common in high-prevalence areas among other features, with a $\rho$-value of 0.73. For melanoma risk, it finds a high-correlation with the popularity of outdoor activities, corresponding to exposure to sunlight being one of the main risk factors in skin cancer, with an overall $\rho$-value of 0.72. One of the main limitations of our approach is the need for a large collection of sentences for each community as well as a large number of communities with target variables, leading to potentially unreliable results when this is not the case, such as for social media posts by individuals or when modeling target values which are only available in e.g. few counties. Further research is needed to ascertain whether significant results can also be achieved in such scenarios, and if robustness of our approach is improved compared to bag-of-words-based baselines \cite{eichstaedt2015psychological,brown2018does,schwartz2018more}. Furthermore, all mentioned approaches rely on \emph{correlation}, and thus do not provide a way to determine any \emph{causation}, or ruling out of potential underlying factors not captured by the model. Even though using social media data introduces a non-negligible bias towards users of social media, our approach was able to predict target variables tied to very different age-groups, which is encouraging and supports the robustness of our approach. \\ Our method captures language features on a community scale. This raises the question of how these findings can be translated to the individual person. Theoretically, a community-based model as described above could be used to rank social media posts or messages of an individual user, with respect to specific health risks. However, as we currently do not have ground truth values on the individual level, and since user's social media history has very high variance, this is left for future investigation. Future research should also address the applicability of our model to textual data other than Twitter and potentially from non-social media sources, to communities that are not geography based, to the time evolution of topics and health/lifestyle statistics, as well as to targets that are not health related. The general methodology offers promise for new avenues for data-driven discovery in fields such as medicine, sociology and psychology. \paragraph{Acknowledgements.} We would like to thank Ahmed Kulovic and Maxime Delisle for valuable input and discussions. \clearpage
{'timestamp': '2019-06-25T02:35:35', 'yymm': '1906', 'arxiv_id': '1906.06465', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06465'}
arxiv
\section{Introduction} In this paper we consider the problem of building the minimal deterministic finite-state automaton generating a given regular language. This is a classical issue that arises in many different areas of computer science such as verification, regular expression searching and natural language processing, to name a few. There exists a number of methods, such as Hopcroft's~\cite{hopcroft1971} and Moore's algorithms~\cite{moore1956}, that receive as input a deterministic finite-state automaton (DFA for short) generating a language and build the minimal DFA for that language. In general, these methods rely on computing a partition of the set of states of the input DFA which is then used as the set of states of the minimal DFA. On the other hand, Brzozowski~\cite{brzozowski1962canonical} proposed the \emph{double-reversal method} for building the minimal DFA for the language generated by an input non-deterministic automaton (NFA for short). This algorithm alternates a reverse operation and a determinization operation twice, relying on the fact that, for any given NFA \(\mathcal{N}\), if the reverse automaton of \(\mathcal{N}\) is deterministic then the determinization operation yields the minimal DFA for the language of \(\mathcal{N}\).\linebreak This method has been recently generalized by Brzozowski and Tamm~\cite{brzozowski2014theory}. They showed the following \emph{necessary and sufficient condition}: the determinization operation yields the minimal DFA for the language of \(\mathcal{N}\) if and only if the reverse automaton of \(\mathcal{N}\) is \emph{atomic}. It is well-known that all these approaches to the DFA minimization problem aim to compute Nerode's equivalence relation for the considered language. However, the double-reversal method and its later generalization appear to be quite isolated from other methods such as Hopcroft's and Moore's algorithms. This has led to different attempts to better explain Brzozowski's method~\cite{bonchi_algebra-coalgebra_2014} and its connection with other minimization algorithms~\cite{Adamek2012,Champarnaud2002,Garcia2013}. We use a framework of automata constructions based on equivalence classes over \emph{words} to give new insights on the relation between these algorithms. In this paper we consider equivalence relations over words on an alphabet \(\Sigma\) that induce finite partitions over \(\Sigma^*\). Furthermore, we require that these partitions are well-behaved with respect to concatenation, namely, \emph{congruences}. Given a regular language \(L\) and an equivalence relation satisfying these conditions, we use well-known automata constructions that yield automata generating the language \(L\)~\cite{Buchi89,Khoussainov2001}. In this work, we consider two types of equivalence relations over words verifying the required conditions. First, we define a \emph{language-based equivalence}, relative to a regular language, that behaves well with respect to \emph{right} concatenation, also known as the right Nerode's equivalence relation for the language. When applying the automata construction to the right Nerode's equivalence, we obtain the minimal DFA for the given language~\cite{Buchi89,Khoussainov2001}. In addition, we define an \emph{automata-based equivalence}, relative to an NFA. When applying the automata construction to the automata-based equivalence we obtain a determinized version of the input NFA. On the other hand, we also obtain counterpart automata constructions for relations that are well-behaved with respect to \emph{left }concatenation. In this case, language-based and automata-based equivalences yield, respectively, the minimal co-deterministic automaton and a co-deterministic NFA for the language. The relation between the automata constructions resulting from the language-based and the automata-based congruences, together with the the duality between right and left congruences, allows us to relate determinization and minimization operations. As a result, we formulate a sufficient and necessary condition that guarantees that determinizing an automaton yields the minimal DFA. This formulation evidences the relation between the double-reversal and the state partition refinement minimization methods. We start by giving a simple proof of Brzozowski's double-reversal method~\cite{brzozowski1962canonical}, to later address the generalization of Brzozowski and Tamm~\cite{brzozowski2014theory}. Furthermore, we relate the iterations of Moore's partition refinement algorithm, which works on the states of the input DFA, to the iterations of the greatest fixpoint algorithm that builds the right Nerode's partition on words. We conclude by relating the automata constructions introduced by Brzozowski and Tamm~\cite{brzozowski2014theory}, named the \emph{átomaton} and \emph{the partial átomaton}, to the automata constructions described in this work. \subparagraph{Structure of the paper.} % \label{subp:structure} After preliminaries in Section~\ref{sec:preliminaries}, we introduce in Section~\ref{sec:automataConstructions} the automata constructions based on congruences on words and establish the duality between these constructions when using right and left congruences. Then, in Section~\ref{sec:congruences}, we define language-based and automata-based congruences and analyze the relations between the resulting automata constructions. In Section~\ref{sec:Novel}, we study a collection of well-known constructions for the minimal DFA. Finally, we give further details on related work in Section~\ref{sec:relatedWork}. % For space reasons, missing proofs are deferred to the Appendix. \section{Preliminaries} \label{sec:preliminaries} \subparagraph{Languages.} Let \(\Sigma\) be a finite nonempty \emph{alphabet} of symbols. Given a word \(w \in \Sigma^*\), \(w^R\) denotes the \emph{reverse} of \(w\). Given a language \(L \subseteq \Sigma^*\), \(L^R ≝ \{w^R \mid w \in L\}\) denotes the \emph{reverse language} of \(L\). We denote by \(L^c\) the \emph{complement} of the language \(L\). The \emph{left (resp. right) quotient} of L by a word \(u\) is defined as the language \(u^{-1}L ≝ \{x \in \Sigma^* \mid ux \in L\}\) (resp. \(Lu^{-1} ≝ \{x \in \Sigma^* \mid xu \in L\}\)). \subparagraph{Automata.} A \emph{(nondeterministic) finite-state automaton} (NFA for short), or simply \emph{automaton}, is a 5-tuple \(\mathcal{N} = (Q, \Sigma, \delta, I, F)\), where \(Q\) is a finite set of \emph{states}, \(\Sigma\) is an alphabet, \({I\subseteq Q}\) are the \emph{initial} states, \(F \subseteq Q\) are the \emph{final} states, and \(\delta: Q \times \Sigma \rightarrow \wp(Q)\) is the \emph{transition} function. We denote the \emph{extended transition function} from \(\Sigma\) to \(\Sigma^*\) by \(\hat{\delta}\). Given \(S,T \subseteq Q\), \(W^{\mathcal{N}}_{S,T} \stackrel{\rm\scriptscriptstyle def}{=} \{w \in \Sigma^* \mid \exists q \in S, q' \in T: q' \in \hat{\delta}(q,w)\}\). In particular, when \(S = \{q\}\) and \(T = F\), we define \emph{the right language} of state \(q\) as \(W^{\mathcal{N}}_{q,F}\). Likewise, when \(S = I\) and \(T = \{q\}\), we define the \emph{left language} of state \(q\) as \(W^{\mathcal{N}}_{I,q}\). We define \(\post_w^{\mathcal{N}}(S) \stackrel{\rm\scriptscriptstyle def}{=} \{q \in Q \mid w \in W^{\mathcal{N}}_{S,q}\}\) and \(\pre_w^{\mathcal{N}}(S) \stackrel{\rm\scriptscriptstyle def}{=} \{q \in Q \mid w \in W^{\mathcal{N}}_{q,S}\}\). In general, we omit the automaton \(\mathcal{N}\) from the superscript when it is clear from the context. We say that a state \(q\) is \emph{unreachable} if{}f \(W^{\mathcal{N}}_{I,q} = \emptyset\) and we say that \(q\) is \emph{empty} if{}f \(W^{\mathcal{N}}_{q,F} = \emptyset\). Finally, note that \(\lang{\mathcal{N}} = \bigcup_{q \in I} W_{q,F}^{\mathcal{N}} = \bigcup_{q \in F} W_{I,q}^{\mathcal{N}} = W_{I,F}^{\mathcal{N}}\). Given an NFA \(\mathcal{N} = (Q, \Sigma, \delta, I, F)\), the \emph{reverse NFA} for \(\mathcal{N}\), denoted by \(\mathcal{N}^R\), is defined as \(\mathcal{N}^R = (Q, \Sigma, \delta_r, F, I)\) where \(q \in \delta_r (q',a)\) if{}f \(q' \in \delta(q,a)\). Clearly, \(\lang{\mathcal{N}}^R = \lang{\mathcal{N}^R}\). A \emph{deterministic finite-state automaton} (DFA for short) is an NFA such that, \(I = \{q_0\}\), and, for every state \(q \in Q\) and every symbol \(a \in \Sigma\), there exists exactly one \(q' \in Q\) such that \(\delta(q,a) = q'\). According to this definition, DFAs are always \emph{complete}, i.e., they define a transition for each state and input symbol. In general, we denote NFAs by \(\mathcal{N}\), using \(\mathcal{D}\) for DFAs when the distinction is important. A \emph{co-deterministic finite-state automata} (co-DFA for short) is an NFA \(\mathcal{N}\) such that \(\mathcal{N}^R\) is deterministic. In this case, co-DFAs are always \emph{co-complete}, i.e., for each target state \(q'\) and each input symbol, there exists a source state \(q\) such that \(\delta(q,a) = q'\). Recall that, given an NFA \(\mathcal{N} = (Q, \Sigma, \delta, I, F)\), the well-known \emph{subset construction} builds a DFA \(\mathcal{D} = (\wp(Q), \Sigma, \delta_{d}, \{I\}, F_{d})\) where \(F_d = \{S \in \wp(Q) \mid S \cap F \neq \emptyset\}\) and \(\delta_d(S,a) = \{q' \mid \exists q \in S, q' \in \delta(q,a)\}\) for every \(a \in \Sigma\), that accepts the same language as \(\mathcal{N}\)~\cite{Ullman2003}. Given an NFA \(\mathcal{N} = (Q, \Sigma, \delta, I, F)\), we denote by \(\mathcal{N}^D\) the DFA that results from applying the subset construction to \(\mathcal{N}\) where only subsets (including the empty subset) that are reachable from the initial subset of \(\mathcal{N}^D\) are used. Then, \(\mathcal{N}^D\) possibly contains empty states but no state is unreachable. A DFA for the language \(\lang{\mathcal{N}}\) is \emph{minimal}, denoted by \(\mathcal{N}^{DM}\), if it has no unreachable states and no two states have the same right language. The minimal DFA for a regular language is unique modulo isomorphism. \subparagraph{Equivalence Relations and Partitions.} Recall that an \emph{equivalence relation} on a set \(X\) is a binary relation \(\sim\) that is reflexive, symmetric and transitive. Every equivalence relation \(\sim\) on \(X\) induces a \emph{partition} \(P_{\sim}\) of \(X\), i.e., a family \(P_{\sim} = \{B_i\}_{i\in \mathcal{I}}\subseteq \wp(X)\) of subsets of \(X\), with \(\mathcal{I} \subseteq \mathbb{N}\), such that: \begin{romanenumerate}% \item \(B_i \neq \emptyset\) for all \(i \in \mathcal{I}\); \item \(B_i \cap B_j = \emptyset\), for all \(i,j \in \mathcal{I}\) with \(i \neq j\); and \item \(X = \bigcup_{i \in \mathcal{I}} B_i\). \end{romanenumerate} We say that a partition is \emph{finite} when \(\mathcal{I}\) is finite. Each \(B_i\) is called a \emph{block} of the partition. Given \(u\in X\), then \(P_{\sim}(u)\) denotes the unique block that contains \(u\) and corresponds to the \emph{equivalence class} \(u\) w.r.t. \(\sim\), \( P_{\sim}(u) ≝ \{v \in X \mid u \sim v \}\). This definition can be extended in a natural way to a set \(S \subseteq X\) as \(P_{\sim}(S) ≝ \bigcup_{u \in S} P_{\sim}(u)\). We say that the partition \(P_{\sim}\) \emph{represents precisely} \(S\) if{}f \(\ P_{\sim}(S) = S\). An equivalence relation \(\sim\) is \emph{of finite index} if{}f \(\sim\) defines a finite number of equivalence classes, i.e., the induced partition \(P_{\sim}\) is finite. In the following, we will always consider equivalence relations of finite index, i.e., finite partitions. Finally, denote \(Part(X)\) the set of partitions of \(X\). We use the standard refinement ordering \(\preceq\) between partitions: let \(P_1, P_2 \in Part(X)\), then \(P_1 \preceq P_2\) if{}f for every \(B \in P_1\) there exists \(B' \in P_2\) such that \(B \subseteq B'\). Then, we say that \(P_1\) is \emph{finer than} \(P_2\) (or equivalently, \(P_2\) is \emph{coarser than} \(P_1\)). Given \(P_1, P_2 \in Part(X)\), define the \emph{coarsest common refinement}, denoted by \(P_1 \curlywedge P_2\), as the coarsest partition \(P \in Part(X)\) that is finer than both \(P_1\) and \(P_2\). Likewise, define the \emph{finest common coarsening}, denoted by \(P_1 \curlyvee P_2\), as the finest partition \(P\) that is coarser than both \(P_1\) and \(P_2\). Recall that \((Part(X), \preceq, \curlyvee, \curlywedge)\) is a complete lattice where the top (coarsest) element is \(\{X\}\) and the bottom (finest) element is \(\{\{x\}\mid x \in X\}\). \section{Automata Constructions from Congruences}\label{sec:automataConstructions} We will consider equivalence relations on \(\Sigma^*\) (and their corresponding partitions) with good properties w.r.t. concatenation. An equivalence relation \(\sim\) is a \emph{right (resp. left) congruence} if{}f for all \(u,v \in Σ^*\), we have that \(u \sim v \Rightarrow ua\sim va\), for all \(a \in \Sigma\) (resp. \(u \sim v \Rightarrow au \sim av\)). We will denote right congruences (resp. left congruences) by \(\sim^{r}\) (resp. \(\sim^{\ell}\)). The following lemma gives a characterization of right and left congruences. \begin{restatable}{lemmaR}{CongruencePbwComplete}\label{lemma:CongruencePbwComplete} The following properties hold: \begin{enumerate} \item \(\sim^{r}\) is a right congruence if{}f \(P_{\sim^{r}}(v)u \subseteq P_{\sim^{r}}(vu)\), for all \(u,v \in \Sigma^*\). \item\(\sim^{\ell}\) is a left congruence if{}f \(uP_{\sim^{\ell}}(v) \subseteq P_{\sim^{\ell}}(uv)\), for all \(u,v \in \Sigma^*\). \end{enumerate} \end{restatable} \vspace{4pt} Given a right congruence \(\sim^{r}\) and a regular language \(L \subseteq \Sigma^*\) such that \(P_{\sim^{r}}\) represents precisely \(L\), i.e., \(P_{\sim^{r}}(L) = L\), the following automata construction recognizes exactly the language \(L\)~\cite{Khoussainov2001}. \begin{definition}[Automata construction \(\mathsf{H}^{r}(\sim^{r}, L)\)] \label{def:right-const} Let \(\sim^{r}\) be a right congruence and let \(P_{\sim^{r}}\) be the partition induced by \(\sim^{r}\). Let \(L \subseteq \Sigma^*\) be a language. Define the automaton \(\mathsf{H}^{r}(\sim^{r}, L)=\linebreak (Q, \Sigma, \delta, I, F)\) where \(Q = \{P_{\sim^{r}}(u) \mid u \in \Sigma^*\}\), \(I = \{P_{\sim^{r}}(\varepsilon) \}\), \(F = \{P_{\sim^{r}}(u) \mid u \in L\}\), and \(\delta(P_{\sim^{r}}(u), a) = P_{\sim^{r}}(v)\) if{}f \(P_{\sim^{r}}(u)a \subseteq P_{\sim^{r}}(v)\), for all \(u,v \in \Sigma^*\) and \(a \in \Sigma\). \end{definition} \begin{remark} \label{remark:deterministic} Note that \(\mathsf{H}^{r}(\sim^{r}, L)\) is \emph{finite} since we assume \(\sim^{r}\) is of finite index. Note also that \(\mathsf{H}^{r}(\sim^{r}, L)\) is a complete \emph{deterministic} finite-state automaton since, for each \(u \in \Sigma^*\) and \(a \in \Sigma\), there exists \emph{exactly one} block \(P_{\sim^{r}}(v)\) such that \(P_{\sim^{r}}(u)a \subseteq P_{\sim^{r}}(v)\), which is \(P_{\sim^{r}}(ua)\). Finally, observe that \(\mathsf{H}^{r}(\sim^{r}, L)\) possibly contains empty states but no state is unreachable. \end{remark} \begin{restatable}{lemmaR}{HrGeneratesL} \label{lemma: HrGeneratesL} Let \(\sim^{r}\) be a right congruence and let \(L\subseteq \Sigma^*\) be a language such that \(P_{\sim^{r}}(L) = L\). Then \(\lang{\mathsf{H}^{r}(\sim^{r}, L)} = L\). \end{restatable} Due to the left-right duality between \(\sim^{\ell}\) and \(\sim^{r}\), we can give a similar automata construction such that, given a left congruence \(\sim^{\ell}\) and a language \(L \subseteq \Sigma^*\) with \(P_{\sim^{\ell}}(L) = L\), recognizes exactly the language \(L\). \begin{definition}[Automata construction \(\mathsf{H}^{\ell}(\sim^{\ell}, L)\)] \label{def:left-const} Let \(\sim^{\ell}\) be a left congruence and let \(P_{\sim^{\ell}}\) be the partition induced by \(\sim^{\ell}\). Let \(L \subseteq \Sigma^*\) be a language. Define the automaton \(\mathsf{H}^{\ell}(\sim^{\ell}, L)=\linebreak (Q, \Sigma, \delta, I, F)\) where \(Q = \{P_{\sim^{\ell}}(u) \mid u \in \Sigma^*\}\), \(I = \{ P_{\sim^{\ell}}(u) \mid u \in L \}\), \(F = \{P_{\sim^{\ell}}(\varepsilon)\}\), and \( P_{\sim^{\ell}}(v) \in \delta(P_{\sim^{\ell}}(u), a)\) if{}f \(aP_{\sim^{\ell}}(v) \subseteq P_{\sim^{\ell}}(u)\), for all \(u,v \in \Sigma^*\) and \(a \in \Sigma\). \end{definition} \begin{remark} \label{remark:co-deterministic} In this case, \(\mathsf{H}^{\ell}(\sim^{\ell}, L)\) is a co-complete \emph{co-deterministic} finite-state automaton since, for each \(v \in \Sigma^*\) and \(a \in \Sigma\), there exists \emph{exactly one} block \(P_{\sim^{\ell}}(u)\) such that \linebreak\(aP_{\sim^{\ell}}(v) \subseteq P_{\sim^{\ell}}(u)\), which is \(P_{\sim^{\ell}}(av)\). Finally, observe that \(\mathsf{H}^{\ell}(\sim^{\ell}, L)\) possibly contains unreachable states but no state is empty. \end{remark} \begin{restatable}{lemmaR}{HlgeneratesL} \label{lemma:HlgeneratesL} Let \(\sim^{\ell}\) be a left congruence and let \(L\subseteq \Sigma^*\) be a language such that \(P_{\sim^{\ell}}(L) = L\). Then \(\lang{\mathsf{H}^{\ell}(\sim^{\ell}, L)} = L\). \end{restatable} Lemma~\ref{lemma:AutomataPartitionleftRightReverse} shows that \(\mathsf{H}^\ell\) and \(\mathsf{H}^r\) inherit the left-right duality between \(\sim^{\ell}\) and \(\sim^{r}\). \begin{restatable}{lemmaR}{AutomataPartitionleftRightReverse} \label{lemma:AutomataPartitionleftRightReverse} Let \(\sim^{r}\) and \(\sim^{\ell}\) be a right and left congruence respectively, and let \(L \subseteq \Sigma^*\) be a language. If the following property holds \begin{equation}\label{eq:AutomataPartitionleftRightReverse} u \sim^{r} v \Leftrightarrow u^R \sim^{\ell} v^R \end{equation} then \(\mathsf{H}^{r}(\sim^{r}, L) \) is isomorphic to \( \left(\mathsf{H}^{\ell}(\sim^{\ell}, L^R)\right)^R\). \end{restatable} \section{Language-based Congruences and their Approximation using NFAs}\label{sec:congruences} \label{sec: Languages} Given a language \(L \subseteq \Sigma^*\), we recall the following equivalence relations on \(\Sigma^*\), which are often denoted as \emph{Nerode's equivalence relations} (e.g., see \cite{Khoussainov2001}). \begin{definition}[Language-based Equivalences]\label{def:language} Let \(u,v \in \Sigma^*\) and let \(L \subseteq \Sigma^*\) be a language. Define: \begin{align} u \sim^{r}_{L} v & \Leftrightarrow u^{-1}L = v^{-1}L & \quad \text{\emph{Right-}language-based Equivalence}\label{eq:Rlanguage} \\ u \sim^{\ell}_{L} v & \Leftrightarrow Lu^{-1} = Lv^{-1} & \quad \text{\emph{Left-}language-based Equivalence} \label{eq:Llanguage} \end{align} \end{definition} Note that the right and left language-based equivalences defined above are, respectively, right and left \emph{congruences} (for a proof, see Lemma~\ref{lemma:lang-cong} in the Appendix). Furthermore, when \(L\) is a regular language, \(\rr_{L}\) and \(\rl_{L}\) are of \emph{finite index} \cite{Buchi89,Khoussainov2001}. Since we are interested in congruences of finite index (or equivalently, finite partitions), we will always assume that \(L\) is a regular language over \(\Sigma\). The following result states that, given a language \(L\), the right Nerode's equivalence induces the coarsest partition of \(\Sigma^*\) which is a right congruence and precisely represents \(L\). \begin{lemma}[de Luca and Varricchio~\cite{deluca2011}] \label{lemma:Varricchio} Let \(L\subseteq \Sigma^*\) be a regular language. Then, \[P_{\rr_{L}} = \bigcurlyvee \{P_{\sim^{r}} \mid \; \sim^{r} \text{is a right congruence and } P_{\sim^{r}}(L) = L\} \enspace .\] \end{lemma} In a similar way, one can prove that the same property holds for the left Nerode's equivalence. Therefore, as we shall see, applying the construction \(\mathsf{H}\) to these equivalences yields minimal automata. However, computing them becomes unpractical since languages are possibly infinite, even if they are regular. Thus, we will consider congruences based on the states of the NFA-representation of the language which induce finer partitions of \(\Sigma^*\) than Nerode's equivalences. In this sense, we say that the automata-based equivalences \emph{approximate} Nerode's equivalences. \begin{definition}[Automata-based Equivalences] \label{def:automataEquiv} Let \(u,v \in\Sigma^*\) and let \(\mathcal{N} = (Q, \Sigma, \delta, I, F)\) be an NFA. Define: \begin{align} u \rr_{\cN} v & \Leftrightarrow \post^{\mathcal{N}}_u(I) = \post^{\mathcal{N}}_v(I) & \quad \text{\emph{Right-}automata-based Equivalence}\label{eq:RState} \\ u \rl_{\cN} v & \Leftrightarrow \pre^{\mathcal{N}}_u(F) = \pre^{\mathcal{N}}_v(F) & \quad \text{\emph{Left-}automata-based Equivalence} \label{eq:LState} \end{align} \end{definition} Note that the right and left automata-based equivalences defined above are, respectively, right and left \emph{congruences} (for a proof, see Lemma~\ref{lemma:automata-cong} in the Appendix). Furthermore, they are of \emph{finite index} since each equivalence class is represented by a subset of states of \(\mathcal{N}\). The following result gives a sufficient and necessary condition for the language-based (Definition~\ref{def:language}) and the automata-based equivalences (Definition~\ref{def:automataEquiv}) to coincide. \begin{restatable}{lemmaR}{languageEqualPost} \label{lemma:languageEqualPost} Let \(\mathcal{N} = (Q,\Sigma,\delta,I,F)\) be an automaton with \(L = \lang{\mathcal{N}}\). Then, \begin{equation}\label{eq:RightSetsDisjoint} \mathord{\rr_{L}} = \mathord{\rr_{\cN}} \enspace \text{ if{}f } \enspace \forall u,v \in \Sigma^*, \; W_{\post_{u}^{\mathcal{N}}(I),F}^{\mathcal{N}} = W_{\post_{v}^{\mathcal{N}}(I),F}^{\mathcal{N}} \Leftrightarrow \post_{u}^{\mathcal{N}}(I) = \post_{v}^{\mathcal{N}}(I)\enspace . \end{equation} \end{restatable} \subsection{Automata Constructions} In what follows, we will use \(\cF{}\) and \(\cG{}\) to denote the construction \(\mathsf{H}\) when applied, respectively, to the language-based congruences induced by a regular language and the automata-based congruences induced by an NFA. \begin{definition}\label{def:FG} Let \(\mathcal{N}\) be an NFA generating the language \(L = \lang{\mathcal{N}}\). Define: \begin{align*} \cF{r}(L) & ≝ \mathsf{H}^{r}(\rr_{L}, L) & \cG{r}(\mathcal{N}) & ≝ \mathsf{H}^{r}(\rr_{\cN}, L) \\ \cF{\ell}(L) & ≝ \mathsf{H}^{\ell}(\rl_{L}, L) & \cG{\ell}(\mathcal{N}) & ≝ \mathsf{H}^{\ell}(\rl_{\cN}, L) \enspace . \end{align*} \end{definition} Given an NFA \(\mathcal{N}\) generating the language \(L=\lang{\mathcal{N}}\), all constructions in the above definition yield automata generating \(L\). However, while the constructions using the right congruences result in DFAs, the constructions relying on left congruences result in co-DFAs. Furthermore, since the pairs of relations~\eqref{eq:Rlanguage}-\eqref{eq:Llanguage} and~\eqref{eq:RState}-\eqref{eq:LState}, from Definition~\ref{def:language} and~\ref{def:automataEquiv} respectively, are dual, i.e., they satisfy the hypothesis of Lemma~\ref{lemma:AutomataPartitionleftRightReverse}, it follows that \(\cF{\ell}(L)\) is isomorphic to \((\cF{r}(L^R))^R\) and \(\cG{\ell}(\mathcal{N})\) is isomorphic to \((\cG{r}(\mathcal{N}^R))^R\). On the other hand, since \(\cF{r}\) relies on the language-based congruences, the resulting DFA is minimal, which is not guaranteed to occur with \(\cG{r}\). This easily follows from the fact that the states of the automata constructions are the equivalence classes of the given congruences and there is no right congruence (representing \(L\) precisely) that is coarser than the right Nerode's equivalence (see Lemma \ref{lemma:Varricchio}). % Finally, since every co-deterministic automaton satisfies the right-hand side of Equation~\eqref{eq:RightSetsDisjoint}, it follows that determinizing (\(\cG{r}\)) a co-deterministic automaton (\(\cG{\ell}(\mathcal{N})\)) results in the minimal DFA (\(\cF{r}(\lang{\mathcal{N}})\)), as already proved by Sakarovitch~\cite[Proposition 3.13]{sakarovitch2009elements}. We formalize all these notions in Theorem~\ref{theoremF}. Finally, Figure~\ref{Figure:diagramAutomata} summarizes all these well-known connections between the automata constructions given in Definition \ref{def:FG}. \begin{restatable}{theoremR}{theoremF}\label{theoremF} Let \(\mathcal{N}\) be an NFA generating language \(L = \lang{\mathcal{N}}\). Then the following properties hold: \begin{alphaenumerate}% \item \(\lang{\cF{r}(L)} =\lang{\cF{\ell}(L)} = L = \lang{\cG{r}(\mathcal{N})} = \lang{\cG{\ell}(\mathcal{N})}\). \label{lemma:language-F} \item \(\cF{r}(L)\) is isomorphic to the minimal deterministic automaton for \(L\).\label{theorem:minimalDFAlanguage} \item \(\cG{r}(\mathcal{N})\) is isomorphic to \(\mathcal{N}^{D}\).\label{lemma:rightNDet} \item \(\cF{\ell}(L)\) is isomorphic to \((\cF{r}(L^R))^R\). \label{lemma:FlisomorphicRfrR} \item \(\cG{\ell}(\mathcal{N})\) is isomorphic to \((\cG{r}(\mathcal{N}^R))^R\).\label{lemma:AlRequalArNR} \item \(\cG{r}(\cG{\ell}(\mathcal{N}))\) is isomorphic to \(\cF{r}(L)\).\label{lemma:LS+RS=RN} \end{alphaenumerate} \end{restatable} \begin{figure}[!ht] \begin{minipage}[l]{0.42\textwidth} \begin{tikzcd}[column sep=normal, row sep=large] \mathcal{N} \ar[d, description, "R"',leftrightarrow] \ar[r, "\cG{\ell}"] \ar[rr, bend left=30, "\cF{r}"] & \cG{\ell}(\mathcal{N}) \ar[d, description, "R"',leftrightarrow] \ar[r, "\cG{r}"] & \cG{r}(\cG{\ell}(\mathcal{N})) \ar[d, description, "R"',leftrightarrow]\\ \mathcal{N}^R \ar[r, "\cG{r}"] \ar[rr, bend right=30, "\cF{\ell}"] & \cG{r}(\mathcal{N}^R) \ar[r, "\cG{\ell}"] & \cG{\ell}(\cG{r}(\mathcal{N}^R)) \end{tikzcd} \end{minipage}% \hspace{1.2cm} \begin{minipage}[r]{0.48\textwidth} The upper part of the diagram follows from Theorem~\ref{theoremF}~(\ref{lemma:LS+RS=RN}). Both squares of the diagram fo\-llow from Theorem~\ref{theoremF}~(\ref{lemma:AlRequalArNR}), which states that \(\cG{\ell}(\mathcal{N})\) is isomorphic to \((\cG{r}(\mathcal{N}^R))^R\). Finally, the bottom curved arc follows from Theorem~\ref{theoremF}~(\ref{lemma:FlisomorphicRfrR}). Incidentally, the diagram shows a new relation which follows from the left-right dualities between \(\rl_{L}\) and \(\rr_{L}\), and \(\rl_{\cN}\) and \(\rr_{\cN}\): \(\cF{\ell}(\lang{\mathcal{N}^R})\) is isomorphic to \(\cG{\ell}(\cG{r}(\mathcal{N}^R))\). \end{minipage} \caption{Relations between the constructions \(\cG{\ell},\cG{r},\cF{\ell}\) and \(\cF{r}\). Note that constructions \(\cF{r}\) and \(\cF{\ell}\) are applied to the language generated by the automaton in the origin of the labeled arrow, while constructions \(\cG{r}\) and \(\cG{\ell}\) are applied directly to the automaton.} \label{Figure:diagramAutomata} \end{figure} \section{A Congruence-based Perspective on Known Algorithms} \label{sec:Novel} We can find in the literature several well-known independent techniques for the construction of minimal DFAs. Some of these techniques are based on refining a state partition of an input DFA, such as Moore's algorithm~\cite{moore1956}, while others directly manipulate an input NFA, such as the double-reversal method~\cite{brzozowski1962canonical}. Now, we establish a connection between these algorithms through Theorem~\ref{theorem:minimalifreverseatomic}, which gives a necessary and sufficient condition on an NFA so that determinizing it yields the minimal DFA. \begin{lemma}\label{lemma:minimalifreverseatomic} Let \(\mathcal{N} = (Q,\Sigma,\delta,I,F)\) be an NFA with \(L=\lang{\mathcal{N}}\) and \(\rr_{L}=\rr_{\cN}\). Then \(\forall q \in Q,\; P_{\rr_{L}}(W_{I,q}^{\mathcal{N}}) = W_{I,q}^{\mathcal{N}}\). \end{lemma} \begin{proof} \begin{align*} P_{\rr_{L}}(W_{I,q}^{\mathcal{N}}) & = \quad \text{[By definition of \(P_{\rr_{L}}\)]}\\ \{w \in \Sigma^* \mid \exists u \in W_{I,q}^{\mathcal{N}}, \; w^{-1}L = u^{-1}L\} & = \quad \text{[Since \(\rr_{L} = \rr_{\cN}\)]} \\ \{w \in \Sigma^* \mid \exists u \in W_{I,q}^{\mathcal{N}}, \; \post_w^{\mathcal{N}}(I) = \post_u^{\mathcal{N}}(I)\} & \subseteq \quad \text{[\( u \in W_{I,q}^{\mathcal{N}} \iff q \in \post_u^{\mathcal{N}}(I)\)]}\\ \{w \in \Sigma^* \mid q \in \post_w^{\mathcal{N}}(I)\} & = \quad \text{[By definition of \(W_{I,q}^{\mathcal{N}}\)]}\\ W_{I,q}^{\mathcal{N}} \enspace . \end{align*} By reflexivity of \(\rr_{L}, \) we conclude that \(P_{\rr_{L}}(W_{I,q}^{\mathcal{N}}) = W_{I,q}^{\mathcal{N}} \). \end{proof} \begin{theorem}\label{theorem:minimalifreverseatomic} Let \(\mathcal{N} = (Q,\Sigma,\delta,I,F)\) be an NFA with \(L=\lang{\mathcal{N}}\). Then \(\cG{r}(\mathcal{N})\) is the minimal DFA for \(L\) if{}f \(\forall q \in Q,\; P_{\rr_{L}}(W_{I,q}^{\mathcal{N}}) = W_{I,q}^{\mathcal{N}}\). \end{theorem} \begin{proof} Assume \(\cG{r}(\mathcal{N})\) is minimal. Then \(P_{\rr_{\cN}}(u) = P_{\rr_{L}}(u)\) for all \(u \in \Sigma^*\), i.e. \(\mathord{\rr_{L}} = \mathord{\rr_{\cN}}\). It follows from Lemma~\ref{lemma:minimalifreverseatomic} that \(P_{\rr_{L}}(W_{I,q}^{\mathcal{N}}) = W_{I,q}^{\mathcal{N}} \). Now, assume that \(P_{\rr_{L}}(W_{I,q}^{\mathcal{N}}) = W_{I,q}^{\mathcal{N}}\), for each \(q \in Q\). Then, for every \(u \in \Sigma^*\), \[P_{\rr_{\cN}}(u) = \hspace{-5pt}\bigcap\limits_{\substack{q \in \post^{\mathcal{N}}_u(I)}} W_{I,q}^{\mathcal{N}} \; \cap \hspace{-5pt}\bigcap\limits_{\substack{q \notin \post^{\mathcal{N}}_u(I)}} (W_{I,q}^{\mathcal{N}})^c = \hspace{-5pt}\bigcap\limits_{\substack{q \in \post^{\mathcal{N}}_u(I)}} P_{\rr_{L}}(W_{I,q}^{\mathcal{N}}) \;\; \cap \hspace{-5pt}\bigcap\limits_{\substack{q \notin \post^{\mathcal{N}}_u(I)}} (P_{\rr_{L}}(W_{I,q}^{\mathcal{N}}))^c\] where the first equality follows by rewriting \(P_{\rr_{\cN}}(u) = \{v \in \Sigma^* \mid \post^{\mathcal{N}}_u(I) = \post^{\mathcal{N}}_v(I)\}\) with universal quantifiers, hence intersections, and the last equality follows from the initial assumption \(P_{\rr_{L}}(W_{I,q}^{\mathcal{N}}) = W_{I,q}^{\mathcal{N}} \). It follows that \(P_{\rr_{\cN}}(u)\) is a \emph{union} of blocks of \(P_{\rr_{L}}\). Recall that \(\rr_{L}\) induces the coarsest right congruence such that \(P_{\rr_{L}}(L)=L\) (Lemma \ref{lemma:Varricchio}). Since \(\rr_{\cN}\) is a right congruence satisfying \(P_{\rr_{\cN}}(L)=L\) then \(P_{\rr_{\cN}} \preccurlyeq P_{\rr_{L}}\). Therefore, \(P_{\rr_{\cN}}(u)\) necessarily corresponds to one single block of \(P_{\rr_{L}}\), namely, \(P_{\rr_{L}}(u)\). Since \(P_{\rr_{\cN}}(u) = P_{\rr_{L}}(u)\) for each \(u \in \Sigma^*\), we conclude that \(\cG{r}(\mathcal{N}) = \cF{r}(L)\). \end{proof} \subsection{Double-reversal Method} In this section we give a simple proof of the well-known double-reversal minimization algorithm of Brzozowski~\cite{brzozowski1962canonical} using Theorem~\ref{theorem:minimalifreverseatomic}. Note that, since \(\cG{r}(\mathcal{N})\) is isomorphic to \(\mathcal{N}^D\) by Theorem~\ref{theoremF}~(\ref{lemma:rightNDet}), the following result coincides with that of Brzozowski. \begin{theorem}[\cite{brzozowski1962canonical}]\label{theorem:DoubleReversal} Let \(\mathcal{N}\) be an NFA. Then \(\cG{r}((\cG{r}(\mathcal{N}^R))^R)\) is isomorphic to the minimal DFA for \(\lang{\mathcal{N}}\). \end{theorem} \begin{proof} Let \(L = \lang{\mathcal{N}}\). By definition, \(\mathcal{N}' = (\cG{r}(\mathcal{N}^R))^R\) is a co-DFA and, therefore, satisfies the condition on the right-hand side of Equation~\eqref{eq:RightSetsDisjoint}. It follows from Lemma~\ref{lemma:languageEqualPost} that \(\rr_{L}=\sim^{r}_{\mathcal{N}'}\) which, by Lemma~\ref{lemma:minimalifreverseatomic} and Theorem~\ref{theorem:minimalifreverseatomic}, implies that \(\cG{r}(\mathcal{N}')\) is minimal. \end{proof} Note that Theorem~\ref{theorem:DoubleReversal} can be inferred from Figure~\ref{Figure:diagramAutomata} by following the path starting at \(\mathcal{N}\), labeled with \(R-\cG{r}-R-\cG{r}\) and ending in \(\cF{r}(\lang{\mathcal{N}})\). \subsection{Generalization of the Double-reversal Method} Brzozowski and Tamm~\cite{brzozowski2014theory} generalized the double-reversal algorithm by defining a necessary and sufficient condition on an NFA which guarantees that the determinized automaton is minimal. They introduced the notion of \emph{atomic} NFA and showed that \(\mathcal{N}^D\) is minimal if{}f \(\mathcal{N}^R\) is atomic. We shall show that this result is equivalent to Theorem~\ref{theorem:minimalifreverseatomic} due to the left-right duality between the language-based equivalences (Lemma~\ref{lemma:AutomataPartitionleftRightReverse}). \begin{definition}[Atom~\cite{brzozowski2014theory}]\label{def:atom} Let \(L\) be a regular language \(L\). Let \(\{K_i \mid 0 \leq i \leq n-1\}\) be the set of left quotients of \(L\). An \emph{atom} is any non-empty intersection of the form \(\widetilde{K_0} \cap \widetilde{K_1} \cap \ldots \cap \widetilde{K_{n-1}}\), where each \(\widetilde{K_i}\) is either \(K_i\) or \(K_i^c\). \end{definition} This notion of atom coincides with that of equivalence class for the left language-based congruence \(\rl_{L}\). This was first noticed by Iván~\cite{Ivan16}. \begin{restatable}{lemma}{atoms}\label{eq:atoms} Let \(L\) be a regular language. Then for every \(u \in \Sigma^*\), \[P_{\rl_{L}}(u) = \bigcap\limits_{\substack{u \in w^{-1}L \\w \in \Sigma^* }} w^{-1}L \; \cap \bigcap\limits_{\substack{u \notin w^{-1}L \\w \in \Sigma^* }} (w^{-1}L)^c \enspace .\] \end{restatable} \begin{definition}[Atomic NFA~\cite{brzozowski2014theory}]\label{def:atomicNFA} An NFA \(\mathcal{N} = (Q,\Sigma,\delta,I,F)\) is \emph{atomic} if{}f for every state \(q \in Q\), the right language \(W_{q,F}^{\mathcal{N}}\) is a union of atoms of \(\lang{\mathcal{N}}\). \end{definition} It follows from Lemma~\ref{eq:atoms} that the set of atoms of a language \(L\) corresponds to the partition \(P_{\rl_{L}}\). Therefore, a set \(S \subseteq \Sigma^*\) is a union of atoms if{}f \(P_{\rl_{L}}(S)=S\). This property, together\linebreak with Definition~\ref{def:atomicNFA}, shows that an NFA \(\mathcal{N} = (Q,\Sigma,\delta,I,F)\) with \(L = \lang{\mathcal{N}}\) is \emph{atomic} if{}f \begin{equation}\label{eq:atomicNFAClosed} \forall q \in Q, \; P_{\rl_{L}}(W_{q,F}^{\mathcal{N}}) = W_{q,F}^{\mathcal{N}} \enspace . \end{equation} We are now in condition to give an alternative proof of the generalization of Brzozowski and Tamm~\cite{brzozowski2014theory} relying on Theorem~\ref{theorem:minimalifreverseatomic}. \begin{lemma}\label{lemma:atomiccoatomic} Let \(\mathcal{N}=(Q,\Sigma,\delta,I,F)\) be an NFA with \(L=\lang{\mathcal{N}}\). Then \(\mathcal{N}^R\) is atomic if{}f \(\cG{r}(\mathcal{N})\) is the minimal DFA for \(L\). \end{lemma} \begin{proof} Let \(\mathcal{N}^R=(Q,\Sigma,\delta_r,F,I)\) and \(L^R = \lang{\mathcal{N}^R}\). Then, \begin{align*} \forall q \in Q, \; P_{\sim^{\ell}_{L^R}}(W_{q,I}^{\mathcal{N}^R}) = W_{q,I}^{\mathcal{N}^R} &\iff \quad \text{[By \(A = B \Leftrightarrow A^R = B^R\)]} \\ \forall q \in Q, \; \left(P_{\sim^{\ell}_{L^R}}(W_{q,I}^{\mathcal{N}^R})\right)^R = \left(W_{q,I}^{\mathcal{N}^R}\right)^R &\iff \quad \text{[By \(u\rl_{L} v \Leftrightarrow u^R \sim^r_{L^R} v^R\)]} \\ \forall q \in Q, \; P_{\rr_{L}}\left(\left(W_{q,I}^{\mathcal{N}^R}\right)^R\right) = \left(W_{q,I}^{\mathcal{N}^R}\right)^R &\iff \quad \text{[By \(\left(W^{\mathcal{N}^R}_{q,I}\right)^R = W_{I,q}^{\mathcal{N}}\)]} \\ \forall q \in Q, \; P_{\rr_{L}}(W_{I,q}^{\mathcal{N}}) = W_{I,q}^{\mathcal{N}} \enspace. \end{align*} It follows from Theorem~\ref{theorem:minimalifreverseatomic} that \(\cG{r}(\mathcal{N})\) is minimal. \end{proof} We conclude this section by collecting all the conditions described so far that guarantee that determinizing an automaton yields the minimal DFA. \begin{corollary}\label{corol:detProducesMinimal} Let \(\mathcal{N}=(Q,\Sigma,\delta,I,F)\) be an NFA with \(L=\lang{\mathcal{N}}\). The following are equivalent: \begin{alphaenumerate}% \item \(\cG{r}(\mathcal{N})\) is minimal. \item \(\mathord{\rr_{\cN}} = \mathord{\rr_{L}}\). \item \(\forall u,v \in \Sigma^*, \; W_{\post_{u}^{\mathcal{N}}(I),F}^{\mathcal{N}} = W_{\post_{v}^{\mathcal{N}}(I),F}^{\mathcal{N}} \Leftrightarrow \post_{u}^{\mathcal{N}}(I) = \post_{v}^{\mathcal{N}}(I)\). \item \(\forall q \in Q,\; P_{\rr_{L}}(W_{I,q}^{\mathcal{N}}) = W_{I,q}^{\mathcal{N}} \). \label{lemma:atomic-minimal} \item \(\mathcal{N}^R\) is atomic. \end{alphaenumerate} \end{corollary} \subsection{Moore's Algorithm} \iffalse In what follows we use partitions in \(\Sigma^*\) induced by partitions on \(Q\) (instead of congruences). Note that congruences and the induced partitions are equivalent. We abuse of notation and refer to partitions induced by right congruences also as right congruences. \begin{definition} Let \(\mathcal{D} = (Q, \Sigma, \delta, I ,F)\) be a DFA. Define a \emph{state-partition w.r.t.} \(\mathcal{D}\), denoted by \(\mathcal{Q}_{\mathcal{D}}\), as any element of \(Part(Q)\). \end{definition} Note that, since \(\mathcal{D}\) is a DFA, the left languages of any pair of distinct sets of states of \(D\) is disjoint. Therefore, given a set-partition w.r.t. \(\mathcal{D}\), we can define a partition of \(\Sigma^*\) as follows. \begin{definition} Let \(\mathcal{D}\) be a DFA and let \(\mathcal{Q}_{\mathcal{D}}\) be a state-partition w.r.t. \(\mathcal{D}\). Define the partition \(P_{\mathcal{Q}_{\mathcal{D}}} \stackrel{\rm\scriptscriptstyle def}{=} \{W_{I,S}^{\mathcal{D}} \mid S \in \mathcal{Q}_{\mathcal{D}}\} \in Part(\Sigma^*)\). \end{definition} \begin{lemma} Let \(\mathcal{D}\) be a DFA and let \(\mathcal{Q}_{\mathcal{D}}^1\) and \(\mathcal{Q}_{\mathcal{D}}^2\) be two state-partitions w.r.t \(\mathcal{D}\). Then \(P_{\mathcal{Q}_{\mathcal{D}}^1 \curlyvee \mathcal{Q}_{\mathcal{D}}^2} = P_{\mathcal{Q}_{\mathcal{D}}^1} \bigcurlyvee P_{\mathcal{Q}_{\mathcal{D}}^2}\). \end{lemma} \begin{lemma} Let \(\mathcal{D}\) be a DFA with \(L = \lang{\mathcal{D}}\) and let \(\mathcal{Q}_{\mathcal{D}}\) be any state-partition w.r.t \(\mathcal{D}\). Then \[P_{\rr_{L}} = \bigcurlyvee \{P_{\mathcal{Q}_{\mathcal{D}}} \mid P_{\mathcal{Q}_{\mathcal{D}}} \text{ is a right congruence and } P_{\mathcal{Q}_{\mathcal{D}}}(L) = L\}\] \end{lemma} \begin{proof} Recall from Lemma~\ref{lemma:Varricchio} that \[P_{\rr_{L}} = \bigcurlyvee \{P_{\sim^{r}} \mid \; P_{\sim^{r}} \text{ is a right congruence and } P_{\sim^{r}}(L) = L\} \enspace .\] In what follows, we show that for every right congruence \(P_{\sim^{r}}\) satisfying \(P_{\sim^{r}}(L) = L\) there exists an state-partition \(\mathcal{Q}_{\mathcal{D}}\) such that \( P_{\sim^{r}} \preceq P_{\mathcal{Q}_{\mathcal{D}}}\) and \(P_{\mathcal{Q}_{\mathcal{D}}}\) is a right congruence satisfying \(P_{\mathcal{Q}_{\mathcal{D}}} (L)= L\). Let \(P_{\sim^{r}}\) be a right-congruence and define \[\mathcal{Q}_{\mathcal{D}} \stackrel{\rm\scriptscriptstyle def}{=} \bigcurlyvee \{\post_B^{\mathcal{D}}(I),(\post_B^{\mathcal{D}}(I))^c \mid B \in P_{\sim^{r}}\} \enspace .\] By definition, every \(B \in P_{\mathcal{Q}_{\mathcal{D}}}\) is of the form \(W_{I,S}^{\mathcal{D}}\) for some \(S \in \mathcal{Q}_{\mathcal{D}}\). On the other hand, for every \(S \in \mathcal{Q}_{\mathcal{D}}\) there exists \(B' \in P_{\sim^{r}}\) such that \(\post_{B'}^{\mathcal{D}}(I) \subseteq S\). Therefore, for every \(B \in P_{\mathcal{Q}_{\mathcal{D}}}\) there exists \(B' \in P_{\sim^{r}}\) such that \(\post_{B'}^{\mathcal{D}}(I) \subseteq B\). It follows that \(P_{\sim^{r}} \preceq P_{\mathcal{Q}_{\mathcal{D}}}\). Now we show that \(\cP_{\mathcal{Q}_{\mathcal{D}}}\) is a right congruence. By definition, for every \(B \in \cP_{\mathcal{Q}_{\mathcal{D}}}\) there exists \(S \in \mathcal{Q}_{\mathcal{D}}\) such that \(B = W_{I,S}^{\mathcal{D}}\). On the other hand, every \(S \in \mathcal{Q}_{\mathcal{D}}\) satisfies \(S =\bigcup_{B \in P_{\sim^{r}}, B \subseteq W_{I,S}^{\mathcal{D}}} \post_B^{\mathcal{D}}(I)\). Therefore, for every \(u \in W_{I,S}^{\mathcal{D}}(I)\) we have that \(u \in B\) for some \(B \in P_{\sim^{r}}\). Since \(P_{\sim^{r}}\) is a right congruence, there exists \(B' \in P_{\sim^{r}}\) such that \(Ba \subseteq B'\). Again, by definition of \(\mathcal{Q}_{\mathcal{D}}\) there exists \(S' \in \mathcal{Q}_{\mathcal{D}}\) such that \(S' \supseteq \bigcup_{B \in P_{\sim^{r}}, B \subseteq W_{I,S}^{\mathcal{D}}, Ba \subseteq B'} \post_{B'}^{\mathcal{D}}(I)\). It is straightforward to check that \(ua \in W_{I,S'}^{\mathcal{D}}\). Finally, it remains to show that \(P_{\mathcal{Q}_{\mathcal{D}}}(L) = L\). \end{proof} \begin{corollary} Let \(\mathcal{D} = (Q, \Sigma, \delta, I, F)\) be a DFA with \(L = \lang{\mathcal{D}}\) and let \(\mathcal{Q}^{\mathcal{D}} \stackrel{\rm\scriptscriptstyle def}{=} \bigcurlyvee \{\mathcal{Q} \mid \mathcal{Q} \text{ is a right congruence} \text{ and } \mathcal{Q}(F) = F\}\) then \(P_{\rr_{L}} = P_{\mathcal{Q}^D}\). Therefore \(\mathsf{H}^r(P_{\mathcal{Q}_{\mathcal{D}}},L)\) is the minimal DFA for \(L\). \end{corollary} \fi Given a DFA \(\mathcal{D}\), Moore~\cite{moore1956} builds the minimal DFA for the language \(L=\lang{\mathcal{D}}\) by removing unreachable states from \(\mathcal{D}\) and then performing a stepwise refinement of an initial partition of the set of reachable states of \(\mathcal{D}\). Since we are interested in the refinement step, in what follows we assume that all DFAs have no unreachable states. In this section, we will describe Moore's state-partition \(\mathcal{Q}^{\mathcal{D}}\) and the right-language-based partition \(P_{\rr_{L}}\) as greatest fixpoint computations and show that there exists an isomorphism between the two at each step of the fixpoint computation. In fact, this isomorphism shows that Moore's DFA \(M\) satisfies \(P_{\rr_{L}}(W_{I,q}^{M}) = W_{I,q}^{M}\) for every state \(q\). Thus, by Theorem~\ref{theorem:minimalifreverseatomic}, \(M\) is isomorphic to \(\cF{r}(\lang{\mathcal{D}})\). First, we give Moore's algorithm which computes the state-partition that is later used to define Moore's DFA. \renewcommand{\fnum@algocf}{\AlCapSty{\AlCapFnt\algorithmcfname}} \begin{algorithm} \SetAlgorithmName{Moore's Algorithm}{} \SetSideCommentRight \caption{Algorithm for constructing Moore's partition.}\label{alg:Moore} \KwData{DFA \(\mathcal{D}=\tuple{Q,\Sigma,\delta,I,F}\) with \(L = \lang{\mathcal{D}}\).} \KwResult{\(\mathcal{Q}^{\mathcal{D}} \in Part(Q)\).} \(\mathcal{Q}^{\mathcal{D}} := \{F,F^c\}\), \(\mathcal{Q}' := \varnothing\)\; \While{\(\mathcal{Q}^{\mathcal{D}}\neq \mathcal{Q}'\)} { \(\mathcal{Q}' := \mathcal{Q}^{\mathcal{D}}\)\; \ForAll{\(a\in \Sigma\)}{ \(\mathcal{Q}_a := \bigcurlywedge_{p \in \mathcal{Q}^{\mathcal{D}}} \{\pre_a^{\mathcal{D}}(p), (\pre_a^{\mathcal{D}}(p))^c\}\)\; } \(\mathcal{Q}^{\mathcal{D}} := \mathcal{Q}^{\mathcal{D}} \curlywedge \bigcurlywedge_{a \in \Sigma} \mathcal{Q}_a\)\; } \Return \(\mathcal{Q}^{\mathcal{D}}\)\; \end{algorithm} \vspace{-5pt} \begin{definition}[Moore's DFA] \label{def:MooreDFA} Let \(\mathcal{D} = (Q,\Sigma,\delta,I,F)\) be a DFA, and let \(\mathcal{Q}^{\mathcal{D}}\) be the partition of \(Q\) built by using Moore's algorithm. \emph{Moore's DFA} for \(\lang{\mathcal{D}}\) is \(M = (Q^M,\Sigma,\delta^M,I^M,F^M)\) where \(Q^M = \mathcal{Q}^{\mathcal{D}}\), \(I^M = \{\mathcal{Q}^{\mathcal{D}}(q) \mid q \in I\}\), \(F^M = \{\mathcal{Q}^{\mathcal{D}}(q) \mid q \in F\}\) and, for each \( S,S' \in Q^M\) and \(a \in \Sigma\), we have that \(\delta^M(S,a) = S'\) if{}f \(\exists q \in S, q' \in S'\) with \(\delta(q,a) = q'\). \end{definition} Next, we describe Moore's state-partition \(\mathcal{Q}^{\mathcal{D}}\) and the right-language-based partition \(P_{\rr_{L}}\) as greatest fixpoint computations and show that there exists an isomorphism between the two at each step of the fixpoint computation. \begin{definition}[Moore's state-partition] \label{def:state-partition} Let \(\mathcal{D}=(Q,\Sigma,\delta,I,F)\) be a DFA. Define \emph{Moore's state-partition w.r.t.} \(\mathcal{D}\), denoted by \(\mathcal{Q}^{\mathcal{D}}\), as follows. \[\mathcal{Q}^{\mathcal{D}} \stackrel{\rm\scriptscriptstyle def}{=} \gfp(\lambda X. \bigcurlywedge\limits_{\substack{a \in \Sigma, S \in X}} \{\pre_a(S), (\pre_a(S))^c\} \curlywedge \{F, F^c\}) \enspace .\] \end{definition} On the other hand, by Theorem~\ref{theoremF}~(\ref{theorem:minimalDFAlanguage}), each state of the minimal DFA for \(L\) corresponds to an equivalence class of \(\rr_{L}\). These equivalence classes can be defined in terms of non-empty intersections of complemented or uncomplemented right quotients of \(L\). \begin{restatable}{lemmaR}{lemmacoatoms}\label{lemma:coatoms} Let \(L\) be a regular language. Then, for every \(u \in \Sigma^*\), \[P_{\rr_{L}}(u) = \bigcap\limits_{\substack{u \in Lw^{-1}\\w \in \Sigma^* }} Lw^{-1} \; \cap \bigcap\limits_{\substack{u \notin Lw^{-1}\\w \in \Sigma^* }} (Lw^{-1})^c\enspace .\] \end{restatable} It follows from Lemma~\ref{lemma:coatoms} that \(P_{\rr_{L}} = \bigcurlywedge_{w \in \Sigma^*}\{Lw^{-1},(Lw^{-1})^c\}\), for every regular language \(L\) . Thus, \(P_{\rr_{L}}\) can also be obtained as a greatest fixpoint computation as follows. \begin{restatable}{lemmaR}{lemmafixpointcoatoms}\label{lemma:fixpointcoatoms} Let \(L\) be a regular language. Then \begin{equation}\label{eq:fixpointcoatoms} P_{\rr_{L}} = \gfp(\lambda X. {\bigcurlywedge\limits_{\substack{a \in \Sigma, B \in X}}} \{Ba^{-1}, (Ba^{-1})^c\} \curlywedge \{L, L^c\}) \enspace . \end{equation} \end{restatable} The following result shows that, given a DFA \(\mathcal{D}\) with \(L=\lang{\mathcal{D}}\), there exists a partition isomorphism between \(\mathcal{Q}^{\mathcal{D}}\) and \(P_{\rr_{L}}\) at each step of the fixpoint computations given in Definition~\ref{def:state-partition} and Lemma~\ref{lemma:fixpointcoatoms} respectively. \begin{theorem}\label{theorem:postisomorphism} Let \(\mathcal{D}=(Q,\Sigma,\delta,I,F)\) be a DFA with \(L = \lang{\mathcal{D}}\) and let \(\varphi: \wp(Q) \rightarrow \wp(\Sigma^*)\) be a function defined by \(\varphi(S) \stackrel{\rm\scriptscriptstyle def}{=} W_{I, S}^{\mathcal{D}}\). Let \(\mathcal{Q}^{\mathcal{D}(n)}\) and \(P_{\rr_{L}}^{(n)}\) be the \(n\)-th step of the fixpoint computation of \(\mathcal{Q}^{\mathcal{D}}\) (Definition~\ref{def:state-partition}) and \(P_{\rr_{L}}\) (Lemma~\ref{lemma:fixpointcoatoms}), respectively. Then, \(\varphi\) is an isomorphism between \(\mathcal{Q}^{\mathcal{D}(n)}\) and \(P_{\rr_{L}}^{(n)}\) for each \(n \geq 0\). \end{theorem} \begin{proof} In order to show that \(\varphi\) is a partition isomorphism, it suffices to prove that \(\varphi\) is a bijective mapping between the partitions. We first show that \(\varphi(\mathcal{Q}^{\mathcal{D}(n)}) = P_{\rr_{L}}^{(n)}\), for every \(n \geq 0\). Thus, the mapping \(\varphi\) is surjective. Secondly, we show that \(\varphi\) is an injective mapping from \(\mathcal{Q}^{\mathcal{D}(n)}\) to \(P_{\rr_{L}}^{(n)}\). Therefore, we conclude that \(\varphi\) is a bijection. To show that \(\varphi(\mathcal{Q}^{\mathcal{D}(n)}) = P_{\rr_{L}}^{(n)}\), for each \(n \geq 0\), we proceed by induction. \begin{itemize} \item \emph{Base case:} By definition, \(\mathcal{Q}^{\mathcal{D}(0)} = \{F,F^c\}\) and \(P_{\rr_{L}}^{(0)} = \{L, L^c\}\). Since \(\mathcal{D}\) is deterministic (and complete), it follows that \(\varphi(F) = W_{I,F}^{\mathcal{D}} = L\) and \(\varphi(F^c) = W_{I,F^c}^{\mathcal{D}} = L^c\). \item \emph{Inductive step:} Before proceeding with the inductive step, we show that the following equations hold for each \(a,b \in \Sigma\) and \(S, S_i, S_j \in \mathcal{Q}^{\mathcal{D}(n)}\) with \(n \geq 0\): \begin{align} \varphi(\pre_a(S)^c) = ((W_{I,S}^{\mathcal{D}})a^{-1})^c & \label{eq:varphicomplement} \\ \varphi(\pre_a(S_i) \cap \pre_b(S_j)) = (W_{I,S_i}^{\mathcal{D}})a^{-1} \cap (W_{I,S_j}^{\mathcal{D}})b^{-1}& \label{eq:varphicap} \enspace . \end{align} For each \(S \in \mathcal{Q}^{\mathcal{D}(n)} \) and \(a \in \Sigma\) we have that: \begin{align*} \varphi(\pre_a(S)^c) & = \quad \text{[By definition of \(\varphi\)]} \\ W_{I,\pre_a(S)^c}^{\mathcal{D}} & = \quad \text{[\(I = \{q_0\}\) and def. of \(W_{I,\pre_a(S)^c}^{\mathcal{D}}\)]} \\ \{w \in \Sigma^* \mid \exists q \in \pre_a(S)^c,\; q = \hat{\delta}(q_0, w)\} & = \quad \text{[\(\mathcal{D}\) is deterministic and complete]} \\ \{w \in \Sigma^* \mid \exists q \in \pre_a(S), \; q = \hat{\delta}(q_0, w)\}^c & = \quad \text{[By definition of \(\pre_a(S)\)]} \\ \{w \in \Sigma^* \mid \exists q \in S, \; q = \hat{\delta}(q_0, wa)\}^c & = \quad \text{[By definition of \((W_{I,S}^{\mathcal{D}})a^{-1}\)]} \\ ((W_{I, S}^{\mathcal{D}})a^{-1})^c \enspace . \end{align*} Therefore Equation~\eqref{eq:varphicomplement} holds at each step of the fixpoint computation. Consider now Equation~\eqref{eq:varphicap}. Let \(S_i, S_j \in \mathcal{Q}^{\mathcal{D}(n)}\). Then, \begin{align*} \varphi(\pre_{a}(S_i) \cap \pre_b(S_j)) & = \quad \text{[By Def. \(\varphi\)]} \\ W_{I,(\pre_{a}(S_i) \cap \pre_b(S_j))}^{\mathcal{D}} & = \quad \text{[\(I = \{q_0\}\) and def. \(W_{I,S}\)]} \\ \{w \in \Sigma^* \mid \exists q \in \pre_{a}(S_i) \cap \pre_b(S_j), q = \hat{\delta}(q_0,w)\} & = \quad \text{[By Def. of \(\cap \)]}\\ \{w \in \Sigma^* \mid \exists q \in \pre_{a}(S_i), \; q \in \pre_b(S_j), q = \hat{\delta}(q_0,w)\} & = \quad \text{[\(\mathcal{D}\) is deterministic]}\\ W_{I, \pre_a(S_i)}^{\mathcal{D}} \cap W_{I, \pre_b(S_j)}^{\mathcal{D}} & = \quad \text{[By Def. of \((W_{I,S}^{\mathcal{D}})a^{-1}\)]} \\ (W_{I, S_i}^{\mathcal{D}})a^{-1} \cap (W_{I, S_j})b^{-1} & \enspace . \end{align*} Therefore Equation~\eqref{eq:varphicap} holds at each step of the fixpoint computation. Let us assume that \(\varphi\left(\mathcal{Q}^{\mathcal{D}(n)}\right) = P_{\rr_{L}}^{(n)}\) for every \(n \leq k\) with \(k > 0\). Then, \begin{adjustwidth}{-0.6cm}{} \begin{align*} \varphi\bigl(\mathcal{Q}^{\mathcal{D}(k{+}1)}\bigr) & = \text{[By Def.~\ref{def:state-partition} with \(X = \mathcal{Q}^{\mathcal{D}(k)}\)]} \\ \varphi\bigl(\bigcurlywedge\limits_{\substack{a \in \Sigma, S \in X}} \{\pre_a(S), \pre_a(S)^c\} \curlywedge \{F, F^c\}\bigr) &= \text{[By Eqs.~\eqref{eq:varphicomplement},~\eqref{eq:varphicap} and def. of \(\bigcurlywedge\)]} \\ \bigcurlywedge\limits_{\substack{a \in \Sigma \\ \varphi(S) \in \varphi(X)}}\hspace{-5pt} \{(W_{I, S}^{\mathcal{D}})a^{-1}, {((W_{I, S}^{\mathcal{D}})a^{-1})}^c\} \curlywedge \{L, L^c\} &= \text{[By induction hypothesis, \(\varphi(X) = P_{\rr_{L}}^{(k)}\)]}\\[-6pt] \bigcurlywedge\limits_{\substack{a \in \Sigma, B \in X'}}\hspace{-5pt} \{Ba^{-1}, {(Ba^{-1})}^c\} \curlywedge \{L, L^c\} &= \text{[By Lemma~\ref{lemma:fixpointcoatoms} with \(X' = P_{\rr_{L}}^{(k)}\)]} \\[-6pt] P_{\rr_{L}}^{(k{+}1)} \enspace . \end{align*} \end{adjustwidth} \end{itemize} Finally, since \(\mathcal{D}\) is a DFA then, for each \(S_i, S_j \in \mathcal{Q}^{\mathcal{D}(n)}\)(\(n \geq 0\)) with \(S_i \neq S_j\) we have that \(W_{I, S_i}^{\mathcal{D}} \neq W_{I, S_j}^{\mathcal{D}}\), i.e., \(\varphi (S_i) \neq \varphi(S_j)\). Therefore, \(\varphi\) is an injective mapping. \end{proof} \begin{corollary} \label{cor:stepwise-invariant} Let \(\mathcal{D}\) be a DFA with \(L = \lang{\mathcal{D}}\). Let \(\mathcal{Q}^{\mathcal{D}(n)}\) and \(P_{\rr_{L}}^{(n)}\) be the \(n\)-th step of the fixpoint computation of \(\mathcal{Q}^{\mathcal{D}}\) and \(P_{\rr_{L}}\) respectively. Then, for each \(n \geq 0\), \[P_{\rr_{L}}^{(n)}(W_{I,S}^{\mathcal{D}}) = W_{I,S}^{\mathcal{D}}\enspace , \text{ for each \(S \in \mathcal{Q}^{\mathcal{D}(n)}\)} \enspace .\] \end{corollary} It follows that Moore's DFA \(M\), whose set of states corresponds to the state-partition at the end of the execution of Moore's algorithm, satisfies that \(\forall q \in Q^M,\; P_{\rr_{L}}(W_{I,q}^{M}) = W_{I,q}^{M}\) with \(L = \lang{M}\). By Theorem~\ref{theorem:minimalifreverseatomic}, we have that \(\cG{r}(M)( = M\), since \(M\) is a DFA) is minimal. \begin{restatable}{theoremR}{theoremMoore} \label{thm:Moore} Let \(\mathcal{D} \) be a DFA and \(M\) be Moore's DFA for \(\lang{\mathcal{D}}\) as in Definition~\ref{def:MooreDFA}. Then, \(M\) is isomorphic to \(\cF{r}(\lang{\mathcal{D}})\). \end{restatable} Finally, recall that Hopcroft~\cite{hopcroft1971} defined a DFA minimization algorithm which offers better performance than Moore's. The ideas used by Hopcroft can be adapted to our framework to devise a new algorithm from computing \(P_{\rr_{L}}\). However, by doing so, we could not derive a better explanation than the one provided by Berstel et al.~\cite{berstel2010minimization}. \section{Related Work and Conclusions}\label{sec:relatedWork} Brzozowski and Tamm~\cite{brzozowski2014theory} showed that every regular language defines a unique NFA, which they call \emph{átomaton}. The átomaton is built upon the minimal DFA \(\mathcal{N}^{DM}\) for the language, defining its states as non-empty intersections of complemented or uncomplemented right languages of \(\mathcal{N}^{DM}\), i.e., the atoms of the language. They also observed that the atoms correspond to intersections of complemented or uncomplemented left quotients of the language. Then they proved that the átomaton is isomorphic to the reverse automaton of the minimal deterministic DFA for the reverse language. Intuitively, the construction of the átomaton based on the right languages of the minimal DFA corresponds to \(\cG{\ell}(\mathcal{N}^{DM})\), while its construction based on left quotients of the language corresponds to \(\cF{\ell}(\lang{\mathcal{N}})\). \begin{corollary} \label{cor:atomaton} Let \(\mathcal{N}^{DM}\) be the minimal DFA for a regular language \(L\). Then, \begin{alphaenumerate} \item \(\cG{\ell}(\mathcal{N}^{DM})\) is isomorphic to the átomaton of \(L\).\label{cor:atomatonG} \item \(\cF{\ell}(L)\) is isomorphic to the átomaton of \(L\).\label{cor:atomatonF} \end{alphaenumerate} \end{corollary} In the same paper, they also defined the notion of \emph{partial átomaton} which is built upon an NFA \(\mathcal{N}\). Each state of the partial atomaton is a non-empty intersection of complemented or uncomplemented right languages of \(\mathcal{N}\), i.e., union of atoms of the language. Intuitively, the construction of the partial átomaton corresponds to \(\cG{\ell}(\mathcal{N})\). \begin{corollary} \label{cor:partial-atomaton} Let \(\mathcal{N}\) be an NFA. Then, \(\cG{\ell}(\mathcal{N})\) is isomorphic to the partial átomaton of \(\mathcal{N}\).\break \end{corollary} \vspace{-10pt} Finally, they also presented a number of results~\cite[Theorem 3]{brzozowski2014theory} related to the átomaton \(\mathcal{A}\) of a minimal DFA \(\mathcal{D}\) with \(L = \lang{\mathcal{D}}\): \begin{enumerate} \item \(\mathcal{A}\) is isomorphic to \(\mathcal{D}^{RDR}\).\label{enum:ADRDR} \item \(\mathcal{A}^R\) is the minimal DFA for \(L^R\) \item \(\mathcal{A}^D\) is the minimal DFA for \(L\). \item \(\mathcal{A}\) is isomorphic to \(\mathcal{N}^{RDMR}\) for every NFA \(\mathcal{N}\) accepting \(L\).\label{enum:ANRDMR} \end{enumerate} All these relations can be inferred from Figure~\ref{fig:DiagramResults} which connects all the automata constructions described in this paper together with the constructions introduced by Brzozowski and Tamm. For instance, property~\ref{enum:ADRDR} corresponds to the path starting at \(\mathcal{N}^{DM}\) (the minimal DFA for \(\lang{\mathcal{N}}\)), labeled with \(R - \cG{r} - R \), and ending in the átomaton of \(\lang{\mathcal{N}}\). On the other hand, property~\ref{enum:ANRDMR} corresponds to the path starting at \(\mathcal{N}\), labeled with \(R - \cF{r} - R\) and ending in the átomaton of \(\lang{\mathcal{N}}\). Finally, the path starting at \(\mathcal{N}\), labeled with \(R - \cG{r} - R \) and ending in the partial átomaton of \(\mathcal{N}\) shows that the later is isomorphic to \(\mathcal{N}^{RDR}\). \begin{figure}[!ht] \vspace{-7pt} \centering \begin{tikzcd}[column sep=huge, row sep=normal] \mathcal{N} \ar[r,"\cG{\ell};\; C.\ref{cor:partial-atomaton}", pos=0.6] \ar[d,"R",leftrightarrow] \ar[rr,"\cF{r}; \; T.\ref{theoremF}(\ref{theorem:minimalDFAlanguage})", bend left=25, near end] \ar[rrr,"\cF{\ell}; \;T.\ref{theoremF}(\ref{lemma:FlisomorphicRfrR})", bend left=25]& \begin{tabular}{c} Partial átomaton \\ of \(\mathcal{N}\)\end{tabular} \ar[r,"\cG{r}; \; T.\ref{theoremF}(\ref{lemma:rightNDet})"] \ar[d,"R",leftrightarrow] & \mathcal{N}^{DM} \ar[d,"R",leftrightarrow] \ar[r,"\cG{\ell};\;C.\ref{cor:atomaton}(\ref{cor:atomatonG})"] & \begin{tabular}{c} Átomaton \\ of \(\lang{\mathcal{N}}\)\end{tabular} \ar[d,"R",leftrightarrow] \ar[l,"\cG{r}; \; T.\ref{theoremF}(\ref{lemma:LS+RS=RN})"',bend right=25, pos=0.5] \\ \mathcal{N}^{R} \ar[r,"\cG{r}; \;T.\ref{theoremF}(\ref{lemma:rightNDet})"] \ar[rrr,"\cF{r}; \; T.\ref{theoremF}(\ref{theorem:minimalDFAlanguage})", bend right=25] \ar[rr,"\cF{\ell}; \;C.\ref{cor:atomaton}(\ref{cor:atomatonF})", bend right=24, pos=0.4] & \mathcal{N}^{RD} \ar[r,"\cG{\ell}; \; T.\ref{theoremF}(\ref{lemma:AlRequalArNR})"] & \begin{tabular}{c} Átomaton \\ of \(\lang{\mathcal{N}^{R}}\)\end{tabular} \ar[r,"\cG{r}; \; T.\ref{theoremF}(\ref{lemma:rightNDet})"] & \mathcal{N}^{RDM} \ar[l,"\cG{\ell};\;C.\ref{cor:atomaton}(\ref{cor:atomatonG})"',bend right=25, pos=0.6] \end{tikzcd} \vspace{-15pt} \caption{Extension of the diagram of Figure~\ref{Figure:diagramAutomata} including the átomaton and the partial átomaton. Recall that \(\mathcal{N}^{DM}\) is the minimal DFA for \(\lang{\mathcal{N}}\). The results referenced in the labels are those justifying the output of the operation.}\label{fig:DiagramResults} \vspace{-7pt} \end{figure} In conclusion, we establish a connection between well-known independent minimization methods through Theorem~\ref{theorem:minimalifreverseatomic}. Given a DFA, the left languages of its states form a partition on words, \(P\), and thus, each left language is identified by a state. Intuitively, Moore's algorithm merges states to enforce the condition of Theorem~\ref{theorem:minimalifreverseatomic}, which results in merging blocks of \(P\) that belong to the same Nerode's equivalence class. Note that Hopcroft's partition refinement method~\cite{hopcroft1971} achieves the same goal at the end of its execution though, stepwise, the partition computed may differ from Moore's. On the other hand, any co-deterministic NFA satisfies the right-hand side of Equation~\eqref{eq:RightSetsDisjoint} hence, by Lemma~\ref{lemma:minimalifreverseatomic}, satisfies the condition of Theorem~\ref{theorem:minimalifreverseatomic}. Therefore, the double-reversal method, which essentially determinizes a co-determinized NFA, yields the minimal DFA. Finally, the left-right duality (Lemma~\ref{lemma:AutomataPartitionleftRightReverse}) of the language-based equivalences shows that the condition of Theorem~\ref{theorem:minimalifreverseatomic} is equivalent to that of Brzozowski and Tamm~\cite{brzozowski2014theory}. Some of these connections have already been studied in order to offer a better understanding of Brzozowski's double-reversal method~\cite{Adamek2012,bonchi_algebra-coalgebra_2014,Champarnaud2002,Garcia2013}. In particular, Adámek et al.~\cite{Adamek2012} and Bonchi et al.~\cite{bonchi_algebra-coalgebra_2014} offer an alternative view of minimization and determinization methods in a uniform way from a category-theoretical perspective. In contrast, our work revisits these well-known minimization techniques relying on simple language-theoretical notions.
{'timestamp': '2019-06-28T02:14:45', 'yymm': '1906', 'arxiv_id': '1906.06194', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06194'}
arxiv
\section{Introduction} \label{sec:introduction} Traditionally, personal mobility data were solicited via small-scale surveys (1-5\% sample) and governments would take the responsibility to secure the personal information before sharing for public use. Nowadays, smartphones, cellphone towers, Wi-Fi hotspots, traffic sensors, among others, can passively solicit detailed mobility data of the urban population. Processing and analyzing passively as well as actively solicited data has the potential to aid governments and researchers to better understand human mobility for designing smarter, demand-driven, reliable and secure transportation systems. To fully exploit the potential of passively solicited large-scale data, privacy and security challenges need to be addressed. Passively solicited data include sensitive personal information like GPS logs or trip and activity habits. Therefore, guarding people's privacy and securing their information from untrusted parties is of utmost importance. One of the highest priorities companies are expected to have is the protection of people’s personal information that the companies may collect. Nevertheless, breaches happen whether it is due to poorly designed information systems or hackers finding clever ways of breaching these systems. In recent years, cyber-security breaches have occurred all around the globe and transportation systems are not an exception. In 2015 a group of civic hackers deciphered and exposed the unstandardized bus system location data of Baltimore~\cite{Rector2015}. In 2016 the San Francisco transit was hacked to give free access to commuters for two days~\cite{Stewart2016}. During the same year, information of 57 million Uber customers and drivers were leaked~\cite{Wong2017}. Data transparency is an important issue in the privacy of individuals. Various services that collect our transportation data fail to clearly explain where or with whom our data are being shared. For example, the Waze app states in the Terms of Service\footnote{\url{https://www.waze.com/en-GB/legal/tos}} that ``...(Waze will) share personal information with companies or organizations connected or affiliated with Waze...''. So all the information collected by Waze could be shared with other organizations associated with Waze. However, the Terms of Service do not make it clear if the user can track with whom their information has been shared. Another point related to privacy is the access control of the information that is provided by the users. It was recently discovered that Google keeps collecting user location data even if they explicitly deactivate the tracking system in their mobiles~\cite{Nakashima2018}. Another example of disclosing information without the user’s consent is the infamous Facebook-Cambridge Analytica scandal~\cite{Cadwalladr2018}. The General Data Protection Regulation\footnote{\url{https://eugdpr.org/}} (GDPR) is a step forward for privacy. Although the GDPR is valid only in the European Union, it is still expected to push multinational companies to be more transparent on how they manage people’s private information. In the authors opinion, no matter how many rules and fines governments apply, given the current centralized ways of collecting people’s data, some entities will always find a loophole in legislation or hackers will be able to tamper with these centralized data systems. In addition to laws, individuals have to have total control and ownership of their information. We need to be the guardians and responsible of our own privacy, unfortunately nowadays we have to trust third parties for that. Distributed ledger technologies like blockchain have the potential to give the people full control of their information, protect individual's personal mobility information and guard their privacy. The technology is difficult to tamper with and transactions are secure as well as transparent to all parties, including the individuals who generated the data. A blockchain is a distributed database, data structure or shared ledger that maintains a list of transaction records, which cannot be altered unless a consensus in the network is reached using an algorithm~\cite{Kim2018}. Some of the most common algorithms in public blockchains are proof-of-work used by Bitcoin and proof-of-stake used by Peercoin, while close blockchains, like Hyperledger, use a byzantine fault tolerance variant. The blockchain is formed by timestamped blocks containing transactions and where each block is permanently linked to a previous block~\cite{Nakamoto2008}. Consensus algorithms together with linked blocks make it very hard to tamper with the blockchain. The network is run by a set of participants so that no single entity controls the flow of information, and nodes can transact with other nodes as long as both nodes agree to some terms, so each node has full control of the assets they possess. As such, blockchain presents a solution for developing a network for transportation data and associated services, where people own their mobility data, all the transactions are transparent (a public ledger is available to the interested parties in the network), democratic (a consensus must be reached to accept any transaction) and secure (linked blocks make it difficult to tamper with the network). In this paper a multi-layered blockchain framework for mobility data transactions is proposed. The main objective is to secure the collected data and to maintain the privacy of the individuals. The rest of the paper is organized as follows: We first introduce the background on how blockchain can solve data management problems and privacy issues in the context of mobility data. We describe the six layer model of the Blockchain framework for smart mobility data transactions. Each layer is described and discussions on different properties of the blockchain are presented. Data shared on the network as well as the rules of participation are discussed. Details of an implementation for the mobility data sharing is outlined and the performance is analyzed. At the end of the paper, a case study and concluding discussion are presented. \section{Background} \label{sec:brackground} {The distributed data structure of the blockchain was originally developed for the Bitcoin currency ~\cite{Nakamoto2008} as a mechanism to maintain public transaction ledgers. However, in recent years blockchain has gained tremendous attention in other domains e.g. food, pharmacy, real-estate, logistics, etc. This interest is due to blockchain's ability to create secure and private networks where accounting is at the core and no single organization is in control of the transactions as well as the data. Nowadays, distributed ledger technologies are actively developed by industry as well as academia for a range of financial and non-financial applications.} \subsection{Blockchain in transportation and logistics} Supply chain management is one of the main transportation applications of blockchain. The stakeholders can track their goods along the complete chain and they do not need to rely on a centralized entity for authenticity of the branded products~\cite{Crosby2016}. In combination with RFID technology~\cite{Androulaki2018,Kim2018}, the blockchain would allow the companies to track products from creation to delivery to the final consumer and will help them to improve their businesses by quickly identifying problems in the chain. Blockchain can also be used to tackle transportation supply problems.~\cite{Sharma2017} proposed a blockchain network, where vehicles share their resources (fuel consumption, speed logs, space available, among others) in order to find cheap fuel stations, people for ride-sharing, or to probe good driving behavior in order to get discounts in insurance policies. The Blockchain Mobility Consortium\footnote{\url{https://blockchain-mobility.org/}} wants to share and monetize the driver's information to improve network performance and to make money while driving. Applications like Arcade City\footnote{\url{https://arcade.city/}} are proposing to share their trips in a shared mobility service, but without third party involvement in the transaction. Shared mobility can exploit the use of blockchain to connect drivers and riders with no third party intermediaries. However as~\cite{Stocker2016} pointed out, some issues like regulatory uncertainty, liability issues and network optimization need to be address before fully implementing blockchain for shared mobility. The blockchain B\textsuperscript{2}ITS is a conceptual model which can be used as a network for Parallel Transportation Management and Control System~\cite{Yuan2016}. \subsection{Privacy and cybersecurity} Maintaining individual's privacy is currently one of the key challenges faced by various industries and researchers. Almost every part of our lives is stored on servers owned by various companies. Previously, techniques like hashing function have been used to anonymize user data in transportation \cite{beaulieu2016large}. Public and private key encryption techniques have been used for data and communication security~\cite{Farooq2015}. However, researchers and technologists have found that blockchain can be a potential solution to the privacy problem by decentralizing information and making the individuals the sole owners and controllers of their information. Blockchain can be used to securely share private information in: medical networks~\cite{Yue2016}, IoT networks~\cite{Dorri2017}, smart grids~\cite{ZhumabekulyAitzhan2016} and data provenance in cloud computing~\cite{Liang2017}. To the authors knowledge, in the literature there is no record of a generalized multi-layered blockchain framework for smart mobility data transactions that can guard the privacy of individuals and protect against hacking. The framework presented in this work can be a solution to the privacy and security challenges of sharing actively as well as passively solicited large-scale smart mobility data. \section{Conceptual framework} \label{sec:framework} The level of permission is the first step in the creation of a blockchain, e.g., in the Bitcoin blockchain anyone can participate and all the transactions are publicly available. Essentially there are four types of permissions~\cite{Olnes2017}: \begin{enumerate} \item \emph{Public closed}: Anyone can do the transactions and have access to the ledger. Only a restricted set of participants can be involved in the consensus mechanism. \item \emph{Public open}: Anyone can do the transactions, have access to the ledger and can participate in consensus mechanisms. \item \emph{Private closed}: Restricted access to transactions, have access to the ledger and the consensus mechanisms. Only the owner determines who can participate. \item \emph{Private open}: Restriction on access and who can transact. All participants can be involved in the consensus mechanism. \end{enumerate} The main disadvantage of \emph{open} blockchains is the amount of energy to reach consensus necessary to build trust between all parties in the network, for example the estimated energy consumption of the Bitcoin is 100MW~\cite{Harald2017}. In the authors' opinion it will be better to consider an eco-friendlier path and to opt for a network with less consumption of energy. We propose a \emph{close} blockchain as this type of network consumes considerably less energy than an \emph{open} counterpart. The decision between \emph{private} or \emph{public} has to be taken in terms of access to the ledger and participation. In \emph{private} only the owner determines who can participate, giving such power to one entity or entities may lead to an undemocratic process and can hurt people's trust. The \emph{public} blockchain may fit better in the proposed framework as the participation is open to the public. However, in this type of networks the ledger is also public, so in order to protect the privacy of the individuals the personal information is not stored in the ledger. Nevertheless, we believe that choosing the right type of blockchain, should be a decision taken by all parties involved. People, society, government bodies, and concerned companies need to discuss this in depth. Figure~\ref{fig:diagramBlock} shows the general framework of a \emph{public closed} Blockchain for Smart Mobility Data-market (BSMD) composed of nodes: \emph{Individuals}, \emph{Companies}, \emph{Universities} and \emph{Government} (transport, census, planing and development agencies). The nodes collect their own data and store it in \textit{identifications}. Each node is the sole owner of their data and can share their information by showing other nodes their \emph{identifications} or parts of it. \begin{figure} \centering \centerline{\includegraphics[scale = .16]{blockchain.pdf}} \caption{Blockchain network and data collectors} \label{fig:diagramBlock} \end{figure} Nodes in BSMD are divided into \emph{passive} nodes and \emph{active} nodes. \emph{Passive} nodes may read or host copies of the ledger. This type of node is suitable for individuals or small businesses who want to participate and take advantage of the network, but do not have the resources for running nodes for extended periods of time. \emph{Active} nodes can write blocks and store updated versions of the ledger for other nodes to connect. This type of node is suitable for governments, universities or companies who have the resources for these tasks. In the blockchain there are \emph{smart contracts} available that the nodes need to sign before any transaction of information is conducted. {There are no differences between the \emph{active} and \emph{passive} nodes in terms of their ability to do the transaction of information on BSMD. An individual person can be an \emph{active} node, if they wish to. However, given that the BSMD is \emph{closed} they would need to acquire permission from the current nodes to become \emph{active}. Furthermore, it is expected from them to have a strong computing power available.} {Blockchain frameworks are often described in layers~\cite{Biswas2016, Glaser2017, Yuan2016}, inspired from the classic Open System Interconnection (OSI) model~\cite{day1983osi}. Hence in Figure~\ref{fig:layerBlock} we present a six layered model for BSMD}. The Identification layer is composed of mobility and other information that the nodes own. The Privacy layer is the differential privacy model for accessing Location Based Services. In the Contract layer are the set of \emph{smart contracts} and the \emph{brokers} who facilitate data transactions between nodes. The Communication layer contains the Decentralized Identifiers~\cite{Reed2018} of the nodes whose serve as endpoints to establish \emph{peer-to-peer} connections. The Consensus layer contains the consensus algorithms in which the \emph{active} nodes agree to write transactions in the ledger. Finally, in the Incentive layer are the rewards the \emph{active} nodes receive for participating in consensus and the reward nodes receive for sharing (selling) their information. In the following subsections each layer is discussed in greater details. \begin{figure} \centering \centerline{\includegraphics[scale = .27]{layersBlock}} \caption{Multi-layered Blockchain model for smart mobility data-market.} \label{fig:layerBlock} \end{figure} \subsection{Identification layer} \label{sec:identificaton} Mobility data is constantly generated by different nodes. There are several companies, municipalities, and individuals producing transportation information which is valuable to governments, researchers and people. For example, telecommunication companies generate data that can be used for transportation modeling, the logs of available mobile devices registered by cellphone towers or Wi-Fi hotspots can be used to monitor traffic~\cite{Farooq2015} or to capture the individual's daily activity patterns~\cite{Phithakkitnukoon2010}. The companies can also take advantage of the blockchain to find customers or use the data generated by Government, Universities or other Companies to improve their business. It is worth noting that according to the BSMD framework companies are in control of their data so they can decide to what extent they want to share information. One of the responsibilities of the government is to collect data in order to model, manage and improve transportation networks. Information on tolls, smartcards, traffic detectors, surveys, parking and properties can be use to find new ways of shaping our mobility~\cite{Toledo2017,Alsger2018}. Universities often need to collect particular data not collected by government or companies. This data is often targeted to specific purposes like the state-preferences survey on the willingness to buy an autonomous vehicle~\cite{farooq2018virtual}. The biggest data source of transportation systems are the individuals and their smartphones. Everyday individuals generate huge amounts of data which is passively or actively solicited by companies or governments. Nowadays, it is possible to infer different aspects of the travel behavior of the users just by processing the GPS information gathered using their smartphones \cite{Yazdizadeh2018}. {An important principle of BSMD is that nodes are in control and can track their data}. All transportation data are contained in files called \emph{Identification} and they are stored in personal cloud services or in personal devices. The advantage of the cloud services is that data generated by mobiles is updated in real-time and is accessible from any device connected to the web. Each \emph{Identification} is composed of metadata, static data and dynamic data. The metadata contains the information relative to the characteristics of the node, but without disclosing any personal information. This information is publicly available and is the gateway to find nodes in the network. By looking into the metadata other nodes can see the blockchain address for making connection request and if the node they are trying to reach is an individual, a government agency, a private company or an academic institution. {Nodes may opt to request that their identity key, issued by a trusted node (e.g. government, reputable non-profit agency, university, etc) is exposed in the metadata. This key will give data generator nodes some level of confidence that the node they are dealing with is an actual person/agency/entity with verifiable credentials. Issuing identity keys would work the same way as in the current situation, where every government issues IDs to individuals, companies, etc. residing/working in a country. For an individual to acquire their identity key, it would be necessary to show the trusted nodes (e.g. government) their birth certificates, passports or other government issued papers. Identity keys of the individuals can be used to show that the data owner is a verifiable-person. It can also be used to verify other attributes, e.g. age, gender, location etc. Companies/agencies/organizations may need to show paper work from the public registry in order to get the identity key. They can prove their sector (educational, commercial, government), address and contact information with their keys. Individuals and companies/agencies/organizations need to show a trusted node, actual identifications that are supposedly difficult to tamper with, e.g, a passport or public registry records. If nodes are trying to fake their identity in the BSMD, they will have to first fake their real identification papers. The identity keys have been used to verify claims with the issuer in other studies~\cite{SovrinFoundation2018}. For illustration purposes, suppose that nodes A and B want to share some information. First, node A would ask B to prove that it is an actual person. At the time of joining, node B would have already been issued their identity key by showing their passport to the government. Node B sends their key to A and A uses this key to verify in the BSMD that B is an actual person. At the same time, A would not know the personal attributes e.g. gender or age of Node B, if they are not shared in the metadata. Keys do not contain personal information, but can be used to prove claims without disclosing personal data. To make it further secure, the issuing node can keep the identity keys for the verified-nodes dynamic.} The static data in \emph{Identification} layer contain information that does not change for long periods of time. The static information of an individual can be their name, birthday, gender, etc. While the static information of a government agency can be name, sector, board members, etc. The dynamic data contains information that is generated continuously. The dynamic information of an individual can be: daily trips, speed, modes used, origins-destinations, among others. The dynamic information of a transit agency are their daily demand and supply, real-time information on arrivals, vehicles in services, line closures, etc. Nodes need consent from the owner to access the static and the dynamic data. Figure~\ref{fig:identification} shows an \emph{identification} file of an individual and a transit agency. \subsection{Privacy layer} \label{sec:privacy} There is no doubt that Location Based Services (LBS) have made our life easier as we have instant access to information about our surroundings. However, when we access those services we are fully disclosing our location to receive the information we are looking for. For example, if users want to know the arrival times of bus lines near their location they will need to disclose their actual location in order to receive the information they want. BSMD will protect users from external agents trying to steal their information as all communications between nodes in the blockchain are \emph{peer-to-peer} and the records in the ledger do not contain information that can be used to track the location of a specific user. However, the provider of the LBS will know the actual location of the user. No matter if the node providing the LBS is honest or not, they still know the actual location of the user and this could be perceived as a privacy invasion. It is possible to access LBS without disclosing the user's exact location. One popular technique is $k$-anonymity~\cite{Sweeney2002} which consist of hiding the real location in a set of similar, but fake locations. Thus, making it hard to identify the real data. This technique has been applied in LBS through the use of: \emph{dummy locations}~\cite{Lu2008} where the dummy locations along with the real locations are sent together to the LBS; \emph{cloaks}~\cite{Zhao2018} where a region containing the real location is sent to the LBS; and \emph{geomasking}~\cite{Zhang2017} where the real locations is randomly displaced outside of an inner circle but contained in an outer circle, i.e., the real location is displaced inside a ``donut''. Another model which is gaining momentum in recent years is Differential Privacy~\cite{Dwork2008}. Apple has started using this model to anonymize mobile usage while typing\footnote{\url{https://www.apple.com/ca/privacy/}}. In Differential Privacy the probability of a query returning a value $v$ when applied to a database $D$ is similar when compared to the probability to query the same value in an adjacent database $D'$ differing by only one observation. When the operations are performed on $D$ the outcome of these operations will be close enough to the outcome of the operations performed on $D'$. In the context of LBS a Differential Privacy model called \emph{Geo-indistinguishability} (\emph{GeoInd}) can be used~\cite{Andres2013}. When a user query LBS using \emph{GeoInd} instead of searching from the actual location they will use a random nearby location such that it is possible to filter the results from the fake location to get information they are looking for. The idea is that from the random location the larger search radius will contain the smaller search radius of the real location. In Figure~\ref{fig:geoind} the actual location and search radius are shown in green and the random nearby location and search radius are shown in black. The user sends the random location (black dot) to the LBS to get the result contained in the black circle. Then, the user will filter the results of the black circle to get the results contained in the green circle. In this manner, the actual location of the user will never be sent to the LBS. \begin{figure}[!h] \centering \centerline{\includegraphics[scale = .350]{identification.pdf}} \caption{\emph{Identification} schema} \label{fig:identification} \end{figure} \begin{figure}[!h] \centering \centerline{\includegraphics[scale = .40]{geoind.pdf}} \caption{Search radii in \emph{GeoInd}} \label{fig:geoind} \end{figure} \cite{Oya2017} reported that for maintaining a high level of privacy in \emph{GeoInd} the utility must be sacrificed. Thus, the information retrieved from LBS using \emph{GeoInd} may not be useful unless users sacrifice some degree of privacy. On the other hand~\cite{Badu-Marfo2018} reported that although $k$-anonymity using \emph{geomask} outperformed \emph{GeoInd} in privacy protection, the latter shows promising results for data utility if properly configured. Nowadays, accessing LBS is part of people's day-to-day life. Whether it is for looking for restaurants or searching bus arrivals, but at the same time users prefer not to disclose their location. In BSDM, we propose a hybrid approach, where users can select the level of privacy. $k$-anonymity using \emph{geomask} is used for high levels of privacy and low levels of utility while \emph{GeoInd} is used for low levels of privacy and high levels of utility. In situations where the exact location is not important for getting accurate response, \emph{geomask} is used to protect the privacy, e.g. getting information of subway network. In situations where the exact location is important for getting accurate response, \emph{GeoInd} is used, e.g. walking distance to nearest subway station. Also, the LBS provider can reward users for their information if more relaxed parameters for privacy are set, but in the end the user is in control of their privacy and not the LBS provider. \subsection{Contract layer} \label{sec:contracts} The contract layer is composed by \emph{Smart Contracts} and data \emph{Brokers}. A \emph{smart contract} is a set of promises, specified in digital form, including protocols within which the parties perform on these promises~\cite{Szabo1996}. A \emph{smart contract} is a script which defines the set of assets available to transfer and the type of transactions permitted. All \emph{smart contracts} are stored in the blockchain and have a unique address. They act as independent actors whose objective is to transact assets given a certain set of rules that involved parties agreed upon. Once all the parties agree on the terms of the contract, they cryptographically sign the \emph{smart contracts} and start sharing the selected data via a \emph{peer-to-peer} connection. {In BSMD, \emph{smart contracts} are used to self-enforce fair trade between the nodes and to automatically solve various disputes. When nodes join the BSMD, they select their terms for the data they are willing to share and such terms cannot be altered by other nodes. For instance, if a node considers the information they are willing to share is not valuable for them or might not affect their privacy, they might give it away for free. On the other hand, if the node considers that they are sharing some personal information with a high value, they might ask for a reward in exchange and share their information using differential privacy. Information acquirer can also set their own terms for the transactions e.g. maximum payments, type and value of the service to be provided, and the accuracy level they want from the collected information.} {Before a transaction is executed, the terms of sharing from all the parties involved are considered to automatically select the appropriate \emph{smart contract} that can handle the transaction. If the terms of the parties conflict the transaction is either not performed or parties are given a chance to negotiate and update their terms. The advantage of \emph{smart contracts} is that minimal human interaction is need. Nodes just need to setup their terms once and maybe renegotiate a contract if the new terms are in their best interest. Predefined terms can be given to individual users when entering the BSMD or users may opt to use advanced options and create an \emph{ad-hoc} set of terms. After nodes select their terms, transaction procedures are transparent to the nodes and self enforced by \emph{smart contracts}}. {In general, the terms of the owner of information should be composed of:} \begin{enumerate} \item \emph{Service requested}: Information/services the user wants in exchange for the data. \item \emph{Monetary reward}: Payment for the shared data. \item \emph{Level of privacy}: To what extent the owner is willing to disclose. Owner may opt to share raw or aggregated information, e.g. user may disclose their age or range of age. \item \emph{Temporality}: For how long the owner is willing to share his data. For example, share information during April or just one time. \item \emph{Extended permissions}: Owner can select the level of redistribution. For example, owner may forbid or give permissions to redistribute their data for marketing purposes. \item \emph{Identity key}: Nodes may require to validate the identity key of the requester before starting the sharing process. \end{enumerate} {While the contract terms for an acquirer/requester should be composed of:} \begin{enumerate} \item \emph{Service provided}: Information the requester will share in exchange for the data. \item \emph{Monetary reward}: Payment value to the owner for their data. \item \emph{Accuracy of information}: Level of detail of the requested data. For example, a company may solicit exact location of the owner. \item \emph{Temporality}: For how long the requester wants to get the data of the owner. \item \emph{Extended permissions}: With whom it will share/sell the owner data \item \emph{Identity key}: Nodes may require to validate the identity key of the owner before starting the sharing process. \end{enumerate} {\emph{Smart contracts} would reside on the blockchain and are automatically activated before a transaction. A typical \emph{smart contract} in the BSMD is composed of the terms of both parties and \emph{conditional-statements} deciding if the transactions can be perform. The \emph{smart contract} shown in Algorithm~\ref{alg:smart} takes as input the terms of the owner and requester nodes. If both terms are in line with each other the nodes digitally sign the contract and a \emph{peer-to-peer} connection between the nodes is opened to complete the transaction. If at least one term (from the owner or requester) is not fulfilled, the connection is rejected.} \begin{algorithm} \footnotesize \SetAlgoLined ($s_r$)= \{get near by restaurants ($s_o$), no reward ($r_o$), differential privacy is use and age range ($p_o$), one time share ($t_o$), identity key required ($id_o$)\}\\ Requester terms = \{send near by restaurants ($s_r$), no reward ($r_r$), low geographic accuracy ($a_r$), one time share ($t_r$), identity key required ($id_r$)\}\\ \SetKwProg{Fn}{Function}{}{end} \Fn{ShareInfo(Owner terms, Requester terms)}{ \eIf{$s_o$ = $s_r$}{ \eIf{$r_o \leq s_r$}{ \eIf{$p_o \subset a_r$}{ \eIf{$t_o \subset t_r$}{ \eIf{$id_o$ pass verification AND $id_r$ pass verification}{ continue connection; } { refuse connection; } }{ refuse connection; } }{ refuse connection; } }{ refuse connection; } }{ refuse connection; } } \caption{\emph{Smart contract} Information transaction} \label{alg:smart} \end{algorithm} \emph{Brokers} are nodes in the network that arrange transactions between nodes for selling or buying transport information. The \emph{Brokers} can be associated to companies nodes or to individual nodes (see Figure~\ref{fig:diagramBlock}). They do not participate in data transfers and do not have access to private data of their clients. Their job is to find pairs of nodes that benefit from the exchange of information. To reduce possible scams, \emph{brokers} need identity keys from trusted nodes {(e.g. government, university, non-profit organization)}, so when a \emph{broker} contacts a node, before making a connection the node may will a trusted node if the \emph{broker} has an identity key, otherwise the connection is rejected. {When \emph{brokers} are involved in the transaction between two nodes they can set in the \emph{smart contract} a fee that they would collect for every transaction. Later in Section~\ref{sec:implementation} an example is given that describes the complete transaction process when one of the nodes request the services of a \emph{broker}.} \emph{Brokers} look for costumers by exploring the meta-data of the nodes and then ask them the type of information they are willing to share or the information they may need from other nodes. Figure~\ref{fig:broker} shows the \emph{broker} process for searching and getting costumers. In the step $1$ the \emph{broker} searches in the blockchain for costumers using the identification metadata. In step $2$ it will try to connect with the nodes using the metadata address, but before a communication can be established the node will check if the \emph{broker} has validation form a trusted node. Both parties need to sign a \emph{smart contract} to establish a connection. In step $3$ the \emph{broker} and the node communicate and the \emph{broker} saves their costumer in a wallet. In step $5$ both parties communicate the transaction to \emph{active} nodes for consensus (see Section~\ref{sec:consensus}). Finally in step $6$ an \emph{active} node writes the transaction in the ledger. \begin{figure} \centering \centerline{\includegraphics[scale = .5]{broker.pdf}} \caption{\emph{Broker} searching and getting costumers} \label{fig:broker} \end{figure} \subsection{Communication layer} \label{sec:Communication} Nodes communicate with each other using \emph{Decentralized Identifiers (DID)} which are fully under their control, independent from any centralized registry, identity provider, or certificate authority~\cite{Reed2018}. \emph{DIDs} are URLs to communicate with other nodes with the advantage that any node can create their own DID without the permission of a central authority. The address in the \emph{identification} metadata is a Decentralized Identifier called \emph{DID$_p$} which resolved to a document that contains: (a) the service endpoint for requesting connections and (b) the characteristics of the node but without disclosing any personal information. As all \emph{DID$_p$} are public this cannot be used for sharing transport data. Once two nodes accept to share information a new \emph{DID$_i$} is created by each node for opening a communication channel and sharing the information. So a single node will have multiple \emph{DID}s to communicate with the nodes. Having multiple $DID$s for communication will make it harder to intercept the information while it is being transferred. Instead of tampering one communication channel the attacker will need to tamper multiple communication channels. An advantage of the \emph{DID}s is that its owners can revoke access as they please~\cite{Reed2018}. Hence, at any given point a node can remove their \emph{DID} and shutdown the communication. Revocability of access to personal data is one of the key aspects in data privacy, which unfortunately in today's world is not that simple. On-line search shows several sites with detailed instructions for opting out from different pages. With the use of DID opting out is as simple as deleting a file on your computer. {$DID$s are the gates for sharing data via \emph{peer-to-peer} connections where the information is transferred using an asymmetric encryption.} {In BSMD the ledger is public, hence everyone can query its contents. If the information being transacted is of public interest, like the location of transit vehicles during service hours, then all the public information (without duplication) along with the \emph{DID}s are written in the ledger. When the transacted information is private, only the \emph{DID}s of both nodes along with the type of information being transacted is written in the ledger}. Given that a node will have one unique DID per transaction, it is difficult for an attacker to correlate \emph{DID}s in the ledger to track single nodes. \subsection{Incentive layer} \label{sec:incentive} Incentives are economic rewards for the participants of the network. They have been used in different blockchain projects~\cite{Shea2017,ODEM2018,Emery2018} as a way to motivate the participants to stay and maintain the network. For example, Blockchains for Cryptocurrency reward participants for validating transactions in the network. In BSMD one reward is given to \emph{active} nodes for participating in the consensus mechanisms and write blocks in the ledger. Incentives for hosting the network and participating in consensus mechanisms motivate the nodes to maintain the network and secure the transactions. Other rewards are given for sharing (selling) information. Any node can put a price on their information or can make an offer to other nodes to access their information. The main business of \emph{brokers} is in this layer, as they are supposed to know how the market is moving in order to get their costumers the best deal for selling or buying transportation data. For every transaction of a costumer the \emph{broker} receives the percentage specified in the \emph{smart contract}. {In BSMD, users own their information so they can decide whether to sell/share it or not. This rule contradicts the current practices where companies permanently own our information and in exchange they provide us a service. Nowadays, the mobility service (e.g. dock-less scooters, routing applications, LBS, among others) providers are not only interested in the rental of their equipment, but also in the collection of disaggregated mobility patterns of their users. Such information can be used for advertising as well as it can be sold to third parties. So a question arises: If users have control over their information would companies still be able to make profits, while offering rewards in exchange for personal mobility data? In~\ref{sec:appedixgame} we analyzed this question using game theory and discuss how and under what conditions companies can still make profits when users own and sell their information.} \subsection{Consensus layer} \label{sec:consensus} When a transaction is performed between two nodes a block is written in the ledger. However, before writing a block the nodes in the network need to reach a consensus. Selecting the most adequate consensus algorithms will depend on the level of security, the energy consumption, and the trustiness of the nodes, a comparative analysis of some consensus algorithms can be found in~\cite{Zheng2017}. In general the process to reach consensus is the following. When two nodes share information a transaction state is sent to the nodes in the network. Given that state some or all nodes performs a computation and share their response to the network. Using the responses from the nodes a consensus is reached and an \emph{active} node writes a block in the ledger. This new block contains the DID associated with the nodes that are sharing information, the type of information being transacted and if necessary the DID of the \emph{broker} who facilitated such transaction. In the BSDM only \emph{active} nodes can write blocks in the ledger as they are the only ones with the infrastructure necessary to make intensive computations and to host complete copies of the ledger. Next, we outline some common consensus algorithms and then we discus the selection of an algorithm. In Proof-of-work (PoW) one node solves a computer intensive puzzle based on the transaction and publishes their response in the network where other nodes can verify the result. If the result is verified the node can write a block in the ledger~\cite{Nakamoto2008}. In Proof-of-Stake (PoS) a lottery is drawn between all the nodes and the prize for the winner is to write a block in the ledger. The number of tickets each node receives is proportional to the stake they have in the network, so the more stake a node has the better their chances are of winning the lottery~\cite{Zheng2017}. Practical Byzantine Fault Tolerance (pBFT) and Tendermint are byzantine algorithms, where nodes are voted through different stages and at the end a node is selected to write a block in the ledger, usually nodes with better reputation (nodes that never write faulty blocks) will have more votes. Table~\ref{tab:consensus} shows a comparison of the PoW, PoS, pBFT and Tendermint consensus algorithms~\cite{Zheng2017}. The level of permission row indicates the openness to participate in the consensus mechanism. The energy saving row indicates the resources necessary to reach consensus. For instance the PoW algorithm consumes a considerable amount of resources while the pBFT and Tedermint consume less resources compared to the others. The tolerated power of adversary row indicates the amount of control an attacker would need to forge transactions. PoW requires that a single node have over the $25\%$ of the computing power of the network\footnote{\cite{Eyal2018} showed that by using \emph{selfish-mining}, it is possible for a set of nodes to control the Bitcoin network}, in PoS a single node would need more than $51\%$ of the stakes, pBFT and Tendermint need that more than $33.3\%$ of the nodes send incorrect messages. \tabulinesep=1.5mm \begin{table} \small \caption{Consensus algorithm characteristics~\cite{Zheng2017}} \label{tab:consensus} \small \begin{tabu} to \linewidth {| X[l,m] | X[l,m] | X[l,m] | X[l,m] | X[l,m] |} \hline \multicolumn{1}{|c|}{\textbf{Property}} & \multicolumn{1}{c|}{\textbf{PoW}} & \multicolumn{1}{c|}{\textbf{PoS}} & \multicolumn{1}{c|}{\textbf{pBFT}} & \multicolumn{1}{c|}{\textbf{Tendermint}} \\ \hline Level of permission & open & open & permissioned & permissioned \\ \hline Energy Saving & no & partial & yes & yes \\ \hline Tolerated power of adversary & $<25\%$ computing power & $<51\%$ stakes & $<33\%$ faulty replicas & $<33\%$ voting power \\ \hline \end{tabu} \end{table} {BSMD is a \emph{public closed} blockchain which means that the nodes will need permissions for participating in consensus mechanisms. We propose the creation of a consortium formed by government, universities, transportation companies and non-profit organizations, who will be in charge of managing the submission process for becoming and \emph{active} node.} To participate in consensus mechanism a node will have restrictions that depend on the implemented algorithm for consensus. For instance, although the PoW and PoS algorithms are open, in BSMD if a node wants to participate in consensus their capacity will be restricted and by law they will not be able to control more than $25\%$ of computing power in PoW or $51\%$ of the stake in PoS. Also any kind of alliances will be prohibited, if this means that the new alliance will lead to a control over network. Analogous restriction can be set for the pBFT and Tendermint algorithms. Unlike cryptocurrencies where all nodes are anonymous, in BSMD the nodes that participate in consensus are not. This will guarantee that nodes engaging in obscure practices during the consensus are easily identified and fines can be applied to those guilty of such practices. In addition to knowing who can participate in consensus, another point that has to be taken into account is the energy consumption and the scalability of the network. BSMD could be grown to a national scale, so it is desirable that the energy necessary to run the network does not impact the environment or number of transaction per second, which will be considerable. PoW and PoS suffer from energy issues (see Table~\ref{tab:consensus}). However, PoS energy problems are not as bad as in PoW. Scalability issues in blockchain an area of ongoing research. For instance, PoW only permits 7 transaction per second~\cite{Vukolic2016}, while variants of Byzantine Fault Tolerant (BFT) algorithms can handle up to 3,500 transaction per second~\cite{Androulaki2018}. {As BSMD is a \emph{public closed} blockchain, Byzantine Fault Tolerant (BFT) algorithm is a good option for consensus. Location Base Services (LBS) will consume most of the transactions in the BSMD, because these services tracks people in real-time to provide services like traffic alerts or turn-by-turn navigation. Even if in BSMD, $75\%$ of the users queries are LBS, it can currently handle $76,000$ users in real-time and with at least 90\% throughput (see~\ref{sec:appedix} for the mathematical analysis). Scaling up of the consensus mechanism in the blockchain is an active area of research. In near future, BSMD will be able to take advantage of these developments to manage even larger number of users in real-time.} Nowadays, the number of transaction per second is a counterweight for implementing blockchains on metropolis. However, some promising results are coming to light~\cite{Zhang2018,Sousa2017} that may solve the problem of scalability in coming years. \section{Implementation} \label{sec:implementation} In order to demonstrate BSMD as a distributed mobility information management system we implemented the BSMD nodes on \emph{Hyperledger} \footnote{\url{https://www.hyperledger.org}}\emph{Indy}, which is a \emph{public-closed} blockchain for decentralized digital identities and provides a framework for the exchange of information on secure \emph{peer-to-peer} connections. The lightweight libraries of \emph{Hyperledger Indy} makes it a good choice for the development of BSMD, where some of the transactions may have to be done using smartphones. In terms of the multi-layered model (\autoref{fig:layerBlock}), we implemented all the layers except the incentive layer, which can be added in future with minimum effort. Figure~\ref{fig:transactionIndy} shows with an example the details of operations implemented in BSMD. In this example we assume that there are three \emph{actives} nodes: University, Government agency, and a non-profit organization. They have the resources to participate in the consensus and to manage the ledger. The fourth and fifth nodes are \emph{passive} nodes associated to an `individual' and a \emph{broker}, who doesn't participate in these activities. {The University node will use BSMD for collecting mobility data during a four month period and it is willing to reward participants for its information.} \begin{figure} \centering \includegraphics[scale = .42]{transaction.pdf} \caption{Transaction between two nodes in the BSMD} \label{fig:transactionIndy} \end{figure} {In step $1$ the University contacts the \emph{broker} to get participants. University can contact the broker via mail, phone, and other usual business norms. For every transaction between the participants and University the \emph{broker} will charge some percentage ($10\%$ here) of the reward that will be enforced in the terms of the \emph{smart contract}. In step $2$ the \emph{broker} sends a transaction request to its clients. The transaction will have the terms of the University and a term to specify the transaction fees of the \emph{broker}}. {Algorithm~\ref{alg:smart_example} illustrates the terms of the \emph{broker}, University and an individual. In this case the \emph{smart contract} states that the information will be shared for a four month period. Hence a connection between the University and the Individual will be accessible during the predefined four month period only. Observe that University node is requesting mobility patterns and this information does not need to be transferred in real-time. The daily mobility patterns of the Individual can be sent during the night, when the bandwidth and device usage are minimal. Therefore, a connection will be opened late at night and when the information for that day is transferred the connection will be closed. This process will repeat during the four month period. Every time a transaction happens the \emph{smart contract} is triggered to enforce that the terms of all nodes are maintained and each party receives what they want.} \begin{algorithm} \footnotesize \SetAlgoLined Individual = \{no service required ($s_o$), reward ($r_o$), differential privacy is use and gender ($p_o$), share mobility patterns from March to June ($t_o$), id key is required ($id_o$)\}\\ University = \{no service provided ($s_r$), reward ($r_r$), low geographic accuracy and gender ($a_r$), share mobility patterns during for a four month period ($t_r$), no id proof key required $id_r$\}\\ Broker = \{collect $10\%$ of $r_r$\}\\ \SetKwProg{Fn}{Function}{}{end} \Fn{ShareInfo(Owner terms, Requester terms)}{ \eIf{$s_o$ = $s_r$}{ \eIf{$r_o \leq s_r$}{ \eIf{$p_o \subset a_r$}{ \eIf{$t_o \subset t_r$}{ \eIf{University key pass verification}{ Send $10\%$ of $r_r$ to broker\\ start connection; } { refuse connection; } }{ refuse connection; } }{ refuse connection; } }{ refuse connection; } }{ refuse connection; } } \caption{\emph{Smart contract} Information transaction} \label{alg:smart_example} \end{algorithm} {Steps $3$, $4$ and $5$ will occur every day late at night. In step $3$ an encrypted \emph{peer-to-peer} channel of communication is opened by creating two Decentralized Identifiers ($DID$). The individual will create a $DID_I$ and send it to the University, while the University will create a $DID_N$ and send it to the individual. These $DID$s are the addresses that the nodes use for communication. Every time a connection is established a $DID$ is created, so a single node or individual can have multiple $DID$s assigned. In Step $4$ the nodes will submit a transaction request to the BSMD and an \emph{active} node will build a block with the characteristics of the transaction. This type of transaction is private and the information of the Individual node is never written in the ledger. Instead, the private information is encrypted and sent directly to the University node using the \emph{peer-to-peer} connection. Both nodes will keep the data in a private storage. BSMD can also accommodate public transactions where the the information is written in the ledger. For example, bike availability at stations is exposed by bike-share companies so users know in advance the nearest station with available bikes. The details on the block for these two cases are provided in \ref{sec:appedixblocks}.} {More than one \emph{active} nodes can create their own block using a transaction. In Step $5$, by using a consensus protocol it will be decided, which \emph{active} node will write a block to the ledger.} {The complete source code and instructions for using the BSMD implementation in \emph{Hyperledger} can be found at \url{https://github.com/billjee/bsmd}. Note that our framework is very flexible and generic. It can be implemented on various other blockchain SDKs beyond \emph{Hyperledger} with minimal effort.} \subsection{Demonstrations and impact analysis} {Distributed ledger technologies are an active area of research. However, to the best of our knowledge, it is rare to find studies outside the world of cryptocurrencies that have developed extensive analysis on the performance of their proposed frameworks. Table~\ref{tab:blockchainSimulations} lists the major studies on this matter. Majority of them have been small-scale simulation studies, focusing on the technical aspects only. Moreover, to the best of our knowledge, no such general framework currently exists for a blockchain based mobility information management framework.} \tabulinesep=1.5mm \begin{table}[!h] \small \caption{Blockchain simulations} \label{tab:blockchainSimulations} \begin{tabu} to \linewidth {| X[l,m] | X[l,m] | X[l,m] | X[,l,m] | X[l,m] |} \hline \textbf{Framework} & \textbf{Description} & \textbf{Setup} & \textbf{Size of the blockchain} & \textbf{Test}\\ \hline Eikeden~\cite{Cheng2018} & Privacy-preserving \emph{smart contracts} & Master: One local i7, 8GB RAM machine. \newline Slave: 4 EC2 \emph{t2.medium} & 4 nodes & Latency and throughput \\ \hline Hyperledger Fabric~\cite{Sousa2018} & Business blockchain framework & \begin{itemize}[leftmargin=*] \item[a.] Local Xeon E5520 32GB RAM server. \item[b.] 4 EC2 \emph{m4.4xlarge} \end{itemize} & \begin{itemize}[leftmargin=*] \item[a.] 10 nodes in local simulations. \item[b.] 4 nodes in distributed simulations \end{itemize} & Latency, throughput, RAM and HHD usage, size of transactions, impact of CPU in nodes \\ \hline BaDS~\cite{Zhang2018b} & Blockchain framework for IoT & 1 local Core i7, 8GB RAM & Not reported & Computational cost of transactions \\ \hline BeeKeeper~\cite{Zhou2018} & Blockchain-enabled IoT & 4 1GHz CPUs, 2GB RAM servers & Not reported & Latency and throughput \\ \hline Smart-Grid~\cite{Mengelkamp2018} & Blockchain for trading local energy generation & Not reported & Not reported & Market prices \\ \hline \end{tabu} \end{table} The studies presented in Table~\ref{tab:blockchainSimulations} either tested their blockchain on a local computer or on a combination with Amazon Elastic Compute Cloud (EC2). For the evaluation of the performance, latency and average throughput are the common denominators in these simulations. Hence, in order to keep simulation features at least at the same level as that of state-of-the-art, we developed two demonstrations and analyzed their performance using latency and average throughput. The first demonstration simulated the management of real-time mobility data (e.g. GPS stream) on BSMD, generated over 24hr by mobile devices e.g. smartphones. Latency and throughput were analyzed for 106-206 nodes implemented on BSMD. The simulation ran on an Ubuntu 16.04 machine with an i7-8cores (3.5GHz) and 16GB of RAM. Note that the blockchain size here is larger than most of the studies presented in Table~\ref{tab:blockchainSimulations} where a simulation is performed on a local machine to test the blockchain in a controlled environment without the performance impacts of external factors e.g. available bandwidth on a communication network. The setup of the second demonstration is more comprehensive both physically as well in terms of the size. Here the real-time mobility data management is simulated on a physical network and with a blockchain composed of 370 BSMD nodes that were geographically-separated and were using different communication networks: \begin{enumerate} \item[a.] 10 \emph{t2.medium} (Amazon cloud EC2 virtual machines with 2cores at 3.1GHz and 4GB of RAM), running 1 \emph{active} node each \item[b.] 20 Raspberry Pi (RPi) model 3B (4cores at 1.2GHz and 1GB RAM) using WiFi and running 10 \emph{passive} nodes each \item[c.] 1 local computer (i7-8cores at 3.5GHz and 16GB of RAM) using Ethernet for communication, running 20 \emph{passive} nodes in each core \end{enumerate} The EC2 computers ran the \emph{active} nodes i.e. those who participate in the consensus mechanisms and write block in the ledger. On RPis and local computer, individual nodes were implemented that were sharing their mobility information on the blockchain. This demonstration is a very close approximation of the reality where users share their mobility information in the blockchain using their hand-held devices because (a) RPi computing capabilities are a close approximation of a mobile device and (b) simulation running on a real infrastructure where WiFi signals, speed of the internet, and type of device may also affect the performance. Besides the standard operations of BSMD (see Figure \ref{fig:transactionIndy}), following operations specific to mobility data sharing scenario are also implemented: (a) \emph{active} nodes validating other nodes so that individuals (e.g. mobile devices) can trust them when sharing information (b) creation of \emph{smart contracts} specific to the mobility data sharing on BSMD (c) \emph{peer-to-peer} encrypted communication for sharing mobility information. Next, we present the implementation details of the experiments and results of both demonstrations. \subsubsection{BSMD simulation on local machine} \label{sec:localSimulation} To run BSMD on a local machine we installed 6 \emph{active} nodes on 3 cores and used the remaining 5 cores to simulate different sizes of mobile device populations (\emph{passive} nodes). Distributing the BSMD nodes on cores simulate a real case where the nodes interact in the blockchain using different devices. In total we simulated populations of $100$, $125$, $150$, $175$ and $200$ mobile devices. Our local computer was not able to simulate populations beyond $200$ and started crashing, so no further simulations were performed. In reality, population share real-time location data throughout the day, so the simulation ran for a 24hr period. Assuming that an individual sends location points every 5sec, so in 24hr the maximum number of GPS points their devise (e.g. smartphone) could share is $17,280$. On the other extreme, if the individual stay at home all day the minimum number of points shared is $0$. In general most of the individuals will share their home-work trips and errands/entertainment. {We assumed a more extreme scenario where individual users are sharing their location for the most part of their day (even if they are stationary). Hence at an average, an individual will share approximately $9,300$ GPS points throughout the day.} Based on that, for a population of $n$ individuals we assumed that the number of real-time locations generated by individuals is normally distributed with mean, $\mu = 9356$, and standard deviation, $\sigma = 1902$. Figure~\ref{fig:msg_distribution} shows an example of the distribution of real-time locations generated by $100$ individuals. \begin{figure}[!h] \centering \includegraphics[width=0.75\textwidth]{distribution_msg-pers.png} \caption{Distribution of real-time locations in a population of $100$ individuals} \label{fig:msg_distribution} \end{figure} Assuming that most trips are around 08:00 (morning peak) when people go to work and around 18:00 (afternoon) when people return to home, the distribution of the messages a population sends during the day is simulated with a mixture of three normal distributions, such that $\mu_1 = 8$ and $\sigma_1 = 2.3$ represent home to work trips, $\mu_2 = 13$ and $\sigma_2 = 3.5$ represent lunch trips and $\mu_3 = 18$ and $\sigma_3 = 2.3$ represent work to home trips. Figure~\ref{fig:pop_distribution} shows the distributions of messages sent by populations of $100$, $125$, $150$, $175$ and $200$ individuals. Table~\ref{tab:blockchainCharac} we present the main characteristics of each experiment. \begin{figure} \centering \includegraphics[width=\textwidth]{msg-dist.png} \caption{Distribution of messages during the day for populations of $100$, $125$, $150$, $175$ and $200$ individuals} \label{fig:pop_distribution} \end{figure} \begin{table} \footnotesize \caption{Main characteristics of each simulation} \label{tab:blockchainCharac} \begin{tabu} to \linewidth {| X[c,m] | X[c,m] | X[c,m] | X[c,m] |} \hline \textbf{Population Size} & \textbf{Total messages} & \textbf{Maximum locations shared / min.} & \textbf{Average locations shared / min. (st. dev)}\\ \hline $100$ & $944,678$ & $1,160$ & $878$ ($\sigma = 233$) \\ \hline $125$ & $1,174,204$ & $1,418$ & $1,071$ ($\sigma = 281$) \\ \hline $150$ & $1,360,010$ & $1,746$ & $1,318$ ($\sigma = 356$) \\ \hline $175$ & $1,662,254$ & $1,963$ & $1,517$ ($\sigma = 405$) \\ \hline $200$ & $1,857,092$ & $2,296$ & $1,761$ ($\sigma = 484$) \\ \hline \end{tabu} \end{table} The results of the simulations are shown in Table~\ref{tab:blockchainSimuPop}. In general, the latency remains under $0.6$ secs even when the system is high congested with the messages. Thus the response times of the BSMD are promising to keep up with the demands of the the modern world. In actual implementations, this response can be improved further by deploying more active nodes with higher computational power. The throughput shown in Table~\ref{tab:blockchainSimuPop} is the ratio of message served and messages send i.e. an average throughput of $0.9$ mean that $90\%$ of the messages were processed. It is expected that the average throughput decays as the population grows because the number of cores in the local computer hosting the blockchain and the population remains constant. It is worth noting that in the simulation for $200$ individuals the core and RAM usage was at $100\%$ through the peak hours (from minute $480$ to $1080$) of the experiment which may explain why some messages were lost. In general the throughput remains 90\% or more for all the experiments on a limited hardware, which shows a high reliability of the system. \tabulinesep=1.5mm \begin{table}[!h] \small \caption{Blockchain performance with different populations} \label{tab:blockchainSimuPop} \begin{tabu} to \linewidth {| X[0.4,c,m] | X[c,m] | X[c,m] |} \hline \textbf{Population} & \textbf{Average Latency in sec.} & \textbf{Average throughput}\\ \hline 100 & $0.014$ $(\sigma = 0.006)$ & $1$ $(\sigma = 0)$ \\ \hline 125 & $0.14$ $(\sigma = 0.41)$ & $0.976$ $(\sigma = 0.134)$\\ \hline 150 & $0.33$ $(\sigma = 0.64)$ & $0.943$ $(\sigma = 0.135)$\\ \hline 175 & $0.52$ $(\sigma = 0.62)$ & $0.937$ $(\sigma = 0.152)$\\ \hline 200 & $0.60$ $(\sigma = 0.76)$ & $0.9$ $(\sigma = 0.145)$\\ \hline \end{tabu} \end{table} Furthermore, we split the analysis of the latency into two parts. First the frequency of latency of a single message is analyzed and then in the second part we show how the average latency changes through the day. Figure~\ref{fig:latency_distribution} shows the frequency of the latency for the populations. We observe that the latency of all messages remains under $0.2$sec. for a population of $100$ individuals. While for the populations of $125$, $150$, $175$ and $200$ the percentages of messages with latency under 1sec are $91\%$, $85\%$, $70\%$ and $70\%$ respectively. For populations over $100$ the frequency of the latency decay abruptly from $0$ to $0.6$sec, and after $0.6$sec the frequency seems to decay slowly at a constant rate. Figure~\ref{fig:avg_distribution} shows the average latency per minute over a day for all the populations. Since the maximum latency of the $100$ population is less than $0.028$sec, the average latency per minute is presented as a flat line. As expected, the latency increases around the peak hours (08:00 and 18:00) and in between the peak hours the latency decays. Although all populations present spikes for few minutes of the day, if we eliminate the noise by considering the moving average of the 15 previous minutes (see Figure~\ref{fig:moving_avg}) then the latency for all the experiments is under $2.5$sec and for most part of the day the latency is almost under $1.5$sec. \begin{figure} \centering \includegraphics[width=0.63\textwidth]{latency-dist.png} \caption{Latency frequency in seconds for populations of $100$, $125$, $150$, $175$ and $200$ individuals} \label{fig:latency_distribution} \end{figure} \begin{figure}[!h] \centering \includegraphics[width=0.63\textwidth]{agvlatency.png} \caption{Average latency per minute of the day of the different populations} \label{fig:avg_distribution} \end{figure} \begin{figure}[!h] \centering \includegraphics[width=0.63\textwidth]{15movAvg.png} \caption{15 minute moving average of the average latency per minute of the day} \label{fig:moving_avg} \end{figure} \subsubsection{BSMD simulation on a physical network} \label{sec:DisSimulation} Here we simulated a blockchain of 370 nodes on a physical network. We used 10 BSMD \emph{active} nodes installed on 10 \emph{t3.medium} EC2 virtual machines. We also used 20 RPis and one local machine to simulate a population of (10 nodes x 20 RPis) + (20 nodes x 8 cores) = 360 \emph{passive} nodes sharing their real-time location data. Given the low hardware specifications of the RPis and the fact that it is necessary to encrypt and decrypt messages in the blockchain, we could only test a population of 10 individuals per RPi. In this simulation we assumed that each individual is sharing real-time locations during the morning peak-hour, from 08:00 to 09:00. Just like Section~\ref{sec:localSimulation}, here too we assumed that the individual device is sending location points every 5sec. We used a normal distribution with $\mu=9356$ and $\sigma = 1902$ for generating the real-time locations of each individual. And we use a mixture of the distributions $\mu_1 = 8$ and $\sigma_1 = 2.3$, $\mu_2 = 13$ and $\sigma_2 = 3.5$ and $\mu_3 = 18$ and $\sigma_3 = 2.3$ for generating all the GPS points the population share in the blockchain. Hence, during the morning peak hour the \emph{passive} nodes on RPi and the local computer shared $11,443$ locations with the \emph{active} nodes on \emph{t3.medium} virtual machines. Table~\ref{tab:blockchainRPICUP} shows the results of the simulation. Given that each individual sends a message every 5sec, it is desirable that the latency is below this time so as to maintain the real-time flow of information. In Table~\ref{tab:blockchainRPICUP} the average latency of the local machine simulation is $2.9$sec, however for the RPis it is $6.59$sec. This difference is due to the low computation power of RPis and because each of them is simulating 10 nodes simultaneously. Although our tests showed that an RPi can handle the decryption and encryption of the connections request/response for a single node with a latency of less than 1sec, it consumes all of the RPi resources to perform this task for 10 nodes simultaneously. The low latency times are thus more related to the computational power of the RPi than the time needed to get a response from the blockchain. In real-life, mobile devices like smartphones would only run 1 node and would also be more powerful than an RPi we used e.g. iPhone 7, which is an older generation smartphone (released in 2016) has 4 cores at 2.34 GHz and 2GB of RAM. The average throughput in this experiment for both RPis and the local machine was $99\%$. This demonstrates the high reliability of the implemented BSMD. Despite a relatively higher latency exhibited by the overloaded RPis, there is a very low rate of message loss and most of the messages are successfully being sent and received by \emph{active} and \emph{passive} nodes in the blockchain. \tabulinesep=1.5mm \begin{table} \small \caption{Blockchain performance} \label{tab:blockchainRPICUP} \begin{tabu} to \linewidth {| X[c,m] | X[c,m] | X[c,m] |} \hline \textbf{Population} & \textbf{Average Latency in sec.} & \textbf{Average throughput}\\ \hline 20 RPi, 10 users per RPi & $6.59$ $(\sigma = 2.32)$ & $0.998$ $(\sigma = 0.008)$ \\ \hline Local machine, 20 users per core & $2.98$ $(\sigma = 0.82)$ & $0.991$ $(\sigma = 0.021)$\\ \hline RPi + Local Machine & $5.56$ $(\sigma = 1.73)$ & $0.996$ $(\sigma = 0.009)$\\ \hline \end{tabu} \end{table} \subsection{Cybersecurity and privacy impacts} BSMD addresses some key cybersecurity and privacy issues individual user faces these days, while sharing mobility data information. When sharing, it is not easy for the individual to tell if the receiver is actually the one who it claims it is. This situation can result is \emph{spoofing} where fake companies/entities can trick users into sharing information for malicious activities. By using the BSMD implementation, it is possible to verify the identities in blockchain. The identity key system can be managed by all the trusted nodes (government or non-profit organizations). In case of \emph{message interception} attack, the individual's communication with a legitimate entity can be intercepted by a malicious entity. The peer-to-peer encrypted communication in BSMD makes it very difficult for malicious entities to launch such attack. The individual users would like to have the ability to stop sharing their information at any point or bar a node for using their information further. \emph{Smart contract} implemented in BSMD provides the mechanism to give this control to the individuals. Next we present the details on how BSMD safeguards against \emph{spoofing} attacks. However, the detailed implementation of all the three cases i.e. \emph{spoofing}, \emph{message interception}, and \emph{privacy control} can be found at: \url{https://github.com/billjee/bsmd/tree/master/examples}. \subsubsection{Spoofing attack} Here we use the same mobility case study as described in Section \ref{sec:localSimulation}. Assume that the six \emph{actives} nodes are: Federal Government, Provincial Government, City Government, University, a RideHailing Company, and a Non-For-Profit Transportation Organization. They have the resources to participate in the consensus and to manage the ledger. We also chose one random \emph{passive} node `Individual' from the population, who does not participate in these activities but only share their GPS data. If the University wants to get mobility data from the Individual first the Individual needs to verify that the Identity of University is approved by any of the Government node. In order to get a identity key from the Government the following steps are required: \begin{enumerate} \item Government creates a credential schema and sends this definition to the ledger. Schema is a blank credential that the Government will use for creating identity keys. \item Government issues a credential with the identity key of the University. \begin{enumerate} \item University stores the credential in its wallet. \item A registry of the credential is sent to ledger. This registry will be used by others to verify the identity of the University. \end{enumerate} \item University makes a connection request to the Individual for sharing information \item Individual sends the University a sharing application. \item University fills this application with the identity key issued by the Government. Using the application filled, the University obtains from the ledger an application proof that will be used by the Individual node for verifying the identity and establishing the connection. If the University tries to spoof Individual's identity the registry from the ledger will not match with the application and hence the University will not get the application proof making the connection with the user impossible. Figure~\ref{fig:spoofing1} shows the output log when the University tries to spoof Individual's identity before obtaining application proof. \item Individual reads the application and compares it with the registry in the ledger. If application and the registry match, Individual can validate the identity of the University node. If the application and the registry does not match the Individual rejects the connection as the Identity of the node may be spoofed. Figure~\ref{fig:spoofing2} shows the output log when the University node tries to access Individual's identity after obtaining application proof. \end{enumerate} \begin{figure} \centering \begin{subfigure}{.5\textwidth} \centering \includegraphics[scale = 1.2]{spoofing1.png} \caption{Without application proof} \label{fig:spoofing1} \end{subfigure}\hfill \begin{subfigure}{.5\textwidth} \centering \includegraphics[scale = 1.2]{spoofing2.png} \caption{With application proof} \label{fig:spoofing2} \end{subfigure} \caption{Node attempting to access Individual's identity} \label{fig:spoofing} \end{figure} In the presented example, there are two steps of verification of the identity. In first step, the University tries to get an application proof for connection, if the application proof does not match with the registries of the ledger the application proof for connection is not proceed. In second step, if the University tries to access the Individual's identity after obtaining the application proof for connection. In this step the Individual will also compare the received information with the registries from the ledger to verify the identity of the University. The two step verification process makes it harder for nodes to spoof Individual's identity because it is required to compare node's information with the registries of the ledger. One comparison is made by the node itself and the other is made by the node with whom it wants to connect to. The only case where a node can spoof someone's identity would be to tamper the ledger, which is practically impossible due to the design of BSMD. Please also note that all these processes would be implemented in software and would not bring any extra burden on the actual users themselves. In most cases, these features will be turned on by default on the BSMD enabled devices they are using. \section{Discussion} \label{sec:discussion} Nowadays, the flow of the mobility information can be summarized as following steps: \begin{enumerate} \item Mobility information is generated by an individual. As they move, details such as mode, travel time, departure time, etc, can be recorded by their smartphones~\cite{Yazdizadeh2018} or can be described by themselves. \item The information is solicited actively or passively. Third parties can ask for mobility information using surveys or by getting access to sensors data of an individual's smartphones. \item Information is collected. The collection methods can be via phone, in person, online, or actively collected using smartphones. \item The collector processes and analyzes the information. The collected data is processed and stored in central databases from where data analysis can be performed. \end{enumerate} The six layers of BSMD are developed in such a way that they include the steps 1 to 3 in a single environment, making the transaction of mobility information secure, private and in some cases, the collection of mobility information is easier than the current practices. The mechanisms for processing and aggregation of information are not part of BSMD because each collector will choose different tools for these tasks. However, the collector can use the blockchain for sharing or selling the collected information. The privacy and identification layers are for the generators of information (step 1). The privacy layer enforces the principles on which a BSMD is built upon and a model which maintains location privacy of the users. The identification layer has the tools for collecting mobility data. The identification can be build in a standardized way (e.g. json format) so that the collectors of information can easily process and analyze the data. {In this layer nodes can store identity keys, which can be used by other nodes to verify them.} The contract, incentive, communication and privacy layers are for soliciting information (step 2). These layers have the mechanisms for selecting which information individuals are willing to share and a secure way for data transfers. {\emph{Smart contracts} are used to self-enforce fair trade and to manage disputes, such as breaking the terms of transactions or price negotiation}. Using incentives, the nodes can convince individuals to share their information. The collection of information (step 3) uses all the BSMD layers. A collector node will use the identification layer to get the information from other nodes. This information can only be accessed using the contract and privacy layers. The collector can use the incentive layer to encourage others to disclose their information. All information is transferred using the communication layer. Once the transaction is completed the consensus layer will check if the transaction is valid and a block is written in the ledger. \subsection{Opportunities} BSMD aims to drastically improve various aspects in the current way of sharing and collecting mobility data. First, it will give back the generator of the information full control over their information and privacy. Nowadays, it is not easy or in most cases, entirely not possible to access certain services unless users consent to all the conditions imposed by the collectors. Most of the time, the collectors have full control over users' information. \emph{Smart contracts} and public ledger will help users protect, control and track their information. Every transaction in BSMD needs to be validated by other nodes using consensus mechanisms. Thus, unsolicited request of information can be prevented. {When nodes sell information to a third party they do not lose total control over their information, because it is legally protected by terms of the \emph{smart contract}. If the requester node is caught using the information outside the terms of the \emph{smart contract}, then the auditors can take advantage of the public ledger to see which nodes were scammed and take legal actions against the one responsible. Having a public and distributed ledger may speed up the legal process since all transactions are accessible. Nowadays, when companies are caught misusing information, it is hard to prove whose information was misused, since all records are on private servers. Also, it is difficult for authorities to audit private servers to measure the true extent of the damage.} Creating a unified platform where mobility information can be shared in a secure and transparent way will improve the collection of information and hence the analysis of the data. Nowadays, when companies/governments share mobility information they create APIs and develop security mechanisms for others to access their information. Despite the existence of standards for developing such APIs, companies/governments need to spend resources on the development. The blockchain will provide a single and secure network where companies/governments just need to ``plug-in'' and start sharing and accessing mobility data. \subsection{Challenges} Blockchain technology is in its early stages of development and there are a number of challenges that need to be addressed for making BSMD readily available. The monetization of users mobility information is a big business for companies, so further research on monetization schemes needs to be developed in order to convince companies to adopt BSMD. {In Section~\ref{sec:incentive}, we developed a game theory based mechanism to analyze the case where companies can buy information and still make a profit. However, it is not clear what is the fair price for the mobility data, where companies can still profit from individual's mobility information and at the same time protect their privacy. An open-market based on the demand can be a good solution. The design and development of such market could be an interesting topic for a future work.} Although the percentage of users with smartphones or access to computers grows every day, the ubiquitousness of this technology is still few years away. For instance, in 2015 smartphone ownership in the world was $46\%$, while in richer economies this rate was up to $88\%$~\cite{Pew2016}. It is possible that some analysis of the information collected in BSMD will marginalize certain sectors of the population, making their mobility issues invisible to society. When all sectors of the population have a representative sample of smartphone ownership more robust analysis of the mobility information collected in BSMD will be performed. For the moment, transportation studies using the data collected in BSMD will be more useful for populations with high smartphone ownership. {There is a trade-off between \emph{public} and \emph{close} blockchains. In the former, anyone can participate in consensus and host the ledger. However, the consensus requires large use of energy as well as the capacity to handle several transactions per second. BSMD is of the latter type. Here, the participants need approval from \emph{active} nodes to participate in the consensus and hosting the ledger. This type of blockchain can handle considerably more transactions than its counterpart and requires less energy for consensus. In order to keep the BSMD as democratic as possible, the power that the \emph{active} nodes have over BSMD must be legally regulated. Rules need to be set and enforced so when users wants to become an \emph{active} node, they will have the means and will to do that. Defining the set of rules and the mechanisms imposed on the \emph{active} nodes is out of the scope of this paper.} {Theoretically, in \emph{public} blockchains like \textit{Bitcoin} anyone can mine blocks, participate in consensus, and host the ledger. In reality though, only the people/companies who have large computing resources stay active. The cheapest mining computer that can make profits of a couple hundred dollars a year can cost as much as \$2,000. Since \emph{closed} blockchain requires considerably less computing power, money may not be a problem and people will able to easily buy computers that can participate in the consensus mechanisms.} {BSMD is able to automatically resolve disputes and enforce fair trade with \emph{smart contracts}. By using $DID$s and asymmetric encryption in \emph{peer-to-peer} connections, communication jamming can be prevented. The identity keys will reduce the number of fake users and node spoofing attacks. With identity key, a node can verify sector, address and company information of governments/agencies/organizations, as well as gender and age of real persons. At the moment BSMD cannot be used to prevent malicious node from selling spoof location data. Detection of spoof GPS location data is still an open problem and may require invading the privacy of users~\cite{Zhao2018a}. For instance,~\cite{Zhao2017} proposed digging into the social media of users and to detect the probability that the user is in a certain location. The solution by~\cite{Tian2017} needs the users to send photos of landmarks to prove location. In the authors opinion and to keep consistency with the nature of BSMD, privacy should be the first priority and any solution that solves the fake user problem by affecting the privacy of individuals should not be taken into account.} Scalability is another aspect that is worth considering. For BSMD to be successful it has to be capable to manage tens of thousands of transactions per second. One limitation of the blockchains that use proof-of-work for consensus is that at most it can handle 100 transaction per second and latency of 1 hour. So despite its strong security features, this type of consensus mechanism cannot be used in BSDM. SMART, a variant of Byzantine Fault-Tolerant (BFT) can handle up to 2300 transaction per second and has a latency of half a second~\cite{Sousa2017}. \emph{Hyperledger Fabric}~\cite{Androulaki2018} can achieve 3500 transactions per second using special configurations. Nevertheless the security of BFT-SMART and \emph{Fabric} are guaranteed as long as only trusted nodes participate in consensus. Given that BSMD is \emph{public closed}, BFT-SMART may be a solution for fast and secure transactions in big networks. \subsection{Privacy principles} BSMD is build upon the principles of: \begin{enumerate} \item Data Ownership \item Fine-grained Access Control \item Data Transparency \item Auditability \end{enumerate} The main objective of BSMD is to give back to users the power to control and profit from their transportation data. \subsubsection{Data ownership} \label{sec:DataOwnership} Most people do not completely read privacy policies or terms and conditions forms, they just accept these forms to enter web sites~\cite{Obar2016}. Selling information in BSDM is a good incentive for users to guard their privacy and read terms and conditions as this may imply that users will not give their information before checking if the profit they make is a fair exchange. The more information they sell the bigger the reward will be, but at the same time their privacy will be reduced. In BSMD, people have the right to be forgotten. All transactions of information are encrypted and the only way to decrypt the information is if a connection is open between the nodes. So, when a node shuts down a connection the information that was shared will not be accessible by the receiving node because the description key will no longer be available. \subsubsection{Data transparency and auditability} \label{sec:DataTransparency} There have been cases where companies share personal data to untrusted parties~\cite{Solon2018} without the owner's consent.~\cite{Bonneau2009} showed that the protection of personal data is not at the same level as that of user's expectations. The ledger in BSMD is open to the public so anyone can track their personal transactions by using their DID. {If a misusing node shares information and breaks the terms of the \emph{smart contract} authorities and owners can query the ledger to see which information they shared. Thus, the affected parts in the unwanted sharing of information can be easily tracked and legal actions can be taken, since all nodes have the proof that their information was misused}. \subsubsection{Fine-grained access control} \label{sec:FineGrained} Currently, on-line services enforce an all-or-nothing model i.e. when users subscribe to services, it is a common practice to make them accept all the terms and conditions for sharing all the data a service wants. If a user does not want to agree on sharing parts of the data, their only option is not to use such services. By using \emph{smart contract} the BSDM can get rid of such extreme cases and there can be levels of services/rewards for the level of data one shares. Nowadays, companies store mobility data and individuals cannot revoke access to some or all information unless they opt-out and stop receiving the service. In BSMD \emph{smart contract} may have a clause to revise the information a user wants to share after a certain time, for example, after a year a user may update the terms in the contract for sharing information. In BSMD instead of companies setting the terms of use, the user will set those terms and companies will have to work according to each individual's terms of use. \subsection{Adversaries} The main goal of the BSMD framework is to protect the personal mobility information and secure the privacy of the people in order to fully exploit the benefits of actively or passively solicited large-scale data. To measure the level of protection in BSMD, four groups of adversaries are identified whose attacks can be prevented or hindered thanks to the use of the blockchain. Groups of adversaries may attack the network, the nodes or when the information is been transferred (see Figure~\ref{fig:diagramAdversary}). The identified groups of adversaries are: \begin{enumerate} \item \emph{Data interception}: all information transactions are done via a unique and secure \emph{peer-to-peer} connection and information is sent with asymmetric encryption. Attacking a single node may not be worth the effort required to decrypt the data and tamper the connection every time a transactions is made. \item \emph{Data leaks}: all the personal information are decentralized and secured for every individual, so massive leaks on information will require extensive amounts of power to hack the data from a meaningful number of individuals. Also, the interceptions of multiple connections at the same time will require the interception of all connections. The computing power to do this task may not be viable. \item \emph{Unsolicited sharing of information}: every node has full access to the ledger so they can easily verify that their information is where they want it to be. \item \emph{Unsolicited request of information}: \emph{smart contracts} let the node decide the information they want to share with specific nodes. \end{enumerate} \label{sec:adversaries} \begin{figure} \centering \includegraphics[scale = .25]{adversaries.pdf} \caption{Adversary diagram of the blockchain} \label{fig:diagramAdversary} \end{figure} \section{Conclusions and future work} \label{sec:Conclusions} Blockchain framework for Smart Mobility Data-market (BSMD) is designed to solve the privacy, security and management issues related to the sharing of passively as well as actively solicited large-scale data. Data from the individuals, governments, universities and companies are distributed on the network and stored in a decentralized manner, the data transactions are recorded and must have the authorization of the owners. To the authors' knowledge there are no references on the minimum components of a blockchain. In the context of transportation, we identified three major components in a generic blockchain, a shared ledger, a \emph{peer-to-peer} network and consensus mechanisms. For the transaction of the mobility information \emph{smart contracts} are added to the BSMD nodes so that they can control the information they want to share. Based on the components of blockchain and the elements involved in the mobility data solicitation we developed a six layer model for BSMD. Theses layers contain the elements necessary to privately and securely transact mobility information. We developed three set of simulated demonstrations for the proposed BSMD. In the first experiment we implemented BSMD on a local machine with i7-8cores at 3.5GHz and 16GB RAM. 6 \emph{active} and 100 to 200 \emph{passive} nodes were simulated. \emph{Active} nodes were part of the consensus and ledger management process and would represent entities like municipalities, universities, and trusted private firms. \emph{Passive} nodes were sharing real-time mobility information over a 24hr period. They represented individual smartphones and mobile devices. In the second experiment 10 \emph{active} and 360 \emph{passive} BSMD nodes were simulated. Nodes were running on heterogeneous and geographically-separated devices communicating on a physical network. All and all, for low to medium loads the latency was less than a second and throughput was higher than 99\%. The worst case latency of 6.59sec and throughput of 90\% was observed for heavy loads. In real-life applications, the system performance can further be improved by employing some high performance computing nodes that can do the heavy-lifting, agreeing upon bandwidth consumption strategies, and using distributed ledger technologies e.g. IOTA. In the third set of experiments we demonstrated how BSMD impacts the cybersecurity and privacy of the individual users by securing them against spoofing and message interception as well as giving them control in terms of revoking access to their information using smart contract. One possible line of future research is the use of differential privacy based privacy aware machine learning, where the model using the data for parameter estimation preserves the privacy of individuals. Furthermore, instead of the current design in which service provider nodes shares the data with requesting nodes, an alternative design is followed in which the requesting node sends the services provider nodes the analysis model and parameters to be estimated. The service provider nodes run the models on their data and return the analysis parameters back to the requesting node. For the computational time and the model value, the service provider nodes may charge certain fees. There are many current real-life cases where BSMD can be implemented. From the perspective of the user, smartcard has the advantage that with a single card it is possible to pay for the all or most of the transit modes. For instance, in Montr\'eal one can use OPUS card for the metro system, regional rail, and local bikeshare. Governments use the entry and exit point logs of the Smartcard to create strategic plans for the city. Since in many parts of the world the transit is managed by different companies or authorities, if each card reader is connected to BSMD, all payments will be transferred directly to an operator with no third parties involved. Furthermore, each transaction can be assigned to a different DID, so it will be difficult to correlate all the trips of a single user. Transit providers can increase efficiency by eliminating the intermediaries for managing payments while the data of users would still be private and secure. Another potential beneficiary of the BSMD is the Connected and Autonomous Vehicle (CAV). When the market penetration rate of CAV starts to rise, the BSDM could be used as the backbone network for vehicle-to-vehicle and vehicle-to-infrastructure communication. A secure and resilient network is important as it can be used for implementing intelligent traffic management as well as distributed optimization of the CAV routes \cite{Djavadian2018}. In the CAV network the current location, origins, and destinations of the users are known. So, it is necessary that all communications are secured as well as the individual privacy is preserved. The analysis and processing of personal mobility data can improve our transportation systems and make our lives more comfortable whether in terms of going to work, building new facilities or reducing the carbon footprint. However, personal mobility data includes several aspects of life that must be private, and if researchers, governments, and companies want to use personal data they must respect the basic human right of privacy. BSMD is designed and built to give people the control over their information and the right to privately share their information. \section*{Acknowledgement} We greatly appreciate Nikki Hera-Farooq's time and efforts in helping us improve the quality of this manuscript. \bibliographystyle{abbrv}
{'timestamp': '2019-06-18T02:03:23', 'yymm': '1906', 'arxiv_id': '1906.06435', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06435'}
arxiv
\section{Introduction} \label{sec:intro} Kernel methods are among the most popular approaches in machine learning due to their capability to address non-linear problems, their robustness and their simplicity. However, they exhibit two main flaws in terms of memory usage and time complexity. To overcome the latter, some numerical approximation methods have been developed \cite{williams2001using,DBLP:journals/jmlr/DrineasM05}. Landmark-based approaches \cite{BalcanBS08,BalcanBS08_COLT,bellet2012similarity,zantedeschi2018fast} can be used to reduce the number of instances to consider in order to reduce the number of comparisons~\cite{steinwart2003sparseness}, but they heavily depend on the choice of the kernel. Tuning the kernel is, however, difficult and represents another drawback to tackle. Multiple Kernel Learning (MKL)~\cite{lanckriet2004learning,gonen2011multiple,xia2013mkboost,wu2017boosting} and Matching Pursuit (MP) methods~\cite{mallat1993matching,vincent2002kernel} can provide alternatives to this problem but these require the use of a pre-defined dictionary of base functions. Another strategy to improve the scalability of kernel methods is to use the Random Fourier Feature (RFF) approach that proposes to approximate some invariant-shift kernel with random features based on the Fourier Transform of the kernel \cite{rahimi2008random}. This approach is data independent and then a predictor can be learned over these random features. Several works have extended this approach by allowing one to adapt the approximation with respect to the (learning) data points \cite{yang2015carte,oliva2016bayesian,sinha2016learning,LetarteMG19,agrawal19a}. Among them, the recent work of \cite{LetarteMG19} presents a method to quickly obtain a weighting distribution over the random features by a single pass over them. The method is derived from a statistical learning analysis, starting from the observation that each random feature can be interpreted as a weak hypothesis in the form of trigonometric functions obtained by the Fourier decomposition. Thus, a predictor can be seen as a weighted majority vote over the random features. This Fourier decomposition is then considered as a \emph{prior} distribution over the space of weak hypotheses/random features; the authors propose to learn a \emph{posterior} distribution by optimizing a PAC-Bayesian bound with respect to a kernel alignment generalization loss over the learning data points. In other words, this corresponds to learning automatically a representation of the data through the approximation which then does not require to choose or tune a kernel in advance. However, in practice, the method of \cite{LetarteMG19} requires the use of a fixed set of landmarks selected beforehand and independently from the learning task. It is only once these landmarks are selected that the method can learn a representation based on the PAC-Bayesian bound. This leads to three important drawbacks: {\it (i)} the need for a heuristic strategy for selecting enough relevant landmarks, {\it (ii)} these landmarks and the associated representation might not be adapted for the task at hand, and {\it (iii)} the number of landmarks might not be minimal, inducing higher computational and memory costs. Instead of deliberately fixing the landmarks beforehand, we propose in this paper a Gradient Boosting approach (GB)~\cite{friedman2001greedy} for learning both the landmarks and the associated random features combination directly, leading to a strong predictor. This strategy allows us to provide more compact and efficient representations in the context where the learning budget might be limited. The reminder of the paper is organized as follows. Section~\ref{sec:notations} introduces the notations and the setting of the paper. Then, we recall in Section~\ref{sec:posterior} the work of~\cite{LetarteMG19}. We introduce our landmark-based gradient boosting approach in Section~\ref{sec:our_method}. The experiments are performed in Section~\ref{sec:expe}. Then we conclude in Section~\ref{sec:conclu} % \iffalse \section{Proposed Method} In this section, we present our method for learning the representation and the predictor simultaneously. Following~\citeauthor{LetarteMG19}, we study the generalization capabilities of the regressors learned at each iteration of our Gradient Boosting procedure through the lenses of the PAC-Bayesian theory. This theoretical analysis ultimately allows us to derive a closed-form solution of the posterior distribution $Q_t$ (over the random Fourier features at a given iteration $t$), which is guaranteed to minimize the generalization gap. Finally, we describe in detail the proposed learning algorithm, based on Gradient Boosting. \fi \section{Notations and Setting} \label{sec:notations} We consider here binary classification tasks from a \mbox{$d$-dimensional} input space ${\mathbb{R}}^d$ to the label set $Y=\{-1,1\}$. Let $S=\{z_i=({\mathbf x}_i,y_i)\}_{i=1}^n\sim \mathcal{D}^n$ be a training set of $n$ points sampled {\it i.i.d.} from $\mathcal{D}$, a fixed and unknown data-generating distribution over ${\mathbb{R}}^d\times Y$. In this paper, we focus on kernel-based algorithms that rely on pre-defined kernel functions $k:{\mathbb{R}}^d\times {\mathbb{R}}^d \rightarrow [-1,1]$ assessing the similarity between any two points of the input space. These methods present good performances when the parameters of the kernels are learned and the chosen kernel can fit the distribution of the data. However, selecting the right kernel and tuning its parameters is computationally expensive. For this reason, Multiple Kernel Learning techniques~\cite{lanckriet2004learning,gonen2011multiple,xia2013mkboost,wu2017boosting} have been proposed to select the combination of kernels that fits best the training data: a dictionary of base functions $\{k_t\}_{t=1}^T$ is composed by considering various kernels with their parameters fixed to several and different values and a combination is learned, taking the following form: \begin{equation} \label{eq:comb} H({\mathbf x}, {\mathbf x}')\ =\ \sum_{t=1}^T \alpha_t k_t({\mathbf x}, {\mathbf x}'), \end{equation} with $\alpha_t \in {\mathbb{R}}$ the weight of the kernel $k_t({\mathbf x}, {\mathbf x}')$. Similarly, in our method, we aim at learning linear combinations of kernels. However, we do not rely on a pre-computed dictionary of kernel functions. We rather learn them greedily, one per iteration of the Gradient Boosting procedure we propose (described in Section~\ref{sec:our_method}). Because of the computational advantages described in Section~\ref{sec:intro}, we consider landmark-based shift-invariant kernels relying on the value $\delta={\mathbf x}_t - {\mathbf x} \in R^d$ and denoted by abuse of notation: \begin{equation} \label{eq:land-kernel} k(\delta) = k({\mathbf x}_t - {\mathbf x}) = k({\mathbf x}_t, {\mathbf x}), \end{equation} where ${\mathbf x}_t \in {\mathbb{R}}^d$ is the landmark of the input space which all the instances are compared to, that strongly characterizes the kernel. At each iteration of our Gradient Boosting procedure, we optimize not only this landmark but also the kernel function itself, exploiting the flexibility of the framework provided by~\cite{LetarteMG19}. We write the kernel as a sum of Random Fourier Features~\cite{rahimi2008random} and we learn a posterior distribution over them. We achieve this by studying the generalization capabilities of the so-defined functions through the lens of the PAC-Bayesian theory. This theoretical analysis ultimately allows us to derive a closed-form solution of the posterior distribution $q_t$ (over the RFF at a given iteration $t$), which is guaranteed to minimize the kernel alignment loss. In the following section, we recall the framework of~\cite{LetarteMG19} and adapt it to our scenario. \section{Pseudo-Bayesian Kernel Learning with RFF} \label{sec:posterior} The kernel learning method proposed by \cite{LetarteMG19} builds on the Random Fourier Features approximations proposed in~\cite{rahimi2008random}. Given a shift-invariant kernel $k(\delta)=k({\mathbf x}-{\mathbf x}')=k({\mathbf x},{\mathbf x}')$, \cite{rahimi2008random} show that $$k({\mathbf x}-{\mathbf x}')=\esp{{\bm{\omega}}\sim p}\cos\left({\bm{\omega}}\cdot({\mathbf x}-{\mathbf x}')\right),$$ with $p$ the Fourier transform of $k$ defined as $$p({\bm{\omega}})=\frac{1}{(2\pi)^d}\int_{{\mathbb{R}}^d}k(\delta)\exp(-i{\bm{\omega}}\cdot\delta)d\delta.$$ This allows the kernel $k$ to be approximated in practice by drawing $K$ vectors from $p$ denoted by ${\bm{\Omega}} = \{{\bm{\omega}}_j\}_{j=1}^K\sim p^K$ and computing $$ k({\mathbf x}-{\mathbf x}') \simeq \frac{1}{K}\sum_{j=1}^{K}\cos\left({\bm{\omega}}_j\cdot({\mathbf x}-{\mathbf x}')\right).$$ The larger $K$, the better the resulting approximation. Instead of drawing RFF for approximating a known kernel, \cite{LetarteMG19} propose to learn a new one by deriving a posterior distribution $q_t$ for a given landmark point in $\{{\mathbf x}_t\}_{t=1}^T$: $$k_{q_t}({\mathbf x}_t-{\mathbf x})=\esp{{\bm{\omega}}\sim q_t} \cos\left({\bm{\omega}}\cdot({\mathbf x}_t-{\mathbf x})\right).$$ A distribution $q_t$ is learned by minimizing a PAC-Bayesian generalization bound on the expected value of the loss between the landmark ${\mathbf x}_t$ and any point $({\mathbf x},y) \sim \mathcal{D}$. Let $({\mathbf x}_t,y_t)$ be a sample, then its expected loss $\mathcal{L}^t$ and empirical loss $\widehat{\mathcal{L}}^t$ are respectively defined as $$\mathcal{L}^t=\esp{({\mathbf x},y)\sim \mathcal{D}}\ell(k_{q_t}({\mathbf x}_t-{\mathbf x})),\quad\mbox{ and }\quad \widehat{\mathcal{L}}^t=\frac{1}{n-1}\sum_{j=1,j\neq t}^n\ell(k_{q_t}({\mathbf x}_t-{\mathbf x}_j)).$$ Using the PAC-Bayesian theory, they obtain the following theorem, under the linear loss \mbox{$\ell(k_{q_t}({\mathbf x}_t-{\mathbf x})) = \frac12 - \frac12y_tyk_{q_t}({\mathbf x}_t-{\mathbf x})$}, by expressing the loss as \begin{align*} \mathcal{L}^t(k_{q_t})\ &=\ \mathcal{L}^t\left( \esp{{\bm{\omega}}\sim p} h_{\bm{\omega}}^t\right)\\ &=\ \esp{{\bm{\omega}}\sim p}\mathcal{L}^t(h_{\bm{\omega}}^t), \end{align*} with $h_{\bm{\omega}}^t({\mathbf x})=\cos({\bm{\omega}}\cdot({\mathbf x}_t-{\mathbf x}))$. We note that the result also stands for any $[0,1]$-valued convex loss $\ell$. Indeed, by Jensen's inequality, we have $\mathcal{L}^t(k_{q_t})= \mathcal{L}^t( \espdevant{{\bm{\omega}}\sim p} h_{\bm{\omega}}^t)\leq \espdevant{{\bm{\omega}}\sim p}\mathcal{L}^t(h_{\bm{\omega}}^t)$. \begin{theorem} [Theorem 1 from \cite{LetarteMG19}] \label{ref:theoletarte} For $s>0$, $i\in\{1,\dots,n\}$, a convex loss function $\ell:{\mathbb{R}}\times{\mathbb{R}}\to[0,1]$, and a prior distribution $p$ over ${\mathbb{R}}^d$, with probability $1-\epsilon$ over the random choice of $S\sim\mathcal{D}^n$, we have for all $q$ on ${\mathbb{R}}^d$: $$\mathcal{L}^t(k_q)\leq \esp{{\bm{\omega}}\sim p}\widehat\mathcal{L}^t(h_{\bm{\omega}}^t)+\frac{1}{s}\Bigg(\text{KL}(q\Vert p) + \frac{s^2}{2(n-1)}+\ln\frac{1}{\epsilon}\Bigg),$$ where $\text{KL}(q\Vert p)=\espdevant{{\bm{\omega}}\sim p}\frac{p({\bm{\omega}})}{q({\bm{\omega}})}$ is the Kullback-Leibler divergence between $q$ and $p$. \end{theorem} It is well known~\cite{alquier2016properties,catoni2007pac,germain2009pac} that the closed form solution minimizing the bound is the pseudo-posterior distribution $Q^t$ computed as \begin{equation}\label{eq:closed_form_aistats} Q^t_j=\frac{1}{Z_t}\exp\Bigg(-\beta\sqrt{n}\widehat{\mathcal{L}}^t(h_{\bm{\omega}}^t)\Bigg), \end{equation} for $j=1,\dots,K$ with $\beta$ a parameter and $Z_t$ the normalization constant. Finally, given a sample point $({\mathbf x}_t,y_t)$ and $K$ vectors ${\bm{\omega}}$ denoted by ${\bm{\Omega}}^t = \{{\bm{\omega}}_j^t\}_{j=1}^K\sim p^K$, their kernel is finally defined as: $$k_{Q^t}({\mathbf x}_t-{\mathbf x})=\sum_{j=1}^{K}Q^t_j\cos({\bm{\omega}}_j\cdot({\mathbf x}_t-{\mathbf x})).$$ Then \cite{LetarteMG19} learn a representation of the input space of $n_L$ features where each new feature $t=1,\ldots,n_L$ is computed using the kernel $k_{Q^t}$ with the sample $({\mathbf x}_t,y_t)$. To do so, they consider a set of $n_L$ landmarks $L=\{({\mathbf x}_t,y_t)\}_{t=1}^{n_L}$ which they chose either as a random subset of the training set, or as the centers of a clustering of the training set. Then, during a second step, a (linear) predictor can be learned from the new representation. It is worth noticing that this kind of procedure exhibits two drawbacks. First, the model can be optimized only after having learned the representation. Second, the set of landmarks $L$ has to be fixed before learning the representation. Thus, the constructed representation is not guaranteed to be relevant for the learning algorithm considered. To tackle these issues, we propose in the next section a method performing the two steps at the same time through a gradient boosting algorithm, that allows us to learn the set of landmarks. \section{Gradient Boosting for Random Fourier Features} \label{sec:our_method} The approach we propose to follow the widely used gradient boosting framework first proposed by~\cite{friedman2001greedy}. Before presenting our contribution, we quickly recall the classical gradient boosting algorithm instantiated with the least square loss. \begin{algorithm}[t] \caption{Gradient Boosting with least square loss~\cite{friedman2001greedy}\label{algo:gboost}} \SetKwInOut{Input}{Input}\SetKwInOut{Output}{Output} \Input{Training set $S=\{{\mathbf x}_i,y_i\}_{i=1}^n$ with $y_i\in\{-1,1\}$;\\ $T$: number of iterations; $v$: learning rate} \Output{Weighted sum of predictors: $H({\mathbf x})=\text{sign}\left(H_0({\mathbf x})+\underset{t=1}{\overset{T}{\sum}}v\alpha_t h_{a_t}({\mathbf x})\right)$} \begin{algorithmic}[1] \STATE $\displaystyle H_0({\mathbf x}) = \frac1n \sum_{i=1}^n y_i $ \FOR {$t=1,\dots,T$} \STATE $\forall i=1,\dots,n,\quad \tilde{y}_i = y_i - H_{t-1}({\mathbf x}_i)$ \STATE $\displaystyle (\alpha_t,a_t)=\argmin_{\alpha,a} \sum_{i=1}^n\big(\tilde{y}_i-\alpha h_a({\mathbf x})\big)^2,$ where $a$ denotes the parameters of the model $h_a$ \STATE $H_t({\mathbf x}) = H_{t-1}({\mathbf x}) + v\alpha_t h_{a_t}({\mathbf x})$ \ENDFOR \end{algorithmic} \end{algorithm} \subsection{Gradient Boosting in a Nutshell} Gradient boosting is an ensemble method that aims at learning a weighted majority vote over an ensemble of predictors in a greedy way by learning iteratively the predictors to add to the ensemble. The final majority vote is of the form $$ \forall {\mathbf x}\in{\mathbb{R}}^d,\ H({\mathbf x}) = \text{sign}\left(H_0({\mathbf x})+\underset{t=1}{\overset{T}{\sum}}v\alpha_t h_{a_t}({\mathbf x})\right), $$ where $H_0$ is a predictor fixed before the iterative process and is usually set such that it returns the same value for every data point, and $v\alpha_t$ is the weight associated to the predictor $h_{a_t}$ ($v$ is called the learning rate\footnote{The parameter $v$ is often referred as learning rate or shrinkage parameter. Decreasing $v$ usually improves the empirical performances~\cite{buhlmann2007boosting} but requires to increase the number of boosting iterations $T$.} and is fixed for each iteration, and $\alpha_t$ is called the optimal step size learned at the same time as the parameters $a_t$ of the predictor $h_{\alpha_t}$). Given a differentiable loss, the objective of the gradient boosting algorithm is to perform a gradient descent where the variable to be optimized is the ensemble and the function to be minimized is the empirical loss. \iffalse The ensemble is initialized to a set that contains a single predictor $H_0(x)$ outputting the same prediction $\alpha$ for every input example. Then at each iteration, a differentiable loss function $\ell$ is evaluated between the target values and the current prediction, and a predictor is trained to output the negative gradient of the loss with respect to the current prediction. In other words, it performs a gradient descent in functional space where the variable to be optimized is the ensemble and the function to be minimized is the empirical loss. \fi We now remind the gradient boosting algorithm instantiated with the least square loss in Algorithm~\ref{algo:gboost} proposed by~\cite{friedman2001greedy}. At the beginning (line {\bf 1}), the ensemble is constituted by only one predictor, the one that outputs the mean label over the whole training set. At each iteration, the first step (line {\bf 3}) consists in computing the negative gradient of the loss, also called the residual and denoted by $\tilde{y}_i$, for each training example $({\mathbf x}_i,y_i)\in S$. Note that in the case of the least square loss the residual of an example is the deviation between its true label and the returned value of the current model. Then, it learns the parameters $a_t$ of the predictor $h_{\alpha_t}$, along with the optimal step size $\alpha_t$, that fit the best the residuals (line {\bf 4}). Finally, the current model is updated by adding $v\alpha_th_{a_t}(\cdot)$ (line {\bf 5}) to the vote. \iffalse The ensemble is initialized to output the mean label over all the training set (line {\bf 1}). At each iteration the negative gradient of the loss---also called residual---$\tilde{y}_i$ is computed in line {\bf 3}. Let $h_a : {\mathbb{R}}^d\rightarrow {\mathbb{R}}$ be some predictor with $a$ its parameters. Then in line {\bf 4}, we learn simultaneously the optimal parameters $a_t$ of $h$ and the optimal step size $\alpha_t$ for $\alpha h_a$ to fit at best the residuals. Finally, the current model is updated in line {\bf 5}. In addition to the step size $\alpha_t$, the predictor $h_a$ is multiplied by a parameter $v\in(0,1]$ before being added to the ensemble. This parameter is often known as learning rate or shrinkage parameter and decreasing $v$ usually improves empirical performances~\cite{buhlmann2007boosting} but requires to increase the number of boosting iterations $T$. \fi \subsection{Our Algorithm} We now propose to benefit from the gradient boosting to tackle the drawbacks of the landmark-based approach of~\cite{LetarteMG19} recalled in~Section~\ref{sec:posterior}. Our objective is to learn at the same time the landmarks ({\it i.e.}, the representation) and the classification model. Let $k$ be a shift-invariant kernel and let $p$ be its Fourier transform. At each iteration $t$, given ${\bm{\Omega}}^t = \{{\bm{\omega}}_j^t\}_{j=1}^K\sim p^K$ a set of $K$ random features drawn from $p$, the objective is twofold: \begin{itemize} \item Learn the parameters $a_t$ of the base learner $h_{a_t}$ defined as \begin{equation}\label{eq:predictor} h_{a_t}({\mathbf x})=\sum_{j=1}^K Q_j^t\cos\Big({\bm{\omega}}_j^t\cdot({\mathbf x}_t-{\mathbf x})\Big). \end{equation} In our case, the parameters to be learned are $a_t=({\mathbf x}_t,Q^t)$ where ${\mathbf x}_t$ is a landmark, and $Q^t$ is the pseudo-posterior distribution that can be computed using a closed-form similar to Equation~\eqref{eq:closed_form_aistats}. \item Compute the optimal step size $\alpha_t$. \end{itemize} In order to benefit from the theoretical guarantees of Theorem~\ref{ref:theoletarte}, and of the closed form of Equation~\eqref{eq:closed_form_aistats}, we propose the following greedy approach consisting in computing the landmark ${\mathbf x}_t$ by fixing the weight of each random features to $\frac{1}{K}$ (Equation~\eqref{eq:loss_landmark}), then $Q^t$ thanks to its closed-form (Equation~\eqref{eq:closed_form_Q}), and finally $\alpha_t$ (Equation~\eqref{eq:alpha}). First, given the set of random features ${\bm{\Omega}}^t$, we look for the landmark ${\mathbf x}_t \in {\mathbb{R}}^d$ that minimizes the average least square loss between the residuals and the kernel approximation defined as: \begin{equation}\label{eq:loss_landmark} f_{{\bm{\Omega}}^t} ({\mathbf x}_t)=\frac{1}{n}\sum_{i=1}^{n}\Bigg(\tilde{y_i}-\frac{1}{K}\sum_{j=1}^K \cos\Big({\bm{\omega}}_j^t\cdot({\mathbf x}_t-{\mathbf x}_i)\Big)\Bigg)^2. \end{equation} The minimization is done by performing a gradient descent of $f_{{\bm{\Omega}}^t}$ to find the landmark ${\mathbf x}_t$ that minimizes $f_{{\bm{\Omega}}^t}$ where the gradient of $f_{{\bm{\Omega}}^t}$ with respect to ${\mathbf x}_t$ is given by: \begin{equation}\label{eq:gradient_wrt_landmark} \frac{\partial f_{{\bm{\Omega}}^t}}{\partial {\mathbf x}_t}=\frac{2}{n}\sum_{i=1}^{n}\Bigg(\frac1K\sum_{j=1}^{K}{\bm{\omega}}_j^t\sin\Big({\bm{\omega}}_j^t\cdot({\mathbf x}_t-{\mathbf x}_i)\Big)\Bigg)\Bigg(\tilde{y_i}-\frac1K\sum_{j=1}^{K}\cos\Big({\bm{\omega}}_j^t\cdot({\mathbf x}_t-{\mathbf x}_i)\Big)\Bigg). \end{equation} Second, given the landmark ${\mathbf x}_t$ found during the gradient descent, and given the set ${\bm{\Omega}}^t$, we compute the pseudo-posterior distribution $Q^t$ as: \begin{align}\label{eq:closed_form_Q} \nonumber Q_j^t\ &=\ \frac{1}{Z_t} \exp\Big(-c f_{{\bm{\omega}}_j^t}({\mathbf x}_t) \Big)\\ &= \ \frac{1}{Z_t} \exp\left(\frac{c}{n}\sum_{i=1}^{n}\Bigg(\tilde{y_i}- \cos\Big({\bm{\omega}}_j^t\cdot({\mathbf x}_t-{\mathbf x}_i)\Big)\Bigg)^2\right), \end{align} for $j=1,\ldots,K$ with $c\geq 0$ a parameter and $Z_t$ the normalization constant. To finish, the optimal step size $\alpha_t$ is obtained by setting to $0$ the derivative of line {\bf 4} with respect to $\alpha$. We then have \begin{equation}\label{eq:alpha} \alpha_t\ = \ \displaystyle \frac{\displaystyle \sum_{i=1}^n\tilde{y}_ih_{a_t}({\mathbf x}_i)}{\displaystyle \sum_{i=1}^nh_{a_t}({\mathbf x}_i)^2}. \end{equation} This approach has two clear advantages compared to the two-step method of \cite{LetarteMG19}, where one learns the mapping first---for a pre-defined set of landmarks---and learns the predictor afterwards. \begin{enumerate} \item Gradient Boosting allows constructing iteratively the mapping by optimizing one landmark at each step \item The final predictor is learned at the same time and the learning procedure can be stopped when the empirical loss stops decreasing. \end{enumerate} Consequently, the final mapping is likely to be less redundant and more suitable for the task at hand. \section{Experiments} \label{sec:expe} In this section, we provide an empirical study of our method, referred as \underline{GBRFF}. Firstly, we compare the performances of \underline{GBRFF} with the two-step procedure from~\cite{LetarteMG19}, referred as~\underline{PBRFF}, and also with boosting-based methods described in the next paragraph. Then, we compare the influence of the number of landmarks between \underline{GBRFF} and \underline{PBRFF}. \paragraph{Experimental Setup.} For \underline{GBRFF}, we consider predictors as described in Equation~\eqref{eq:predictor} and select by cross-validation the parameter $c\in\{0\}\cup 2^{\{0,\dots,10\}}$. We compare \underline{GBRFF} with the following algorithms : \begin{itemize} \item \underline{PBRFF}~\cite{LetarteMG19} consists in first learning the new representation and then learning a linear SVM on the mapped training set. We select by cross-validation its parameters $\beta\in10^{\{-3,\dots,3\}}$ and $C\in10^{\{-3,\dots,3\}}$. \item \underline{XGB} for Xgboost ~\cite{chen2016xgboost} and \underline{LGBM} for LightGBM~\cite{ke2017lightgbm} which are state-of-the-art gradient boosting methods using trees as base predictors. For these methods, we select by cross-validation the maximum depth of the trees in $\{1,\dots,5\}$. \item \underline{MKBOOST}~\cite{xia2013mkboost} which is a Multiple Kernel Learning method based on the AdaBoost algorithm. At each boosting iteration, it selects the best performing kernel plugged inside a SVM, according to the Boosting weight distribution over the training examples. As it is done by the authors, we consider at each iteration 14 RBF kernels $k({\mathbf x},{\mathbf x}')=\exp(-\gamma\Vert{\mathbf x}-{\mathbf x}'\Vert^2)$ with $\gamma\in2^{\{-6,\dots,7\}}$ and 3 polynomial kernels $k({\mathbf x},{\mathbf x}')=({\mathbf x}^T{\mathbf x}')^d$ with $d\in\{1,2,3\}$. We select by cross-validation the SVM parameter $C\in 10^{\{-5,\dots,3\}}$. \item \underline{BMKR}~\cite{wu2017boosting} which is another Multiple Kernel Learning method based on gradient boosting with least square loss. Similarly as in \underline{MKBOOST}, it selects at each iteration the best performing kernel plugged inside an SVR to learn the residuals. It considers at each iteration 10 RBF kernels with $\gamma\in2^{\{-4,\dots,5\}}$ and the linear kernel $k({\mathbf x},{\mathbf x}')= {\mathbf x}^T{\mathbf x}'$. We select by cross-validation the SVR parameter $C\in 10^{\{-5,\dots,3\}}$. \end{itemize} For the four methods based on gradient boosting, we further select by cross-validation the learning rate $v\in\{1, 0.5, 0.1, 0.05, 0.01\}$. The five boosting-based methods are run for $T=200$ iterations. As for \underline{PBRFF} which is not an iterative method, we select randomly with replacement $n_L=200$ landmarks from the training set. For the two methods \underline{PBRFF} and \underline{GBRFF} using random features, we fix the number of random features $K$ to $100$ and we draw them from the Fourier transform of the Gaussian kernel which is the normal law. We consider $14$ datasets coming mainly from the UCI repository. As we deal with binary classification problems, we have binarized the datasets as described in Table \ref{tab:datasets} where the classes considered respectively as the label `-1' and as the label `+1' are specified. \begin{table}[h]\centering \caption{\label{tab:datasets} Description of the datasets (n: number of examples, d: number of features, c: number of classes) and the classes chosen as negative (Label -1) and positive (Label +1)} \resizebox{0.9\textwidth}{!}{\begin{tabular}{lrrrrrlrrrrr} \toprule Name & n & d & c & Label -1 & Label +1 & Name & n & d & c & Label -1 & Label +1 \\ \midrule wine & 178 & 13 & 3 & 2, 3 & 1 & wdbc & 569 & 30 & 2 & B & M \\ sonar & 208 & 60 & 2 & M & R & balance & 625 & 4 & 3 & B, R & L \\ glass & 214 & 11 & 6 & 2 3 5 6 7 & 1 & australian & 690 & 14 & 2 & 0 & 1 \\ newthyroid & 215 & 5 & 3 & 1 & 2, 3 & pima & 768 & 8 & 2 & 0 & 1 \\ heart & 270 & 13 & 2 & 1 & 2 & german & 1000 & 23 & 2 & 1 & 2 \\ bupa & 345 & 6 & 2 & 2 & 1 & splice & 3175 & 60 & 2 & +1 & -1 \\ iono & 351 & 34 & 2 & g & b & spambase & 4597 & 57 & 2 & 0 & 1 \\ \bottomrule \end{tabular}} \end{table} All datasets are normalized such that each feature has a mean of $0$ and a variance of $1$. For each dataset, we generate $20$ random splits of $30\%$ training examples and $70\%$ testing examples. The hyper-parameters of all the methods are tuned by a \mbox{$5$-fold} cross-validation on the training set. We report in Table~\ref{tab:results1} for each dataset the mean results over the $20$ splits. In terms of accuracy, our method \underline{GBRFF} shows competitive results with the state-of-the-art as it obtains the best performances on 5 datasets out of $14$ with the best average rank among the six methods. This confirms the relevance of our algorithm. \begin{table}[h]\centering \caption{\label{tab:results1}Mean test accuracy $\pm$ standard deviation over 20 random train/test splits.} \resizebox{0.9\textwidth}{!}{\begin{tabular}{l c c c c c c} \toprule Dataset & XGB \cite{chen2016xgboost} & LGBM \cite{ke2017lightgbm} & MKBOOST \cite{xia2013mkboost} & BMKR \cite{wu2017boosting} & PBRFF \cite{LetarteMG19} & GBRFF\\ \midrule wine & 94.92 $\pm$ 2.5& 95.72 $\pm$ 2.1& 98.56 $\pm$ 1.3& \textbf{99.08} $\pm$ 0.6& 97.92 $\pm$ 1.2& 96.80 $\pm$ 2.2\\ sonar & 76.34 $\pm$ 2.8& 76.10 $\pm$ 3.2& \textbf{77.77} $\pm$ 5.8& 71.78 $\pm$ 4.3& 75.82 $\pm$ 4.1& 76.10 $\pm$ 7.5\\ glass & \textbf{79.70} $\pm$ 3.2& 78.33 $\pm$ 4.1& 78.27 $\pm$ 2.8& 77.93 $\pm$ 2.9& 77.27 $\pm$ 3.4& 75.70 $\pm$ 3.0\\ newthyroid & 90.79 $\pm$ 2.9& 83.01 $\pm$ 4.3& 91.26 $\pm$ 13.8& 94.17 $\pm$ 1.4& \textbf{95.89} $\pm$ 1.6& 93.18 $\pm$ 1.6\\ heart & 79.71 $\pm$ 3.3& 80.74 $\pm$ 2.4& 77.67 $\pm$ 2.8& \textbf{83.15} $\pm$ 2.0& 83.02 $\pm$ 2.2& 82.54 $\pm$ 2.2\\ bupa & 66.10 $\pm$ 1.8& 67.19 $\pm$ 2.7& 58.39 $\pm$ 4.0& 62.11 $\pm$ 3.3& 65.48 $\pm$ 2.7& \textbf{67.58} $\pm$ 3.2\\ iono & 89.25 $\pm$ 1.7& 88.64 $\pm$ 2.1& 91.77 $\pm$ 5.9& 92.40 $\pm$ 2.7& \textbf{93.21} $\pm$ 1.9& 85.55 $\pm$ 2.1\\ wdbc & 94.60 $\pm$ 1.8& 95.24 $\pm$ 1.8& 95.16 $\pm$ 1.7& 96.20 $\pm$ 0.8& 95.99 $\pm$ 1.1& \textbf{96.40} $\pm$ 1.1\\ balance & 94.13 $\pm$ 2.4& 95.02 $\pm$ 2.2& 83.89 $\pm$ 9.3& 93.36 $\pm$ 1.2& \textbf{96.12} $\pm$ 1.4& 94.77 $\pm$ 1.0\\ australian & 85.33 $\pm$ 1.2& 85.65 $\pm$ 1.4& 80.46 $\pm$ 3.9& 85.70 $\pm$ 1.1& 85.66 $\pm$ 1.2& \textbf{85.72} $\pm$ 1.3\\ pima & 75.34 $\pm$ 1.8& 74.81 $\pm$ 2.0& 73.06 $\pm$ 2.5& 75.02 $\pm$ 1.6& 75.36 $\pm$ 2.1& \textbf{75.66} $\pm$ 1.9\\ german & 71.51 $\pm$ 1.2& 71.60 $\pm$ 1.4& 69.84 $\pm$ 1.3& 71.18 $\pm$ 2.0& 71.79 $\pm$ 1.3& \textbf{72.36} $\pm$ 1.5\\ splice & \textbf{96.35} $\pm$ 0.4& 96.26 $\pm$ 0.4& 82.70 $\pm$ 3.8& 86.42 $\pm$ 0.6& 85.27 $\pm$ 0.5& 88.16 $\pm$ 0.5\\ spambase & 94.20 $\pm$ 0.3& \textbf{94.25} $\pm$ 0.3& 90.45 $\pm$ 0.6& 92.34 $\pm$ 0.5& 91.60 $\pm$ 0.4& 92.33 $\pm$ 0.3\\ \midrule Average Rank& 3.40& 3.20& 4.40& 3.07& 2.80& 2.73\\ \bottomrule \end{tabular}} \end{table} \paragraph{Influence of the number of landmarks.} In Figure~\ref{fig:graph_newthyroid_bupa}, we analyze the accuracy of our landmark-based method \underline{GBRFF} in two variants. The first one named \underline{GBRFF Learn} corresponds to what was done in the previous experiment where at each iteration a landmark was learned. The second named \underline{GBRFF Random} considers at each iteration a landmark drawn randomly from the training set. In addition, we compare our method to \underline{PBRFF} which also draws the landmarks randomly from the training set. To gain relevant insights, the analysis is made on three datasets for which our method has better and worse performances compared to \underline{PBRFF}. We consider the datasets ``sonar'', ``newthyroid'' and ``bupa''. Overall, as expected, the larger the quantity of landmarks, the better the performances for all methods. We see on the three datasets that \underline{GBRFF Learn} presents better performances than \underline{GBRFF Random}. The difference is especially large when the number of landmarks is small. For ``sonar'' and ``bupa'', \underline{PBRFF} requires much more landmarks than \underline{GBRFF Learn} to reach its maximal value. This shows the importance of learning the landmarks compared to selecting them randomly as it allows converging faster to possibly better performances. On the other hand, the results on ``newthyroid'' are better for \underline{PBRFF}, no matter the number of landmarks used. This may happen because the linear classifier in the two methods is learned differently: it is learned using all landmarks by \underline{PBRFF} with a Linear SVM and learned one landmark at a time by \underline{GBRFF} with gradient boosting. \begin{figure}[h]\centering \makebox[\textwidth]{\includegraphics[width=\textwidth]{graph_sonar_newthyroid_bupa.pdf}} \\ \caption{Mean test accuracy over $20$ train/test splits on the ``sonar'', ``newthyroid'' and ``bupa'' datasets as a function of the number of landmarks used with \underline{PBRFF} and our two variants of \underline{GBRFF}.} \label{fig:graph_newthyroid_bupa} \end{figure} \begin{figure}[h]\centering \makebox[\textwidth]{\includegraphics[width=\textwidth]{bars_increase_number_landmarks.pdf}} \\ \caption{Mean test accuracy over $20$ train/test splits and over the $14$ datasets as a function of the number of landmarks used to train the two methods \underline{PBRFF} and \underline{GBRFF}. The mean values are displayed at the top of the bars, and the numbers of datasets where a method has the best performances are displayed at the bottom of the bars} \label{fig:bars_increase_number_landmarks} \end{figure} We summarize in Figure~\ref{fig:bars_increase_number_landmarks} the influence of the number of landmarks used to train \underline{PBRFF} and \underline{GBRFF}. The figure gives the mean test accuracy across all datasets and over the $20$ train/test splits. As seen in the previous experiment, with $200$ landmarks, \underline{PBRFF} and \underline{GBRFF} have similar performances with respectively $84.49\%$ and $85.03\%$ of mean accuracy and with better performances for \underline{GBRFF} on 8 datasets out of $1$4. However, when the number of landmarks decreases, \underline{GBRFF} demonstrates a clear superiority. Indeed, we can observe in Figure~\ref{fig:bars_increase_number_landmarks} that with $2$5 landmarks, \underline{GBRFF} provides a mean accuracy $0.21$ point higher than the one of \underline{PBRFF} while being better on $1$0 datasets, with $10$ landmarks it is $1.04$ points higher and better for $11$ datasets, with $5$ landmarks it gets $1.82$ points higher and is still better for $11$ datasets, with $3$ landmarks it is $3.35$ points higher and finally with only one landmark it is superior with $4.94$ points higher. Additionally, our method obtains the best performances in $12$ datasets out of $14$ with less than $3$ landmarks. Thus, the smaller the number of landmarks used, the better our method \underline{GBRFF} compared to \underline{PBRFF}. The gain is significative when the number of landmarks is smaller than 25 which also corresponds to learning very small representations. This shows the clear advantage of our landmark-based method when learning compact representations with few landmarks, especially when one has a limited budget. In this case, learning the landmarks to solve the task at hand is preferable to selecting them randomly. \section{Conclusion} \label{sec:conclu} In this paper, we propose a Gradient Boosting algorithm where a kernel is learned at each iteration; the kernel being expressed with random Fourier features (RFF). Compared to state-of-the-art Multiple Kernel Learning techniques that select the best kernel function from a dictionary, and then plug it inside a kernel machine, we directly consider a kernel as a predictor that outputs a similarity to a point called landmark. We learn at each iteration a landmark by approximating the kernel as a sum of Random Fourier Features to fit the residuals of the gradient boosting procedure. Building on a recent work~\cite{LetarteMG19}, we learn a pseudo-distribution over the RFF through a closed-form solution that minimizes a PAC-Bayes bound to induce a new kernel function tailored for the task at hand. The experimental study shows the competitiveness of the proposed method with state-of-the-art boosting and kernel learning methods, especially when the number of iterations used to train our model is small. So far, the landmarks have been learned without any constraint. A promising future line of research is to add a regularization on the set of landmarks to foster diversity. In addition, the optimization of a landmark at each iteration can be computationally expensive when the number of iterations is large, and a possibility to speed-up the learning procedure is to derive other kernel approximations where the landmarks can be computed with a closed-form solution. Other possibilities regarding the scalability include the use of standard gradient boosting tricks \cite{ke2017lightgbm,chen2016xgboost} such as sampling or learning the kernels in parallel. Another perspective could be to extend the analysis of~\cite{LetarteMG19} along with our algorithm to random Fourier features for operator-valued kernels~\cite{brault2016random} useful for multi-task learning or structured output. \subsubsection*{Acknowledgments} This work was supported in part by the French Project APRIORI ANR-18-CE23-0015. \small \bibliographystyle{plain}
{'timestamp': '2019-06-17T02:14:15', 'yymm': '1906', 'arxiv_id': '1906.06203', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06203'}
arxiv
\section{Introduction}\label{sec:introduction} \begin{quote} ``\dots it is a constant source of annoyance when you come up with a clever special algorithm which then gets beaten by translation to SAT.'' \\\mbox{}\hfill---Chris Jefferson \end{quote} The satisfiability (SAT) problem is to determine if a given Boolean expression can be satisfied---is there some way of assigning true and false to its variables that makes the whole formula true? Despite at first seeming disconnected from most of the kinds of problems that mathematicians care about we argue in this paper that it is in the interests of mathematicians to have a familiarity with SAT solving and encoding problems in SAT. An immense amount of effort over the past several decades has produced SAT solvers that are not only practical for many problems but are actually the fastest known way of solving an impressive variety of problems such as software and hardware verification problems~\cite{biere2009handbook}. They have also recently been used to resolve long-standing mathematical conjectures~\cite{heule2017solving} and construct large combinatorial designs~\cite{bright2018sat}. Since 2018, the computer algebra system Maple has included the award-winning SAT solver MapleSAT~\cite{liang2017empirical} as its built-in SAT solver. This solver can be used through the \texttt{Satisfy} command of the \texttt{Logic} package. \texttt{Satisfy} returns a satisfying assignment of a given Boolean expression (if one exists) or \texttt{NULL} if no satisfying assignment exists. In this paper we demonstrate through a number of detailed examples how \texttt{Satisfy} can be an effective and efficient way of solving a variety of problems and puzzles. Very little prerequisites are necessary to understand this paper; the main necessary background is a familiarity with Boolean logic which we outline in Section~\ref{sec:background}. We then present effective solutions to the $n$-queens problem (Section~\ref{sec:nqueens}), logic puzzles like the Einstein riddle (Section~\ref{sec:logic}), Sudoku puzzles (Section~\ref{sec:sudoku}), the maximum clique problem (Section~\ref{sec:clique}), Euler's Graeco-Latin square problem (Section~\ref{sec:latin}), and the 15-puzzle (Section~\ref{sec:15puzzle}). In each case we require no knowledge of any of the special-purpose search algorithms that have been proposed to solve these problems; once the problems have been encoded into Boolean logic they are automatically solved using Maple's \texttt{Satisfy}. All of the examples discussed in this paper were implemented and run in Maple 2018 and Maple 2019. Due to space constraints we have not included our code in this paper, but Maple worksheets containing complete implementations have been made available online through the Maple Application Center~\cite{brightapps}. \section{Background}\label{sec:background} A basic understanding of Boolean logic is the only prerequisite necessary to understand the solutions described in this paper. One of the main advantages of Boolean logic (but also one of its main disadvantages) is its simplicity: each variable can assume only one of two values denoted by $\text{true}$ and $\text{false}$. Boolean expressions consist of variables joined by Boolean operators. The most common Boolean operators (and the ones available in the \texttt{Logic} package of Maple) are summarized in Table~\ref{tbl:operators}. \begin{table}[b] \begin{center} \begin{tabular}{c@{\quad}c@{\qquad}c@{\qquad}c} \bf Name & \bf Symbol & \bf Arity & \bf Maple Syntax \\ Negation & $\lnot$ & 1 & \texttt{\&not} \\ Conjunction & $\land$ & $n$-ary & \texttt{\&and} \\ Disjunction & $\lor$ & $n$-ary & \texttt{\&or} \\ Implication & $\mathbin{\Rightarrow}$ & 2 & \texttt{\&implies} \\ Biconditional & $\mathbin{\Leftrightarrow}$ & 2 & \texttt{\&iff} \\ Alternative denial & $\mathbin{\uparrow}$ & $n$-ary & \texttt{\&nand} \\ Joint denial & $\mathbin{\downarrow}$ & $n$-ary & \texttt{\&nor} \\ Exclusive disjunction & $\mathbin{\underline{\lor}}$ & $n$-ary & \texttt{\&xor} \\ \end{tabular} \end{center} \caption{The Boolean logical operators available in Maple.}\label{tbl:operators} \end{table} The $\lor$ (or), $\land$ (and), and $\lnot$ (not) operators have meanings based on their everyday English meanings. In particular, $x_1\lor\dotsb\lor x_n$ is true exactly when at least one $x_i$ is true, $x_1\land\dotsb\land x_n$ is true exactly when all $x_i$ are true, and $\lnot x$ is true exactly when~$x$ is false. More generally, $x\mathbin{\Leftrightarrow} y$ is true exactly when $x$ and $y$ have the same truth values, $x\mathbin{\Rightarrow} y$ is false exactly when $y$ is true and $x$ is false, $x_1\mathbin{\underline{\lor}}\dotsb\mathbin{\underline{\lor}} x_n$ is true exactly when an odd number of $x_i$ are true, $x_1\mathbin{\uparrow}\dotsb\mathbin{\uparrow} x_n$ is true exactly when at least one~$x_i$ is false, and $x_1\mathbin{\downarrow}\dotsb\mathbin{\downarrow} x_n$ is true exactly when all~$x_i$ are false. A \emph{literal} is an expression of the form $x$ or $\lnot x$ where $x$ is a Boolean variable. A \emph{clause} is an expression of the form $l_1\lor\dotsb\lor l_n$ where all $l_i$ are literals. A \emph{conjunctive normal form} (CNF) expression is of the form $c_1\land\dotsb\land c_n$ where all~$c_i$ are clauses. A standard theorem of Boolean logic is that any expression can be converted into an equivalent expression in conjunctive normal form where two expressions are said to be \emph{equivalent} if they assume the same truth values under all variable assignments. The current algorithms used in state-of-the-art SAT solvers require that the input formula be given in conjunctive normal form. While this is convenient for the purposes of designing efficient solvers it is not convenient for the mathematician who wants to express their problem in Boolean logic---not all expressions are \emph{naturally} expressed in conjunctive normal form. An advantage that Maple has over most current state-of-the-art SAT solvers is that Maple does not require the input to be given in conjunctive normal form. Since the algorithms used by MapleSAT require CNF to work properly, Maple internally converts expressions into CNF automatically. This is done by using a number of equivalence transformations, e.g., the expression $x\mathbin{\Rightarrow} y$ is rewritten as $\lnot x\lor y$. Care has been taken to make the necessary conversion to CNF efficient. This is important because conversions that use the most straightforward equivalence rules generally require exponential time to complete. For example, the Maple command \texttt{Normalize} from the \texttt{Logic} package can be used to convert an expression into CNF. But watch out---many expressions explode in size following this conversion. For example, the expression $x_1\mathbin{\underline{\lor}}\dotsb\mathbin{\underline{\lor}} x_n$ when converted into CNF contains $2^{n-1}$ clauses. The main trick used to make the conversion into CNF efficient is the \emph{Tseitin transformation}~\cite{tseitin1970on}. This transformation avoids the exponential blowup of the straightforward transformations by using additional variables to derive a new formula that is satisfiable if and only if the original formula is satisfiable. For example, the expression $x_1\mathbin{\underline{\lor}}\dotsb\mathbin{\underline{\lor}} x_n$ is rewritten as $(t\mathbin{\underline{\lor}} x_3\mathbin{\underline{\lor}}\dotsb\mathbin{\underline{\lor}} x_n)\land C$ where~$t$ is a new variable and $C$ is the CNF formula \[ (\lnot x_1\lor x_2\lor t)\land(x_1\lor\lnot x_2\lor t)\land(x_1\lor x_2\lor\lnot t)\land(\lnot x_1\lor\lnot x_2\lor\lnot t) . \] The transformation is then recursively applied to $t\mathbin{\underline{\lor}} x_3\mathbin{\underline{\lor}}\dotsb\mathbin{\underline{\lor}} x_n$ (the part of the formula not in CNF) until the entire formula is in CNF. The Maple command \texttt{Tseitin} of the \texttt{Logic} package can be applied to convert an arbitrary formula into CNF using this translation. Thus, Maple offers us the convenience of not requiring encodings to be in CNF while avoiding the inefficiencies associated with a totally unrestricted encoding. \section{The $n$-queens problem}\label{sec:nqueens} \begin{figure} \begin{minipage}{0.7\linewidth} \centering\includegraphics[scale=0.25]{queens.pdf} \end{minipage} \begin{minipage}{0.1\linewidth} \mbox{}\\[-2\baselineskip] \begin{align*} Q_{1, 5} &= \text{true} \\ Q_{2, 7} &= \text{true} \\ Q_{3, 2} &= \text{true} \\ Q_{4, 6} &= \text{true} \\ Q_{5, 3} &= \text{true} \\ Q_{6, 1} &= \text{true} \\ Q_{7, 4} &= \text{true} \\ Q_{8, 8} &= \text{true} \end{align*} \end{minipage} \caption{A visual representation of a solution for the 8-queens problem (left) and the variables assigned to true in this solution using our SAT encoding.} \label{fig:queens} \end{figure} The $n$-queens problem is to place~$n$ chess queens on an $n\times n$ chessboard such that no two queens are mutually attacking (i.e., in the same row, column, or diagonal). The problem was first proposed for $n=8$ by Bezzel in 1848 and the first solution for general~$n$ was given by Pauls in 1874~\cite{bell2009survey}. The problem is solvable for all $n\geq4$; a solution for $n=8$ (found in 0.015 seconds using \texttt{Satisfy}) is shown in Figure~\ref{fig:queens}. The $n$-queens problem is a standard example of a constraint satisfaction problem~\cite{nadel1990representation}. The encoding that we use for this problem uses the $n^2$ Boolean variables $Q_{x,y}$ with $1\leq x,y\leq n$ to denote if there is a queen on square $(x,y)$. There are two kinds of constraints necessary for this problem: \emph{positive} constraints that say that there are $n$ queens on the board and \emph{negative} constraints that say that queens do not attack each other. A satisfying assignment of these constraints exists exactly when the $n$-queens problem is solvable. Since there are $n$ rows and each row must contain a queen the positive constraints are of the form $Q_{1,j} \lor \dotsb \lor Q_{n,j}$ for $1\leq j\leq n$. Similarly, each column must contain a queen; these constraints are of the form $Q_{i,1}\lor\dotsb\lor Q_{i,n}$ for $1\leq i\leq n$. The negative constraints say that if $(x,y)$ contains a queen then all squares attacked by $(x,y)$ do not contain a queen. These constraints are represented in Boolean logic by $Q_{x,y}\mathbin{\Rightarrow}\lnot(A_1\lor\dotsb\lor A_k)$ where $\{A_1,\dotsc,A_k\}$ are the variables ``attacked'' by a queen on $(x,y)$. \texttt{Satisfy} is able to solve the problem for all $n\leq32$ in under 1 second in each case using this simple encoding. \section{The Einstein riddle}\label{sec:logic} The Einstein riddle is a logic puzzle apocryphally attributed to Albert Einstein and is often stated with the remark that it is only solvable by 2\% of the world's population. The true source of the puzzle is unknown, but a version of it appeared in the magazine Life International in 1962. In the puzzle there are five houses in a row with each house a different colour and each house owned by a man of a different nationality. Additionally, each of the owners have a different pet, prefer a different kind of drink, and smoke a different brand of cigarette. Furthermore, the following information is given: \begin{enumerate} \item The Brit lives in the Red house. \item The Swede keeps dogs as pets. \item The Dane drinks tea. \item The Green house is next to the White house, on the left. \item The owner of the Green house drinks coffee. \item The person who smokes Pall Mall rears birds. \item The owner of the Yellow house smokes Dunhill. \item The man living in the centre house drinks milk. \item The Norwegian lives in the first house. \item The man who smokes Blends lives next to the one who keeps cats. \item The man who keeps horses lives next to the man who smokes Dunhill. \item The man who smokes Blue Master drinks beer. \item The German smokes Prince. \item The Norwegian lives next to the Blue house. \item The man who smokes Blends has a neighbour who drinks water. \end{enumerate} The puzzle is: Who owns the fish? To solve this riddle using Maple, we label the houses 1 to 5 and use the variables $S_{i,\textit{a}}$ where $1\leq i\leq 5$ and $\textit{a}$ is either a colour, a nationality, a pet, a drink, or a cigarette brand. Since there five possible house indices, five kinds of attributes, and five possible attributes for each attribute type, there are $5^3=125$ variables~$S_{i,\textit{a}}$. We know that each attribute is not shared among the five houses or their owners. Since there are exactly five houses, each attribute must appear exactly once among the five houses. The knowledge that each attribute appears at least once can be encoded as the clauses $\bigvee_{i=1}^5 S_{i,a}$ for each attribute $a$ and the knowledge that each attribute is not shared can be encoded as $S_{i,a}\mathbin{\Rightarrow}\lnot S_{j,a}$ where~$j$ is a house index not equal to $i$ and $a$ is an attribute. Additionally, the fact that each house has some colour is encoded as $\bigvee_{\text{colour $a$}}S_{i,a}$ for each house index~$i$ and the knowledge that each house cannot have two colours can be encoded as $S_{i,c}\mathbin{\Rightarrow}\lnot S_{i,d}$ where $i$ is a house index and $c$ and $d$ are two distinct colours (and similarly for the other kinds of attributes). The known facts can be encoded into logic fairly straightforwardly; for example, the first fact can be encoded into logic as $S_{i,\text{Brit}}\mathbin{\Rightarrow} S_{i,\text{red}}$ for house indices~$i$ and the last fact can be encoded as $S_{i,\text{Blends}}\mathbin{\Rightarrow}(S_{i-1,\text{water}}\lor S_{i+1,\text{water}})$ for $1<i<5$ and $(S_{1,\text{Blends}}\mathbin{\Rightarrow} S_{2,\text{water}})\land(S_{5,\text{Blends}}\mathbin{\Rightarrow} S_{4,\text{water}})$. Using \texttt{Satisfy} on these constraints produces the unique satisfying solution (that includes the equations $S_{4,\text{German}}=\text{true}$ and $S_{4,\text{fish}}=\text{true}$, thereby solving the puzzle) in under 0.01 seconds. \section{Sudoku puzzles}\label{sec:sudoku} \begin{figure} \begin{minipage}{0.5\linewidth} \centering\includegraphics[scale=0.25]{sudoku.pdf} \end{minipage} \begin{minipage}{0.5\linewidth} \mbox{}\\[-2\baselineskip] \begin{align*} S_{1,9,8} && S_{2,1,9} && S_{2,6,5} \\ S_{2,7,7} && S_{3,2,8} && S_{3,3,1} \\ S_{3,8,3} && S_{4,2,5} && S_{4,4,1} \\ S_{4,8,6} && S_{5,5,4} && S_{5,7,9} \\ S_{6,5,5} && S_{6,6,7} && S_{7,1,4} \\ S_{7,5,7} && S_{7,7,2} && S_{8,2,1} \\ S_{8,3,6} && S_{8,4,3} && S_{9,3,8} \end{align*} \end{minipage} \caption{A Sudoku puzzle estimated to have a difficulty rating of 11 stars, whereas the most challenging Sudoku puzzles that are usually published are given 5 stars. On the right are the starting constraints (as unit clauses) of our encoding for this puzzle.} \label{fig:sudoku} \end{figure} Sudoku is a popular puzzle that appears in many puzzle books and newspapers. Given a 9 by 9 grid whose squares are either blank or contain a number between~1 and 9, the objective is to fill in the blank squares in such a way that each row and column contains exactly one digit between 1 and 9. Additionally, each of the nine 3 by 3 subgrids which compose the grid (called blocks) must also contain exactly one digit between 1 and 9. Figure~\ref{fig:sudoku} contains a Sudoku puzzle designed by mathematician Arto Inkala and claimed to be the world's hardest Sudoku~\cite{collins2012worlds}. It is known that Sudoku can be modelled as a SAT problem~\cite{lynce2006sudoku} or a constraint satisfaction problem~\cite{russell2016artificial}. A straightforward encoding uses $9^3=729$ variables $S_{i,j,k}$ with $1\leq i,j,k\leq 9$ where $S_{i,j,k}$ is true exactly when the square $(i,j)$ contains the digit~$k$. The rules of Sudoku state that each square must be filled with a digit between~1 and~9 and that the same digit cannot appear twice in the same row, column, or block. The first constraint has the form $S_{i,j,1}\lor\dotsb\lor S_{i,j,9}$ for all $1\leq i,j\leq 9$ and the second constraint has the form $S_{i,j,k}\mathbin{\Rightarrow}\lnot S_{i',j',k}$ for all $1\leq i,j,i',j',k\leq 9$ where $(i,j)$ does not equal $(i',j')$ but is in the same row, column, or block as $(i,j)$. One can also include the constraints $S_{i,j,k}\mathbin{\Rightarrow}\lnot S_{i,j,k'}$ for all $1\leq i,j,k,k'\leq 9$ with $k\neq k'$ that say that each square can contain at most one digit. However, these constraints are unnecessary since they are logically implied by the first two constraints. In our tests, including these additional constraints slightly decreased the performance of \texttt{Satisfy}. Without the additional constraints the ``world's hardest Sudoku'' was solved in 0.25 seconds and with them it was solved in 0.33 seconds. Additionally, we developed a method of generating Sudoku puzzles with a unique solution using \texttt{Satisfy}. This allowed us to write an interactive Sudoku game where random puzzles can automatically be generated on command. To begin, \texttt{Satisfy} is used to find a solution to the above Sudoku constraints with an empty grid (no starting clues) and the produced satisfying solution generates a completed Sudoku grid~$R$. A random seed is passed to the SAT solver so that a different solution~$R$ is generated each time; this is done by passing the following \texttt{solveroptions} in the call to \texttt{Satisfy}: \[ \verb|[rnd_init_act=true, random_seed=floor(1000*time[real]())]| \] A random ordering of the entries of $R$ is generated and the first 50 entries are selected as the potential starting configuration of a Sudoku puzzle. This puzzle has the solution $R$ by construction, though other solutions may also exist. To verify that the generated solution is unique, we re-run \texttt{Satisfy} with the additional 50 unit clauses corresponding to the starting configuration along with the constraint $\bigvee_{R_{i,j}=k}\lnot S_{i,j,k}$ which blocks the solution $R$. If \texttt{Satisfy} returns another solution then we start over and find a new $R$ to try. Otherwise the first~50 entries of $R$ form a legal Sudoku puzzle. Additionally, it may be the case that we could use fewer than 50 entries and still obtain a Sudoku puzzle with a unique solution. Thus, we now estimate how many entries need to be assigned using only a few extra calls to the SAT solver. We define $l\coloneqq20$, $h\coloneqq50$, $m\coloneqq\operatorname{round}((l+h)/2)$ and repeat the last step except using only the first $m$ entries of $R$. If the resulting SAT instance is satisfiable then we need to use more than $m$ entries to ensure a unique solution and if the resulting SAT instance is unsatisfiable then we can perhaps use fewer than $m$ entries. Either way, we improve the bounds on how many entries to assign (in the former case we can update $l$ to $m$ and in the latter case we can update $h$ to~$m$) and this step can be repeated a few times to find more precise bounds on how many entries need to be assigned to ensure a unique solution exists. \section{The maximum clique problem}\label{sec:clique} The maximum clique problem is to find a clique of maximum size in a given graph. A \emph{clique} of a graph is a subset of its vertices that are all mutually connected (see Figure~\ref{fig:clique}). The decision version of this problem (does a graph contain a clique of size~$k$?) is in NP, meaning that it is easy to verify the correctness of a solution if one can be found. By the Cook--Levin theorem~\cite{cook1971complexity} the problem can be encoded into a SAT instance in polynomial time. However, the reduction involves simulating the computation of a machine that solves the maximum clique problem and is therefore not very convenient to use in practice. Thus, we provide a simpler encoding into Boolean logic. \begin{figure} \begin{minipage}{0.7\linewidth} \centering\includegraphics[scale=0.25]{graph.pdf} \end{minipage} \begin{minipage}{0.1\linewidth} \mbox{}\\[-2\baselineskip] \begin{align*} x_4&=\text{true} \\ x_9&=\text{true} \\ x_{12}&=\text{true} \\ x_{20}&=\text{true} \\ s_{4,1} &= \text{true} \\ s_{9,2} &= \text{true} \\ s_{12,3} &= \text{true} \\ s_{20,4} &= \text{true} \end{align*} \end{minipage} \caption{On the left is a visual representation of a graph with 20 vertices and a highlighted clique of size 4 that was found in 0.025 seconds. On the right are the important variables assigned to true in the assignment returned by \texttt{Satisfy} for our encoding of the maximum clique problem for this graph.} \label{fig:clique} \end{figure} Suppose the given graph~$G$ has vertices labelled $\{1,\dotsc,n\}$ and we want to find a clique of size~$k$ in~$G$. Our encoding uses the variables $x_1$, $\dotsc$, $x_n$ where $x_i$ represents that the vertex~$i$ appears in the clique we are attempting to find. We need to enforce a constraint that says that if $x_i$ and $x_j$ are true (for any vertices $1\leq i,j\leq n$) then the edge $\{i,j\}$ exists in the graph $G$. Equivalently, if the edge $\{i,j\}$ does not exist in the graph $G$ then the variables $x_i$ and $x_j$ cannot both be true (for any vertices $i,j$). In other words, if $\{i,j\}$ is an edge of the complement of $G$ then we know the clause $\lnot x_i\lor\lnot x_j$. Additionally, we need a way to enforce that the found clique is of size $k$. The most naive way to encode this is \[ (x_1\land\dotsb\land x_k)\lor\dotsb\lor(x_{n-k+1}\land\dotsb\land x_n) \] but this encoding is very inefficient in practice. A cleverer encoding uses Boolean counter variables $s_{i,j}$ (where $0\leq i\leq n$ and $0\leq j\leq k$) that represent that at least $j$ of the variables $x_1$, $\dotsc$, $x_i$ are assigned to true. We know that $s_{0,j}$ will be false for $1\leq j\leq k$ and that $s_{i,0}$ will be true for $0\leq i\leq n$. Additionally, we know that $s_{i,j}$ is true exactly when $s_{i-1,j}$ is true or $x_i$ is true and $s_{i-1,j-1}$ is true. This is represented by the formulas \[ s_{i,j} \mathbin{\Leftrightarrow} (s_{i-1,j}\lor(x_i\land s_{i-1,j-1})) \qquad \text{for $1\leq i\leq n$ and $1\leq j\leq k$} \] or (in conjunctive normal form) by the clauses $\lnot s_{i-1,j}\lor s_{i,j}$, $\lnot x_i\lor \lnot s_{i-1,j-1}\lor s_{i,j}$, $\lnot s_{i,j}\lor s_{i-1,j}\lor x_i$, and $\lnot s_{i,j}\lor s_{i-1,j}\lor s_{i-1,j-1}$. To enforce that the found clique contains at least $k$ vertices we also assign $s_{n,k}$ to true. To solve the maximum clique problem for a given graph $G$ we initialize~$k$ to~$3$ (assuming the graph has at least one edge, otherwise the problem is trivial) and use the above encoding to search for a clique of size~$k$. If such a clique exists we increase~$k$ by~$1$ and repeat the search in this manner until a clique of size~$k$ does not exist. The last satisfying assignment found then provides a maximum clique of~$G$. \begin{table} \begin{center} \begin{tabular}{c@{\quad}c@{\quad}c@{\quad}c@{\quad}c@{\quad}c} Benchmark & SAT time (sec) & Maple 2018 (sec) & Vertices & Edges & Clique size \\ \verb|brock200_2| & 23.52 & \bf 22.19 & 200 & 9876 & 12 \\ \verb|c-fat200-1| & 0.71 & \bf 0.03 & 200 & 1534 & 12 \\ \verb|c-fat200-2| & 2.32 & \bf 0.13 & 200 & 3235 & 24 \\ \verb|c-fat200-5| & \bf 9.07 & 20.63 & 200 & 8473 & 58 \\ \verb|c-fat500-1| & 4.78 & \bf 0.13 & 500 & 4459 & 14 \\ \verb|c-fat500-2| & 11.12 & \bf 0.82 & 500 & 9139 & 26 \\ \verb|c-fat500-5| & \bf 42.46 & 132.84 & 500 & 23191 & 64 \\ \verb|c-fat500-10| & \bf 134.42 & Timeout & 500 & 46627 & 126 \\ \verb|hamming6-2| & \bf 0.64 & 51.10 & 64 & 1824 & 32 \\ \verb|hamming6-4| & 0.04 & \bf 0.02 & 64 & 704 & 4 \\ \verb|hamming8-2| & \bf 58.51 & Timeout & 256 & 31616 & 128 \\ \verb|hamming8-4| & \bf 7.96 & 3393.26 & 256 & 20864 & 16 \\ \verb|johnson8-2-4| & \bf 0.01 & \bf 0.01 & 28 & 210 & 4 \\ \verb|johnson8-4-4| & \bf 0.23 & 7.80 & 70 & 1855 & 14 \\ \verb|johnson16-2-4| & \bf 5.62 & 642.24 & 120 & 5460 & 8 \\ \verb|keller4| & \bf 7.76 & 414.80 & 171 & 9435 & 11 \\ \verb|MANN_a9| & \bf 0.13 & 226.18 & 45 & 918 & 16 \\ \verb|p_hat300-1| & 11.81 & \bf 3.30 & 300 & 10933 & 8 \\ \verb|p_hat500-1| & 308.87 & \bf 34.60 & 500 & 31569 & 9 \\ \verb|p_hat700-1| & 1281.62 & \bf 169.68 & 700 & 60999 & 11 \end{tabular} \end{center} \caption{A comparison of the SAT method and the \texttt{MaximumClique} function of Maple 2018 on a collection of maximum clique benchmarks with a timeout of an hour.}\label{tbl:timings} \end{table} This implementation was tested on the maximum clique problems from the second DIMACS implementation challenge~\cite{johnson1996cliques}. Additionally, it was compared with Maple's \texttt{MaximumClique} function from the \texttt{GraphTheory} package that uses a branch-and-bound backtracking algorithm~\cite{kreher1998combinatorial}. Of the 80 benchmarks, the SAT method solved 18 in under 3 minutes and the branch-and-bound method solved 15. The SAT approach was faster in over half of the solved benchmarks and in one case solved a benchmark in 8 seconds that \texttt{MaximumClique} required 57 minutes to solve (see Table~\ref{tbl:timings}). The SAT method has been made available in Maple 2019 by using the \texttt{method=sat} option of \texttt{MaximumClique}. By default the \texttt{MaximumClique} function in Maple 2019 will run the previous method used by Maple and the SAT method in parallel and return the answer of whichever method finishes first. This hybrid approach is the method of choice especially when more than a single core is available. \section{Euler's Graeco-Latin square problem}\label{sec:latin} A \emph{Latin square} of order $n$ is an $n\times n$ matrix containing integer entries between~$1$ and~$n$ such that every row and every column contains each entry exactly once. Two Latin squares are \emph{orthogonal} if the superposition of one over the other produces all $n^2$ distinct pairs of integers between~$1$ and~$n$. A pair of orthogonal Latin squares was called a \emph{Graeco-Latin square} by the mathematician Leonhard Euler who in 1782 used Latin characters to represent the entries of the first square and Greek characters to represent the entries of the second square~\cite{euler1782recherches}. Figure~\ref{fig:latin} contains a visual representation of a Graeco-Latin square. \begin{figure} \begin{minipage}{0.5\linewidth} \centering\includegraphics[scale=0.25]{graeco-latin.pdf} \end{minipage} \begin{minipage}{0.5\linewidth} \mbox{}\\[-0.75\baselineskip] \begin{align*} A_{1,1,1} &= \text{true} & B_{1,1,1} &= \text{true} \\ A_{2,1,2} &= \text{true} & B_{2,1,10} &= \text{true} \\ A_{3,1,3} &= \text{true} & B_{3,1,5} &= \text{true} \\ A_{4,1,4} &= \text{true} & B_{4,1,2} &= \text{true} \\ A_{5,1,5} &= \text{true} & B_{5,1,6} &= \text{true} \\ A_{6,1,6} &= \text{true} & B_{6,1,9} &= \text{true} \\ A_{7,1,7} &= \text{true} & B_{7,1,4} &= \text{true} \\ A_{8,1,8} &= \text{true} & B_{8,1,7} &= \text{true} \\ A_{9,1,9} &= \text{true} & B_{9,1,3} &= \text{true} \\ A_{10,1,10} &= \text{true} & B_{10,1,8} &= \text{true} \\ \end{align*} \end{minipage} \caption{On the left is a visual representation of a Graeco-Latin square of order~$10$ with each colour denoting a separate integer. The entries of the Graeco square (represented by the small squares in the image) are superimposed onto the entries of the Latin square. On the right are the variables corresponding to the first column of this Graeco-Latin square that are assigned to true using our encoding.} \label{fig:latin} \end{figure} Euler studied the orders $n$ for which Graeco-Latin squares exist and found methods for constructing them when $n$ was odd or a multiple of 4. Since such squares do not exist for $n = 2$ and he was unable to find a solution for $n = 6$ he conjectured that Graeco-Latin squares do not exist when $n\equiv2\pmod{4}$. Euler's conjecture became famous as he was not able to resolve it in his lifetime. The first progress on the conjecture did not come until over a hundred years later when in 1901 Tarry showed that Graeco-Latin squares of order~$6$ do not exist~\cite{tarry1901probleme}. This gave credence to Euler's conjecture and many mathematicians thought the conjecture was true---in fact, three independent proofs of the conjecture were published in the early 20th century~\cite{macneish1922euler,peterson1902les,wernicke1910problem}. In 1959--1960 Bose, Shrikhande, and Parker~\cite{bose1960further,bose1959falsity} made explosive news (even appearing on the front page of the New York Times) by showing that these proofs were invalid by giving explicit constructions for Graeco-Latin squares in all orders except two and six. As it turns out, a lot of time could have been saved if Euler had a copy of Maple---we now show that Euler's conjecture can be automatically disproven in Maple. With \texttt{Satisfy} we are able to construct small Graeco-Latin squares without any knowledge of search algorithms or construction methods. Our encoding for the Graeco-Latin square problem of order~$n$ uses the $2n^3$ variables $A_{i,j,k}$ and $B_{i,j,k}$ with $1\leq i,j,k\leq n$. The variables $A_{i,j,k}$ will be true exactly when the $(i,j)$th entry of the Latin square $A$ is~$k$ and $B_{i,j,k}$ will be true exactly when the $(i,j)$th entry of the Graeco square $B$ is~$k$. There are three kinds of constraints that specify that $(A,B)$ is a Graeco-Latin square: Those that specify that every entry of~$A$ and~$B$ is an integer between~$1$ and~$n$, those that specify that the rows and columns of~$A$ and~$B$ contain no duplicate entries, and those that specify that~$A$ and~$B$ are orthogonal. Additionally, there are constraints that are not logically necessary but help cut down the search space. Some work has previously been done using SAT solvers to search for special kinds of Graeco-Latin squares~\cite{zaikin2015search}. The encoding we use is similar but takes advantage of the fact that Maple does not require encodings to be specified in conjunctive normal form. First, we specify that the entries of~$A$ are well-defined, i.e., consist of a single integer between~$1$ and~$n$. The constraints that say that each entry of $A$ contains at least one integer are of the form $A_{i,j,1}\lor\dotsb\lor A_{i,j,n}$ for each index pair $(i,j)$ and the constraints that say that each entry of $A$ contains at most one integer are of the form $A_{i,j,k}\mathbin{\Rightarrow}\lnot A_{i,j,l}$ for each index pair $(i,j)$ and integer $k\neq l$. Similar constraints are also used to specify that the entries of~$B$ are well-defined. Second, we specify that~$A$ is a Latin square, i.e., all columns and rows contain distinct entries. These have the form $A_{i,j,k}\mathbin{\Rightarrow}\lnot A_{i',j',k}$ where $1\leq k\leq n$ and $(i,j)\neq(i',j')$ but $(i,j)$ is in the same column or row as $(i',j')$. Similarly, we also specify that~$B$ is a Latin square. Third, we specify that~$A$ and $B$ are orthogonal, i.e., for every pair $(k,l)$ there exists some pair $(i,j)$ such that $A_{i,j,k}\land B_{i,j,l}$ holds. These constraints are of the form $\bigvee_{i,j=1}^n(A_{i,j,k}\land B_{i,j,l})$ for each pair $(k,l)$. Lastly, we include some ``symmetry breaking'' constraints. These constraints are not strictly necessary but they shrink the search space and thereby make the search more efficient. In general, when a search space splits into symmetric subspaces it is beneficial to add constraints that remove or ``break'' the symmetry. Graeco-Latin squares $(A,B)$ have a number of symmetries, in particular, a row or column permutation simultaneously applied to $A$ and $B$ produces another Graeco-Latin square. Also, any permutation of $\{1,\dotsc,n\}$ may be applied to the entries of either $A$ or $B$. The result of these symmetries is that any Graeco-Latin square can be transformed into one where the first row and column of $A$ has entries in ascending order (by permuting rows/columns) and the first row of $B$ has entries in ascending order (by renaming the entries of $B$). Thus, we can assume the constraint $\bigwedge_{i=1}^n(A_{1,i,i}\land B_{1,i,i}\land A_{i,1,i})$. Using this encoding the orders up to eight can be solved in 25 total seconds (including 14 seconds to show that no Graeco-Latin squares exist in order six), a Graeco-Latin square of order nine can be found in about 45 minutes, and a Graeco-Latin square of order ten can be found in about 23 hours, thereby disproving Euler's Graeco-Latin square conjecture. \section{The 15-puzzle}\label{sec:15puzzle} The 15-puzzle is a classic ``sliding tile'' puzzle that was first designed in 1880 and became very popular in the 1880s~\cite{slocum200615}. It consists of a $4\times4$ grid containing tiles numbered~$1$ through~$15$ along with one missing tile (see Figure~\ref{fig:15puzzle}). The objective of the puzzle is to arrange the tiles so that they are in ascending order when read from left to right and top to bottom and to end with the blank tile in the lower right. The only moves allowed are those that slide a tile adjacent to the blank space into the blank space. Half of the possible starting positions are solvable~\cite{archer1999modern} and the hardest legal starting positions require eighty moves to complete~\cite{brungger1999parallel}. \begin{figure} \begin{minipage}{0.5\linewidth} \centering\includegraphics[scale=0.25]{15puzzle.pdf} \end{minipage} \begin{minipage}{0.45\linewidth} \mbox{}\\[-\baselineskip] \[\def1.2}\begin{array}{c@{\quad}c@{\quad}c@{\quad}c{1.2}\begin{array}{c@{\quad}c@{\quad}c@{\quad}c} S_{1, 1, 5, 0} & S_{1, 2, 1, 0} & S_{1, 3, 7, 0} & S_{1, 4, 3, 0} \\ S_{2, 1, 9, 0} & S_{2, 2, 2, 0} & S_{2, 3, 11, 0} & S_{2, 4, 4, 0} \\ S_{3, 1, 13, 0} & S_{3, 2, 6, 0} & S_{3, 3, 15, 0} & S_{3, 4, 8, 0} \\ S_{4, 1, 16, 0} & S_{4, 2, 10, 0} & S_{4, 3, 14, 0} & S_{4, 4, 12, 0} \end{array}\] \end{minipage} \caption{On the left is a visual representation of one starting configuration of the 15-puzzle and on the right are the starting constraints (as unit clauses) for this starting configuration in our encoding.} \label{fig:15puzzle} \end{figure} Our encoding of the 15-puzzle is more complicated because unlike the other problems we've considered, a solution to the 15-puzzle is not static. In other words, our encoding must be able to deal with the state of the puzzle changing over time. To do this we use the variables $S_{i,j,n,t}$ to denote that the entry at $(i,j)$ contains tile~$n$ at timestep~$t$. Here $1\leq i,j\leq 4$, $1\leq n\leq 16$ (we let~$16$ denote the blank tile), and $0\leq t\leq 80$ since each instance requires at most~$80$ moves to complete. The board does not permit two tiles to occupy the same location at the same time; these constraints are of the form $S_{i,j,n,t}\mathbin{\Rightarrow}\lnot S_{i,j,m,t}$ for each tile numbers $n\neq m$, valid indices~$i$ and~$j$, and valid timesteps~$t$. Next we need to generate constraints that tell the SAT solver how the state of the board can change from time~$t$ to time $t + 1$. There are two cases to consider, depending on if a square (or an adjacent square) contains the blank tile. The easier case is when a square $(i,j)$ and none of the squares adjacent to that square are blank. In that case, the rules of the puzzle imply that the tile in square $(i,j)$ does not change. We define the function $\doesNotChange(i,j,t)$ to be the constraint that says that the tile in square $(i,j)$ does not change at time~$t$; these constraints are of the form $\bigwedge_{n=1}^{16}(S_{i,j,n,t}\mathbin{\Leftrightarrow} S_{i,j,n,t+1})$. We also use the function $\adj(i,j)$ to denote the squares adjacent to $(i,j)$ and define $\notEqualOrAdjacentToBlank(i,j,t)$ to be $\lnot S_{i,j,16,t}\land\bigwedge_{(k,l)\in\adj(i,j)}\lnot S_{k,l,16,t}$. The static transition constraints are of the form \[ \notEqualOrAdjacentToBlank(i, j, t) \mathbin{\Rightarrow} \doesNotChange(i, j, t) \] for all valid squares $(i, j)$ and timesteps~$t$. The harder transition case is when a square $(i,j)$ contains the blank tile. In this case we need to encode the fact that the blank tile will switch positions with exactly one of the squares adjacent to square $(i,j)$. If the tile on square $(i, j)$ switches positions with the square $(k,l)$ at time~$t$ this can be encoded as the constraint $\bigwedge_{n=1}^{16}(S_{i,j,n,t}\mathbin{\Leftrightarrow} S_{k,l,n,t+1})$. We also need to enforce that all squares adjacent to $(i,j)$ other than $(k,l)$ do not change; these constraints are of the form $\bigwedge_{(x,y)}\doesNotChange(x,y,t)$ where $(x,y)$ is adjacent to $(i,j)$ but not equal to $(k,l)$. Let $\oneTileMoved(i,j,k,l,t)$ denote the conjunction of the above two constraints. Then the slide transition constraints are of the form \[ S_{i,j,16,t} \mathbin{\Rightarrow} \bigvee_{(k,l)\in\adj(i,j)}\oneTileMoved(i,j,k,l,t) \] for all valid squares $(i, j)$ and timesteps~$t$. The constraint $\boardSolved(t)$ that says the board is solved at timestep~$t$ can be encoded as $\bigwedge_{i,j=1}^4 S_{i,j,4i+j-4,t}$. For efficiency reasons we only start looking for solutions with at most 5 moves; if no solution is found then we look for solutions using at most 10 moves and continue in this manner until a solution is found. In other words, we call \texttt{Satisfy} with the given starting constraints, the constraints of the puzzle as described above, and the constraint $\bigvee_{t=m-4}^m\boardSolved(t)$ where~$m$ is initialized to~$5$ and then increased by~$5$ every time no solution is found. This method was applied to the starting configuration from Figure~\ref{fig:15puzzle}. It found that no solutions with at most 5 moves exist in 1.5 seconds, no solutions with at most 10 moves exist in 2.8 seconds, and found a solution with 15 moves in 6.3 seconds. It was also able to solve puzzles requiring up to 40 moves in 20 minutes. While this is not competitive with dedicated solvers for the 15-puzzle, it requires no knowledge beyond the rules of the game and makes an interesting example of how to push SAT solvers to their limits. \section{Conclusion}\label{sec:conclusion} In this paper we've demonstrated how to solve a variety of problems and puzzles using the computer algebra system Maple and its SAT solver MapleSAT~\cite{liang2017empirical}. Maple code for all the examples covered in this paper (including code to read the output of \texttt{Satisfy} and generate the figures included in this paper) are available for download from the Maple Application Center~\cite{brightapps}. The implementations presented in this paper can be considered examples of \emph{declarative programming} where the programmer focuses on describing the problem but not the solution---the computer automatically decides the best way to solve the problem. This is in contrast to \emph{imperative programming} where a programmer needs to describe precisely \emph{how} the computation is to take place. An advantage of declarative programming is that the programmer does not need to worry about specifying a potentially complicated search algorithm. As we saw in the maximum clique problem, sometimes declarative solutions can outperform imperative solutions. However, a disadvantage of declarative programming is that it lacks the kind of detailed control over the method of solution that can be required for optimally efficient solutions. Furthermore, not all problems are naturally expressed in a declarative way. This somewhat unconventional manner of using Maple is not applicable to all problems but we hope the examples in this paper have convinced the reader that SAT solvers are more useful and powerful than they might at first appear. With its extensive logic functionality and convenient method of expressing logical constraints, Maple is an ideal tool for experimenting with SAT solvers and logical programming. \bibliographystyle{splncs04}
{'timestamp': '2019-06-17T02:16:11', 'yymm': '1906', 'arxiv_id': '1906.06251', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06251'}
arxiv
\section*{Introduction} With the development of cellular networks towards 5G and beyond, they are evolving to more complex structures featured by heterogeneity and dense deployment. In these networks, traditional (e.g. non-automated) methods for network deployment, configuration, optimization, and maintenance will be inefficient and will incur huge operational and maintaining expenditures. This has led to the concept of self-organizing network (SON) advocated by the Third Generation Partnership Project (3GPP) and Next Generation Mobile Networks (NGMN) alliance. SON includes three main functions: self-configuration, self-optimization, and self-healing. SON capability will enable more flexible planning and deployment of mobile networks, more efficient optimization and maintenance, less manual intervention, lower capital expenditure (CAPEX) and operational expenditure (OPEX) \cite{b1}. As an important SON functionality, self-healing will automatically detect faults of target networks (e.g. cellular networks) and trigger corresponding actions to fix them. The self-healing functionality mainly includes four phases: fault detection, diagnosis, compensation, and recovery. The goal of fault detection is to find problems such as unacceptable service quality (e.g. due to coverage hole, excessive interference, excessive antenna uptilt or downtilt). Fault diagnosis identifies the root cause based on Key Performance Indicators (KPIs) and alarms. After the faults are identified, recovery actions are launched. To insure quality of service in the process of fault recovery, compensation mechanism is triggered to mitigate degraded network performance in the affected zone through tuning some involved network parameters automatically. In traditional networks, it is common that operators are aware of service failures only after receiving a large number of user complaints. And for failure recovery, the experience of technicians is of paramount importance. In comparison, the objective of self-healing is to perform these tasks automatically in an active manner. Naturally the introduction of intelligence into networks is required, for which machine learning has been recognized as a powerful tool. Specifically, machine learning techniques are able to automatically generate inference and classification models by training collected data, offering accurate results for reliable decision making. And different types of machine learning techniques (e.g. supervised learning, unsupervised learning, and reinforcement leaning) have been leveraged for self-healing. For example, many learning algorithms are devised to detect cell outage and to compensate degraded network performance of problematic cell. And some algorithms can train classifiers for fault diagnosis which can discriminate different faults. However, though machine learning technologies facilitate the development of self-healing methods for cellular networks, several major challenges exist which can impact the performance and practical implementations. In this article, we classify these challenges into the following five categories: \begin{itemize} \item \textbf{Data imbalance:} In cellular networks, due to the occurrence of rare events (e.g. network failure), the collected data sets are usually imbalanced. These imbalanced data can significantly impact the performance of classifiers, which is likely to have a skew towards majority class. However, existing schemes rarely take the issue of data imbalance into account. \item \textbf{Data Insufficiency:} The insufficiency of high quality data can result in severe over fitting of learning models (e.g., classifier). Firstly, the data set obtained from high-fidelity network simulators may not fully represent the measurements in practical cellular networks. While the real data from network operators (e.g. log data) may not be well organized and labeled. And it is difficult to extract effective information and build knowledge from these data. \item \textbf{Cost insensitivity:} Misclassification is unavoidable. However, most existing schemes pursue a low detection error rate, while ignoring the fact that different type of misclassification errors can cause different losses to the operators. In such case, considering accuracy as the only evaluation criterion is defective and cost sensitivity should be considered. \item \textbf{Non-real time response:} Most existing self-healing schemes do not meet the real-time response requirements due to their reactive characteristics. Specifically, they are mainly based on post operations (e.g. diagnosing after malfunctions occur). How to design proactive schemes to reduce the delay and enable real-time response is challenging. \item\textbf{Multi-source data fusion:} Theoretically, data from varying levels such as subscriber level, cell level, and core network level can be jointly exploited for achieving better performance \cite{b2}. However, the multi-source data bring difficulties to model construction. Therefore, how to perform multi-source data fusion for self-healing is a challenging issue. \end{itemize} The main contributions of this article are three folds. Firstly, we discuss the challenges in data-driven machine learning algorithms for self-healing. Secondly, we provide some potential solution directions for addressing these issues. Thirdly, we provide a case study of cost-sensitive fault detection with imbalanced data to illustrate the feasibility and effectiveness of the suggested solutions. \section*{Challenges in Data-Driven Machine Learning} \subsection*{Data Imbalance} Data imbalance often occurs in machine learning and data mining, when at least one class contains more samples comparing to other classes. For convenience, we term the class containing a large number of samples as majority class, and the class including a relatively small number of samples as minority class. The ratio of the number of samples between minority and majority classes is used to measure the degree of data imbalance. In general, in case this ratio is close to 1, the data imbalance can be negligible. Whereas when the ratio is significantly less than 1, the imbalance may hamper the performance of classifiers significantly. In self-healing, fault detection and diagnosis can be considered as typical classification problems. Accordingly, existing machine learning based classification methods can be applied for which measurements data during networking operation period are collected to train corresponding classifiers. Note that a cellular network is functioning well during most of the running time, and service failure or degradation appear with a relative low probability. In this case, the amount of collected normal status data overwhelms that of abnormal data, which then generates imbalanced training data. However, traditional classification algorithms are designed with the premise of balanced data set. When they are applied to fault diagnosis in cellular network which has imbalanced data, the results usually lead to a bias towards majority class, and the classification accuracy for minority class is not satisfying \cite{b3}. Accordingly, data imbalance poses a challenging issue for self-healing which is not considered in most existing work. \subsection*{Data Insufficiency} Currently, the lack of high quality data poses great challenges for the application of machine learning based self-healing mechanisms, which could even hinder the development in this area. Specifically, machine learning algorithms usually require adequate training data to train a stable model. Nevertheless, when the training samples are insufficient, the learners are likely to achieve knowledge from peculiar features rather than common features in data sets, which may result in severe over fitting. Data insufficiency arises mainly due to the following reasons. First, for most researchers in universities and research institutions, acquiring sufficient data from network operators is not an easy task due to privacy and business issues. This can be shown in existing literature in self-healing most of which use data from some high-fidelity network simulators (e.g., NS3, Vienna-LTE, and LTE-Sim). Though these simulators provide good simulation environment, the data collected via simulations cannot fully represent real network scenarios. Also, mobile network measurement data may be collected by means of third-party signal sniffers or some applications in mobile devices, some measurement data (e.g. fault indicating data) are difficult to collect. Second, network operators have huge amount of operation data which are stored in system logs. However, these data may not be well organized and labeled. Accordingly, extracting effective information is difficult. And the data insufficiency also arises due to limited labels. Compared to labeled data, unlabeled data are characterized by large amount. Annotating these unlabeled data usually require experienced engineers and is time/cost consuming and in some cases it may not be always feasible. Therefore, applications of machine learning algorithms for self-healing need to address the challenge of training a model from insufficient real-world data. \subsection*{Cost Insensitivity} In order to evaluate the performance of a machine learning method, metrics such as accuracy, generalization ability, interpretability, time and space complexity, as well as cost-sensitivity need to be taken into account. However, the traditional machine learning methods for self-healing focus primarily on achieving maximized accuracy and ignore the cost involved in the classification process (i.e. assume equal costs for different misclassification errors). However, in real-world scenarios, different misclassification errors often have varying costs. For example, within the process of cell failure diagnosis in self-healing, the cost of mistakenly diagnosing a malfunction to a fault-free case is large than that of identifying a fault-free case to be a case for malfunctioning. Detecting a fault-free case as a malfunction at least can attract the attentions of engineers and makes them take actions to check the failure. However, it means that the network fault is neglected when diagnosing a fault as a normal case mistakenly. Thus, it is unreasonable that different misclassification errors are assigned to equal costs in self-healing. \subsection*{Non-Real-Time Response} Existing self-healing mechanisms cannot meet the real-time response requirements for future mobile networks due to their reactive characteristics. This is due to the fact that they depend on post operations (e.g. detecting and diagnosing after malfunctioning occurs) which can lead to poor service quality for subscribers. For real-time response, the network needs to be fully aware of the changes of context, so that timely response can be taken when network degradation or malfunction occurs. \subsection*{Fusion of Multi-source Data} Currently, for self-healing, cell-level data are frequently utilized for detecting, diagnosing, and recovering from network faults, as well as performing compensation during performance degradation period. Theoretically, data from different levels of sources such as subscriber level, cell level, and core network level can be jointly exploited to achieve better performance \cite{b2}. For example, subscriber-level data (e.g. connection and drop rate, throughput, and delay) are collected from diverse user devices and reflect the communication quality at the user side as well as users' communication behavior/pattern. Operator-level data (e.g. Minimization of Drive Test (MDT) reports, received interference power, and Channel Quality Indicator (CQI)) are collected by the Operation and Maintenance Center (OMC) to monitor the changes of network. However, the data from multiple sources are characterized by different modality and granularity. Also, there could be ambiguity and spuriousness. Accordingly, these multi-sourced data cannot be directly exploited by most existing machine learning algorithms for self-healing. And how to process multi-source data and adjust corresponding algorithms to achieve the potential benefits of data fusion is a challenging issue. \section*{Solution Approaches} In this section, we will present several potential approaches for addressing the above challenges in application of machine learning techniques for self-healing. A concise description of the solutions is given in TABLE I. \subsection*{Data-Imbalance Solutions} We will present the following two types of solution approaches for handling data-imbalance problem: data preprocessing and algorithm modification. \begin{table*}[htbp] \caption{The solutions for different challenges on machine learning in self-healing} \begin{center} \setlength{\tabcolsep}{0.5mm}{ \begin{tabular}{|c|c|c|c|} \hline Challenges & Solutions & Methods & Brief Description \\ \hline \multirow{7}{*}{Data imbalance} & \multirow{4}{*}{Data preprocessing} & Oversampling & Duplicating minority class data\\ \cline{3-4} & & Undersampling & Removing partial majority class data \\ \cline{3-4} & & Oversampling+undersampling & Alleviating the problems caused by using one of them \\ \cline{3-4} & & SMOTE and its variants & Combining resampling and other methods e.g., KNN \\ \cline{2-4} & \multirow{2}{*}{Algorithm modification} & One-class & Estimating a boundary in each class \\ \cline{3-4} & & Hybird strategy & Combining learning algorithms with data preprocessing\\ \cline{3-4}\hline \multirow{6}{*}{Data insufficiency} & \multirow{2}{*}{Data preprocessing} & Oversampling & Duplicating the samples in each class \\ \cline{3-4} & & SMOTE and its variants & Combining resampling and other methods e.g., KNN \\ \cline{2-4} & \multirow{3}{*}{ Using unlabeled data} & Active learning & Selecting useful unlabeled data and annotating them artifically\\ \cline{3-4} & & Unsupervised learning & Dealing with the clustering problems of unlabeled data\\ \cline{3-4} & & Semisupervised learning & Combining labeled and unlabeled data\\ \cline{2-4} & \multirow{1}{*}{Algorithm modification} & Transfer learning& Transferring learning tasks between target and source domains\\ \cline{3-4} \hline \multirow{3}{*}{Cost insensitivity} & {Cost sensitive learning} & Misclassification cost sensitive learning & Setting costs for different classes or samples \\ \cline{2-4} & \makecell[tc]{Introducing new \\ evaluation metrics}& \makecell[tc]{F-measure, G-mean, ROC \\ precision-recall and cost curve} & \makecell[tc]{Combining different components of confusion matrix \\ to estimate system performance comprehensively} \\ \hline {Non-real time response} & Proactive response & Proactive context self-healing & Upgrading existing self-healing from reactive to proactive response \\ \cline{3-4}\hline \multirow{5}{*} {Multi-source data}& \multirow{5}{*}{Data fusion} & \makecell[tc]{Probability based \\ methods} & \makecell[tc]{Obtaining consistent information \\ from random variables, events, or process} \\ \cline{3-4} & & \makecell[tc]{The theory of evidence \\ based methods} & \makecell[tc]{Using symbolic variables and combination rules \\ to infer consistent information from multi-source data}\\ \cline{3-4} & & Artificial intelligence based approaches & Offering a good solution for large-scale complex data\\ \cline{2-4} \hline \end{tabular}} \end{center} \end{table*} \subsubsection{\textbf{Data preprocessing}} It aims to convert imbalanced data to balanced ones through changing the distribution of target data sets before they are fed to the machine learning algorithms. The common preprocessing methods are under-sampling and over-sampling which change the distribution of training samples. Specifically, under-sampling is used to remove several majority class samples randomly and over-sampling is used to duplicate minority class samples, till a balanced data set is produced. However, under-sampling may result in some important information in majority classes to be lost, and over-sampling may result in over-fitting due to the duplicating operations of minority class samples \cite{b3}. One method to mitigate this problem is to combine under-sampling with over-sampling to achieve a trade-off between less information loss in under-sampling and less severe over-fitting in over-sampling. Another option is to enhance the diversity of samples through combining resampling and other techniques such as $K$ Nearest Neighbor (KNN). One common method is synthetic minority over-sampling technique (SMOTE), which produces more samples for minority classes through computing and inserting new instances among randomly selected data and their $K$ nearest neighbors \cite{b3}. \subsubsection{\textbf{Algorithm modification}} The classification problems for imbalanced data set also can be addressed through improving existing machine learning algorithms. Two kinds of solutions may be effective. One is to set reasonable classification boundaries for minority class samples. One-class classifier is a common method for this solution, which estimates a boundary to encompass as sufficient data as possible in each class while minimizing classification errors caused by outliers \cite{b4}. The other is to combine learning algorithms with other technologies such as resampling and cost-sensitive learning. For instance, the combination of traditional classifiers (e.g., Support Vector Machine (SVM), decision tree) and resampling technologies is a good method to improve the classification performance for imbalanced data \cite{b3}. \subsection*{Data-Insufficiency Solutions} These solutions fall into three categories: data preprocessing, algorithm modification, learning with sufficient unlabeled data. \subsubsection{\textbf{Data preprocessing}} The issue of data insufficiency can still be addressed through generating more data artificially. In this context, some methods used to tackle the problems of data imbalance such as random over-sampling, SMOTE and its variants are suitable to cope with the data-insufficiency problem. \subsubsection{\textbf{Algorithm modification}} In the algorithm level, the common solutions are to combine data preprocessing with existing machine learning algorithms. Besides, the concept of {\em transfer learning}, which is based on the idea of acquiring knowledge from one problem/field (source domain) and adopting them to the learning tasks for a new problem/area (target domain), can be a promising solution approach to overcome the problem of data insufficiency \cite{b5}. In self-healing, some learning tasks are similar to the ones in other networks. For example, there could be enough data available from industrial or wireless sensor networks related to the tasks such as error recovery and intrusion detection. These data could be used to train a learning model and transfer it to a machine learning model for self-healing. \subsubsection{\textbf{Learning with sufficient unlabeled data}} When there are limited unlabeled samples and a large number of unlabeled data, the three following solution approaches can be used: active learning, unsupervised and semisupervised learning. Specifically, unsupervised learning deals with the clustering problems of unlabeled data. Semisupervised learning is used to promote the stability of learning models by combining labeled and unlabeled data. Active learning employs learning and selecting engines to find the most useful unlabeled samples, which can be manually annotated to achieve more labeled data \cite{b6}. \subsection*{Solutions to the Cost-Insensitivity Problem} These solutions assign distinct costs to different classes or each sample within the processes of learning and decision making, so that the classifiers pay more attentions to costly classification results. These solutions can be classified into two types: cost-sensitive learning and introducing new evaluation metrics. \subsubsection{\textbf{Cost-sensitive learning}} In general, the classification costs are assigned either for different categories or for each sample, which are known as class-dependent and example-dependent cost, respectively \cite{b7}. The class-dependent cost denotes that different classes have distinct costs while each sample in one class has equal cost, whereas example-dependent cost implies that each sample has a different cost even when these samples belong to the same class. \begin{itemize} \item \textbf{Class-dependent cost:} The methods based on class-dependent costs \cite{b7} allocate different penalties for different classes. These algorithms are mainly classified into two groups. One is to embed this cost into common classifiers like SVM, to achieve more cost-sensitive classifiers. Another is based on Bayesian decision theory to achieve minimum misclassification costs through minimizing conditional risk. \item \textbf{Example-dependent cost:} The approaches based on example-dependent costs aim at changing cost-sensitivity learning tasks into cost-insensitivity ones by two types of methods. One is altering the distribution of original samples based on different weight values. The other is to optimize the weight values of weighted original samples to obtain expected minimum classification costs \cite{b7}. \end{itemize} \subsubsection{\textbf{Introducing new evaluation metrics}} In the presence of data imbalance or cost insensitivity, evaluating an algorithm using accuracy only is not enough. Instead, more effective metrics should be adopted and such measures include F-measure, receiver operating characteristic (ROC) curve, precision-recall curve, and cost curve \cite{b3}. These evaluation criteria use true positive, false positive, true negative and false negative to reflect system performance from different angles. For example,the ROC curves take true and false positive rate into account through placing them in the same coordinate system. \subsection*{Solutions for the non-real-time response} The solution for the non-real-time response problem is to upgrade the existing self-healing approach from the reactive to the proactive one. To this aim, in Fig.~1, we introduce a proactive context-aware self-healing framework. The core idea of this framework is that, the system predicts changes of near-term network performance by using real-time models to capture knowledge from historical and current context information. When possible faults in near-future are predicted, it can trigger self-healing to adjust the current network parameters so that possible loss caused by the faults is minimized. \begin{itemize} \item \textbf{Data collection:} This block is primarily used to gather enough context information, which are classified into three groups: network context, user context, and device context \cite{b8}. \item \textbf{Data preprocessing:} The raw data gathered from different context are not directly used by prediction models since they have several characteristics such as redundancy and different granularity. The goal of this step is to change these imperfect raw data into available ones by using methods such as filtering, ranking and fusion. \item \textbf{Context predictive model:} The main task of this block is to build prediction models (e.g. regression models) with the processed data. \item \textbf{Self-healing:} This block is mainly used to analyze the predicted results from the prediction model and generate corresponding actions for recovery or compensation. \item \textbf{Dynamic response:} This block is used to perform actions for self-healing by generating new parameters to be fed into the network to reconfigure it. \end{itemize} \begin{figure} \includegraphics[width=3 in]{figure1.png} \centering \caption{A proactive context-aware self-healing framework} \end{figure} \subsection*{Solution to the fusion problem for multi-source data} Fusion of multi-source data aims at obtaining unified information by analyzing and reorganizing the data which come from heterogeneous devices and different scenarios. According to \cite{b9}, we classify the solutions for the data fusion problem into three types: probability based methods, the theory of evidence based methods, and artificial intelligence based approaches. Briefly, probabilistic techniques (e.g. Bayesian analysis and Markov Chain) are frequently utilized to discover consistent information from random variables, events or process, which makes them suitable for dealing with uncertain and imprecise multi-source data. The theory of evidence based methods usually use symbolic variables and combination rules to infer consistent information from multi-source uncertain data. Moreover, the artificial intelligence approaches (e.g. machine learning, fuzzy logic, and genetic algorithms) are used for data fusion due to their strong ability on processing large-scale complex data. \section*{Case Study: Cost-Sensitive Fault Detection with Imbalanced Data} We provide a case study on fault detection in order to illustrate the challenges and solutions related to data imbalance and cost-sensitivity issues in machine learning-based solutions for self-healing. We propose a mechanism which enables fault detection through discriminating fault and fault-free measurements jointly considering data imbalance and cost-sensitivity. \subsection*{Classification from Imbalanced Data} To handle the problem of data imbalance in fault detection, re-sampling techniques can be used to preprocess the data. However, as mentioned before, the under-sampling may result in some important information in majority classes to be lost due to its removing operations and the over-sampling may result in over-fitting due to the duplicating operations of minority class samples. SMOTE as an improved scheme can generate new minority class samples by means of neighboring samples. And the neighbor samples are selected by the $K$-nearest neighbor algorithm. Therefore, SMOTE can avoid the over-fitting problem. With this method, a new minority sample could be obtained as follows: for a sample $X$$_i$ in minority class, find the K-nearest neighbors to $X$$_i$, then randomly select a sample $X$$_j$ from above neighbors, calculate their difference $diff=X_i-X_j$, and finally obtain a new sample by $X_n=X_i+rand(0,1)*(X_i-X_j)$. In this experiment, we employ following two methods to demonstrate the necessity to consider data imbalance for machine learning algorithms in self-healing and experimental results are shown in Fig.~3. Also, the whole process of fault detection is shown in Fig.~2. \begin{figure} \includegraphics[width=3 in]{figure2.png} \centering \caption{Fault detection for imbalanced data} \end{figure} \begin{itemize} \item \textbf{Method 1:} We use SVM to classify the imbalanced data set directly. \item \textbf{Method 2:} First, oversampling and SMOTE are used to preprocess the imbalanced data set to convert the imbalanced data to balanced data. Next, SVM is used to classify the balanced data set. \end{itemize} \subsection*{An Example of Cost-Sensitive Learning in Self-healing} We will explain the necessity of considering cost-sensitivity for the existing machine learning algorithms in self-healing and show changes of classification results under different costs. We use $C_{ij}$ ($i,j \in \{ 0,1\}$) as the cost of misclassifying true class $i$ to predicted class $j$, where we preset $C_{00}=C_{11}=0$ and $C_{10}=1$. Class 0 and class 1 represent fault and fault-free classes, respectively. The cost ratio denotes the ratio of $C_{01}$ and $C_{10}$. We have done two tests, which are described as follows. \begin{itemize} \item \textbf{Test 1:} At first, we use SVM to train a model with training set, and utilize cost-sensitive SVM (CS-SVM) \cite{b10} to train different models based on varying cost ratios (i.e. changing $C_{01}$ from 1 to 30). Also, we combine CS-SVM with SMOTE. Next, the test set is utilized to validate the model, and in this process, misclassification costs are calculated through comparing the predicting labels with test set labels. Finally, the total costs along with different cost ratios are achieved and experiment results are shown in Fig.~4. \item \textbf{Test 2:} We compare the classification results of CS-SVM under setting different cost ratios, which are shown in Fig.~5. \end{itemize} \subsection*{Results} We use the simulation scenario proposed in \cite{b11}. We only consider binary classification problem in this article. An imbalanced data set is utilized and there are 117 faults data and 3363 fault-free data in class 0 and 1, respectively. We split the entire data into a training set (including 2783 data) and a testing set (including 696 data), and each data is composed of seven key performance indicators (KPIs): retainability, handover success rate, Reference Signal Received Power (RSRP), Reference Signal Received Quality (RSRQ), Signal-to-Interference-plus-Noise Ratio (SINR), throughput and distance. For performance evaluation, we show the results through ROC curves and use the area under the ROC curve (AUC) to compare different classification algorithms. The larger the AUC is, the better is the classification performance. For the classification based on balanced fault data, the corresponding results are shown in Fig.~3. As can be seen, compared to method 1, method 2 achieves a higher AUC. This demonstrates that, when the data are imbalanced, the performance of traditional classifiers are tempered, and preprocessing imbalanced data via oversampling and SMOTE is an effective method to improve it. In addition, comparing oversampling with SMOTE, the latter works better. This illustrates that SMOTE can improve the performance of random resampling to some extent. \begin{figure} \includegraphics[width=3.2 in]{figure3.png} \centering \caption{Comparison among ROCs for different fault detection methods} \end{figure} With regards to the experiment related to cost-sensitivity, as can be seen from Fig.~4, with cost ratio changing from 1 to 30, the total costs of traditional SVM increase linearly while they do not increase for CS-SVM when the cost ratio is larger than 20. Also, lower total costs can be achieved by adding SMOTE on top of CS-SVM. This illustrates that cost-sensitive algorithms can effectively control misclassification results and a hybrid of SMOTE and cost-sensitive learning can provide better results for the classification of imbalanced data. Also, we can see from Fig.~5 that, when presetting a larger cost ratio for CS-SVM, a higher classification performance is obtained. This indicates that the detection of network faults can be easier when setting larger cost ratio. \begin{figure} \includegraphics[width=3.2 in]{figure4.png} \centering \caption{Comparison among the methods under different cost ratios} \end{figure} \begin{figure} \includegraphics[width=3.2 in]{figure5.png} \centering \caption{Comparison among ROC curves under different cost ratios} \end{figure} \section*{conclusion} Self-healing as a key component in SON will play vital roles in realizing intelligent operation in next generation cellular networks. And it has been well recognized that data-driven machine learning techniques are useful for the development of self-healing mechanism and much research efforts have been put on this topic. However, the application of machine learning techniques in this paradigm faces challenges such as data imbalance and insufficiency, cost-insensitivity, non-real-time response, and the fusion for multi-source data. In this article, we have concisely discussed these challenges and provided potential solutions. Besides, a case study of cost-sensitive fault detection has been presented to illustrate the effectiveness and feasibility of suggested approaches.
{'timestamp': '2019-06-18T02:01:19', 'yymm': '1906', 'arxiv_id': '1906.06357', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06357'}
arxiv
\section{Extract Users' Emotions from Feedback}} \IEEEPARstart{I}{nitially} developed for marketing and political opinion mining, sentiment analysis became popular in many domains including software engineering. Mining emotional sentiment has been used, e.g., to guide developer discussions~\cite{Calefato:2018:SPD:3231288.3231327} or summarize users opinion on app features~\cite{6912257}. Sentiment analysis tools use natural language processing to extract emotions from text messages. Simple lexicon-based approaches match each text token to dictionaries containing negative or positive words. The dictionaries define sentiment scores for specific tokens, such as \textit{``I hate[-4] that u need wifi but overall the app is great[+3]''}. Depending on the tool, the scores are combined, e.g., into a single value reflecting the overall emotion expressed. Table~\ref{tab:sentimenttools} describes state-of-the-art sentiment analysis tools including their approaches, scores, languages supported, technology used, and licenses. For this investigation we selected SentiStrength~\cite{Thelwall:2010:SSD:1890706.1890713}, which is a common baseline for emotion classification used in many studies (e.g., \cite{Calefato:2018:SPD:3231288.3231327}). Its results can be improved with domain-specific lexicons, where specific terms correlate with other emotions than in general as the term `bug' in software engineering. SentiStrengthSE uses a manually adjusted version of the SentiStrength lexicon. Senti4SD is trained on manually labelled questions, answers, and comments from StackOverflow. Hence, the training data includes more software engineering specific terms. Most sentiment analysis tools only support the English language, while apps are offered and allow user to submit feedback in more than 40 languages. To analyze these languages further dictionaries need to be created. \begin{table*}[] \scriptsize \renewcommand{\arraystretch}{1.3} \caption{Overview of Sentiment Analysis Tools} \label{tab:sentimenttools} \centering \begin{tabularx}{\textwidth}{lLLLLL} \toprule \textbf{Tool} & \textbf{Approach} & \textbf{Scores} & \textbf{Languages} & \textbf{Technology} & \textbf{License} \\ \rowcolor{Gray} \midrule SentiStrength & Lexicon-based & Estimates strength of positive and negative sentiment & English (Partly tested: Dutch, Finnish, German, Italian, Russian, Spanish, Turkish) & Command-line (Java) & Commercial, closed source (Free for academic research) \\ SentiStrengthSE & Lexicon-based, ad-hoc heuristics & Estimates strength of positive and negative sentiment & English & Command-line (Java) & \textit{-- inherits from SentiStrength -- } \\ \rowcolor{Gray} Senti4SD & Lexicon-based, keyword-based, semantic features (machine learning, word vectors) & Estimates strength of positive and negative sentiment & English & Command-line (R) & Open source (MIT license) \\ Vader NLTK & Lexicon-based & Estimates strength of positive, neutral, negative, and compound sentiment & English & Python package & Open source (Apache license) \\ \rowcolor{Gray} \makecell[tl]{Google Natural\\ Language API} & Machine-learning (not further specified) & Classifies emotion into positive, neutral, and negative & English, Chinese, French, German, Italian, Japanese, Korean, Portuguese, Spanish & Remote API & Commercial, closed source \\ \makecell[tl]{IBM Watson\\ Tone Analyzer} & Machine-learning (not further specified) & Identifies presence and estimates strength of analytical, anger, confident, fear, and tentative tones & English, French & Remote API & Commercial, closed source \\ \bottomrule \end{tabularx} \end{table*} \section{Emotional Patterns in App Reviews} We applied SentiStrength to 7 million app reviews~\cite{7961885}, corresponding to the 25 top free and paid apps from each of the 23 categories of the US Apple App Store (December 2016). As apps can be listed in several categories, we removed duplicates and only considered apps' main category. In total we analyzed 245 apps. We found that users' sentiments are most negative within app reviews of the categories ``photo \& video'' (mean: 0.4), ``entertainment'' (0.6), and ``sports'' (0.9). In contrast, we observed the most positive average sentiments within the categories ``reference'' (2.7), ``education'' (2.4), and ``health \& fitness'' (2.3). Reviews in app stores include a 1-5 stars rating. We found a moderate correlation between the rating and the sentiment (Pearson correlation coefficient 0.57, Spearman rank correlation 0.56). Compared to star ratings which are often skewed~\cite{6636712}, sentiment scores are more fine grained (e.g., on a range from -5 to +5) and can be calibrated to specific information needs, e.g., by fine-tuning the dictionaries. Further, sentiment scores enable comparisons across different platforms. Particularly, in channels without explicit user ratings, automated sentiment analysis tools can help quickly assessing users' overall opinion, as in social media channels (e.g., Twitter). These channels are increasingly being used by app vendors to gather feedback from users (e.g., @SpotifyCares, see https://twitter.com/spotifycares), due to their popularity and their ability to exchange information in form of screenshots or video recordings. Analyzing the sentiment for different apps over time reveals four recurring emotional patterns~\cite{6912257}, as shown in Figure~\ref{fig:patterns}. Each pattern can be related to specific issues or changes within the apps. For example, new app features might increase the average sentiment. The pattern \textit{consistent emotion} is characterized by a stable negative, neutral, or positive sentiment over time. It can be observed within 15\% of the analyzed apps, such as Spotify or Duolingo. The pattern \textit{inconsistent emotion} is characterized neither by a constant nor by a clear positive or negative trend. This pattern can be observed for 62\% of the analyzed apps, including WhatsApp. The pattern \textit{steady decrease/increase} is characterized by a constant negative or positive sentiment trend. A constant negative trend can be observed within 10\% of the analyzed apps, such as CNN or Microsoft Outlook. A positive trend can only be observed within 3\% of the apps, such as AccuWeather. The pattern \textit{emotion drop/jump} is characterized by a sudden change of the sentiment from negative to positive or vice versa. A change from negative to positive can be observed within 15\% of the analyzed apps. A change from positive to negative can be observed within 9\% of the apps, such as Google Mail or OverDrive. \section{Release Lessons} Regularly watching users' emotions and identifying corresponding patterns is a first step towards understanding an app's health. We additionally present five release lessons that software practitioners can apply to improve users' emotions and prevent general negative feedback which can lead to the fall of apps~\cite{williams2018modeling}. We derived the lessons by looking at the release history, the content of user reviews, official vendor's presentations, and technical blogs of several apps corresponding to each pattern. For each lesson we observed at least two indications (e.g., two example apps). Some of the lessons are also supported by recent studies. However, since our lessons are not the result of an in-depth empirical study, we refrain from claiming any generalizability or completeness of lessons. The lessons with their actionable recommendations should encourage and inspire practitioners consider users emotion together with the release frequency and complexity when fine-tuning their release processes. \subsection{Continuously Analyze User Feedback to Identify and React to Bug Reports and Feature Requests} Software practitioners should analyze user feedback of released app versions and react to frequently mentioned bug reports and feature requests, especially when similar features are already offered by competitors. The majority of apps follow the \textit{inconsistent emotion} pattern. These apps are affected by temporary bugs that are quickly fixed by developers. Figure~\ref{fig:patterns} shows that the sentiment of WhatsApp (similar to Pandora) strongly decreases and then restores for single periods of time. In the third month, relative from the start of our analysis, nearly all users report storage issues, e.g., \textit{``Major Storage Issues''}. With the release of an update that fixes the bug after a week, the issue was reported less often. In month 6, users frequently mention crashes after app start. Although these issues only appear for a short period of time, their impact on the overall sentiment is notable since they affect the majority of users who install the update. Apps that do not react to issues reported by their users are associated with the pattern \textit{steady decrease}. Microsoft Outlook's reviews included diverse emotions until month 6, as shown in Figure~\ref{fig:patterns}. Reviews with positive sentiments such as \textit{``Best email app''} exceeded negative reviews, leading to a stable average sentiment value around 2. The majority of negative reviews is related to issues within the apps, e.g., \textit{``Trash won't empty''} or \textit{``Bug when adding accounts''}. As many competing apps exist, users apparently began to explore alternatives. A user wrote \textit{``In iOS mail, you can copy an attached excel spreadsheets within body of email but outlook doesn't format correctly.''}. Similarly another user reported: \textit{``Although Microsoft has addressed several issue, it's still buggy at times. I just started looking for a replacement app.''}. \vspace{10px} \noindent\fbox{ \parbox{.95\columnwidth}{ \textbf{Recommendation \#1:}\vspace{1mm}\\ Software practitioners should use tools (e.g., https://openreq.eu/) to classify and extract bug reports and feature requests from user feedback. Even when already using automated crash reporting tools, user feedback might include additional non-crashing bugs that cannot be automatically captured. These bugs should be clustered to determine their severity. Bugs that are frequently reported should be quickly fixed by developers before users explore alternative apps. Martin et al.~\cite{7765038} provide a broad overview of the research area app store analysis and existing approaches. } } \begin{figure*}[] \centering \includegraphics[width=\textwidth]{graph-emotionpatterns.png} \caption{Four recurring Emotional Patterns in User Feedback} \label{fig:patterns} \end{figure*} \subsection{Frequently Release Small Changes} If possible, software practitioners should frequently introduce small changes to their apps instead of releasing fundamental changes at once, such as a major redesign of the user interface or the removal of app features. For apps introducing major changes at once we observed \textit{emotion drops}. For Google Mail users provided reviews with positive sentiments until the tenth month of our analysis, such as \textit{``Love it more than iPhone mail''}. With an update that applied Android's material design, that iOS users are unfamiliar with, the sentiment suddenly turns negative. Reviews including negative sentiments were often related to usability issues (e.g., \textit{``New update makes you click on each individual email to delete them.''}) or to features removed (e.g., \textit{``Bring back Mark as Unread.''}). A similar emotion drop can be observed as OverDrive introduced major changes within a single app update. The update included multiple bugs, as several users reported \textit{``Can't download books to device''}, \textit{``Buggy, buggy, annoying''}, or \textit{``App crashes with last update''}. In case of Google Mail, the vendor reacted with weekly updates integrating features requested by users in the reviews succh as \textit{``Select multiple messages [...]''} and \textit{``Mark as read/unread [...]''}. With the release of those updates the sentiment shows a positive trend. For OverDrive, to restore the sentiment most bugs were fixed at once with a single app update after a longer period of time. The frequency of app updates is controversially discussed in the literature. A recent study reports that frequently updated apps receive a significantly lower percentage of negative ratings~\cite{McIlroy2016}. Another study only found a weak correlation, considering negative and positive ratings~\cite{Martin:2016:CIA:2950290.2950320}. However, the study shows that the types of released changes have a varying impact on app ratings. Terms and topics around bug fixes and features occur frequently in the description of impactful releases~\cite{Martin:2016:CIA:2950290.2950320}. We recommend to consider releasing frequent and small updates to avoid surprising users with unexpected (i.e., too many or major) changes~\cite{McIlroy2016, Martin:2016:CIA:2950290.2950320, 7081842}. Further, we consider frequent releases beneficial, since bugs get fixed faster for apps with shorter release cycles~\cite{6224279}. Also, studies show that app releases lead to an increased amount of ratings and reviews~\cite{6636712, Martin:2016:CIA:2950290.2950320, Martens2019}, allowing developers to get more feedback and better understand user needs in highly competitive and dynamic markets~\cite{williams2018modeling}. \vspace{10px} \noindent\fbox{ \parbox{.95\columnwidth}{ \textbf{Recommendation \#2:}\vspace{1mm}\\ High code churn in releases, i.e., the rate at which an app's code evolves, correlates with lower ratings~\cite{7081842} and sentiment scores. Software practitioners should use issue trackers' and version control systems' built-in functionality or external tools to visualize the amount of change introduced (e.g., number of user stories resolved, number of bugs fixed, lines of code implemented). Based on these measures, the severity of changes can be determined to decide whether these should be introduced in separate smaller, more frequent releases. } } \subsection{Pre-Release Changes to Subsets of App Users} Changes should be pre-released to subsets of app users before making these available to everyone. Spotify and Duolingo apply this lesson and are able maintain a consistent positive emotion among their users. For initial tests, software practitioners should provide access to alpha and beta app versions to voluntary users, as Spotify does (https://bit.ly/2T00cj1). The alpha version is updated almost daily and may be affected by stability issues. The beta version is updated one week before official app releases, to discover final issues. Feedback regarding these versions cannot be provided in form of app reviews. Instead, testers email their feedback directly to the development teams as indicated during sign up for the programs. This approach aims to decouple testing (i.e., identifying and reporting bugs) from actually using and assessing the app. Further, software practitioners should select individual users to participate in A/B-tests (e.g. as both Duolingo and Spotify do, see https://bit.ly/2FA7U0o, https://bit.ly/2FHntT3, and https://bit.ly/2VYpf8h). One group of the users temporarily receives access to new or modified app features. Duolingo states: \textit{``Every week, we test at least 10 things on a portion of our users.''} (https://bit.ly/2HiB6KN). Last, whenever possible new features should be gradually rolled out to all users so that app vendors can assess the overall impact on the emotional trend and react to unforeseen issues, e.g., by deactivating the functionality until the next app update. \vspace{10px} \noindent\fbox{ \parbox{.95\columnwidth}{ \textbf{Recommendation \#3:}\vspace{1mm}\\ Software practitioners should explore app stores' functionality to distribute alpha and beta versions. % The Apple App Stores allows to distribute these versions using TestFlight via email invite or public links (https://apple.co/1kxr08D). On Google Play, developers can similarly release their apps using the Play console (https://bit.ly/1gLkkv2). Google Play allows to advertise alpha and beta versions on the official app description page, visible to all users. % After testing, changes should be gradually rolled out to assess their overall impact on users' emotions and to be able to react to unforeseen issues. } } \subsection{Explain Changes to Users} Major changes, such as the increase of the minimum required system version or the removal of app features, should be announced and explained to users. Studies show that users do not pay too much attention to release notes~\cite{McIlroy2016}. Instead, software practitioners should engage in conversations with users~\cite{bailey2019examining} or directly explain the changes within the app itself, e.g., using tutorials and tooltips. We observed that apps that did not follow this lesson were affected by the pattern of \textit{steady decrease}. For example, for the CNN app a user reported: \textit{``What happened to local news. I checked that every day [...] please bring it back''}. For Microsoft Outlook the sentiment decreased significantly when users were affected by incompatibilities with new and old iOS versions, such as \textit{``Update [...] broke the app on iOS 8. Went back to using the stock mail app on my iPhone. Uninstalled it.''}. \vspace{10px} \noindent\fbox{ \parbox{.95\columnwidth}{ \textbf{Recommendation \#4:}\vspace{1mm}\\ App changes should be transparent and understandable to users. Therefore, major changes software practitioners do not want to release in smaller parts should be explained to users, e.g., using app built-in tutorials. Further, users with legacy devices and system versions should be redirected to alternatives (e.g., web version) using announcements before stopping support. } } \subsection{Capture Implicit Feedback to Support Decisions} Software practitioners should capture implicit feedback to empirically determine whether experimental app features should be integrated. At the beginning, the taken measures should reflect a basic overall goal (e.g., maximize the number of tracks listened for music apps, see https://bit.ly/2Mka18R). Then, more complex measures can be developed. For example, Spotify performs A/B-tests even for unfinished features to decide whether these should be further developed. For testing, changes are split into atomic parts. When changing, e.g., the navigation, one test looks into the UI while another test focuses on the content, i.e., order of menu items (https://bit.ly/2Wb0NQw). While implicit measures help software practitioners evaluate and optimize features against comparable criteria, explicit feedback provides additional information why taken measures change \cite{Garcia-Gathright:2018:MME:3240323.3241622}. For explicit feedback where no ratings exist, the sentiment can be calculated to quickly assess users' opinion. Further, it offers a broader understanding of the impact of changes. Users of no longer supported devices are, e.g. able to express their opinion in explicit feedback. \vspace{10px} \noindent\fbox{ \parbox{.95\columnwidth}{ \textbf{Recommendation \#5:}\vspace{1mm}\\ Software practitioners should take further steps towards data-driven requirements engineering~\cite{7325177} by integrating logging frameworks, such as AppSee or Google Analytics, into their apps. Beginning with easy measures that relate to the app's overall goal, software practitioners should develop more complex ones by testing the impact of changes in atomic parts. The implicit measures complement explicit user feedback to support decisions which experimental features to integrate into apps. } } \section*{Acknowledgment} This research was partially supported by the European Union Horizon 2020 project OpenReq under grant agreement no. 732463. \begin{IEEEbiography} [{\includegraphics[width=1in,height=1.25in,clip,keepaspectratio]{authors-danielmartens}}]{Daniel Martens} received the B.Sc. and M.Sc. degree in Computer Science from the University of Hamburg. He is a Ph.D. candidate in the Applied Software Technology group at the University of Hamburg. His research interests include user feedback, data-driven software engineering, context-aware adaptive systems, crowd-sourcing, and mobile computing. Besides his academic career, Daniel Martens also worked as a software engineer where he developed more than 30 top-rated iOS applications. He is a student member of the IEEE, ACM, and German Computer Science Society (GI). The photo of Daniel Martens was taken by UHH/Sukhina. \end{IEEEbiography} \begin{IEEEbiography} [{\includegraphics[width=1in,height=1.25in,clip,keepaspectratio]{authors-walidmaalej}}]{Walid Maalej} is a professor of informatics at the University of Hamburg where he leads the Applied Software Technology group. His research interests include user feedback, data-driven software engineering, context-aware adaptive systems, e-participation and crowd-sourcing, and software engineering’s impact on society. He received his Ph.D. in software engineering from the Technical University of Munich. He is currently a steering committee member of the IEEE Requirements Engineering conference and a Junior Fellow of the German Computer Science Society (GI). The photo of Prof. Walid Maalej was taken by Koepcke-Fotografie. \end{IEEEbiography} \bibliographystyle{IEEEtran}
{'timestamp': '2019-06-18T02:02:44', 'yymm': '1906', 'arxiv_id': '1906.06403', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06403'}
arxiv
\section{Introduction} Storytelling through pictures has been dated back to prehistoric times -- around 30,000 years ago, paintings of herds of animals like bisons, rhinos and gazelles were made in a cave in Southern France. However, these were not merely paintings, they were stories about the heroic adventures of humans. Since then visual storytelling has evolved from paintings to photography to motion pictures to video games. With respect to its timeline, neural generative storytelling has gained traction only recently. Recent research has focused on challenges in generating longer documents \cite{wiseman2017challenges, lau2016empirical} as well as on predicting the next events in the story \cite{martin2018event}. Contemporary research has focused on using deep generative models to capture high-level plots and structures in stories \cite{fan2018hierarchical}. Recent years have also seen some work hinging on the event structures and scripts \cite{mostafazadeh2016caters, rishes2013generating, peng2018towards}. Generating an appropriate ending of a story was also studied by \citet{guan2018story} and \citet{sharma2018tackling}. Research on generating stories from a sequence of images is anew \cite{peng2018towards, lukin2018pipeline, kim2018glac, hsu2018using, gonzalez2018contextualize}. \citet{cavazza2009emotional} have stressed the importance of expressing emotions in the believability of the automated storytelling system. Adapting a personality trait hence becomes crucial to capture and maintain interest of the audience. Associating the narrative to a personality instigates a sense of empathy and relatedness. Although there has been research in generating persona based dialog responses and generating stylistic sentences \cite{shuster2018engaging, fu2018style, prabhumoye2018style, shen2017style}, generating persona based stories with different personality types narrating them has been unexplored. In this paper, we focus on generating a story from a sequence of images as if the agent belongs to a particular personality type. In specific, we choose to perform experimentations on visual story telling \cite{huang2016visual}. This paper introduces a novel approach to generating visual stories in five different personality types. A key challenge to this end is the lack of large scale persona annotated stories. We address this by transferring knowledge from annotated data in dialog domain to the storytelling domain. We base our visual story generator model on \citet{kim2018glac} and propose multiple techniques to induce the personalities in the latent representations of both the encoder and the decoder. The goal of our work is to learn the mapping between the latent representations of the images and the tokens of the story such that we encourage our generative model to generate tokens of a particular personality. We evaluate our generative models using the automatic metric of ROUGE \cite{lin2004rouge} which takes into account the sentence level similarity in structure and thus roughly evaluates the matching of content. We acknowledge that there is a drop in this metric since our model is not trying to optimize generation alone but also adapt personality from a different dataset. We also evaluate the success of generating the story in the target personality type using automatic and qualitative analysis. The automatic metrics comprise of the classification accuracies rooted from the annotated data. We observe that one of the proposed models (LEPC, described in Section \ref{sec:models} performs slightly better at classification accuracies for most of the personas while retaining similar ROUGE scores. The main contribution of this paper is showing simple yet effective approaches to narrative visual stories in different personality types. The paper also displays an effective way of using annotated data in the dialog domain to guide the generative models to a specified target personality. \section{Related Work} \paragraph{Visual Story Telling: } Last decade witnessed enormous interest in research at the intersection of multiple modalities, especially vision and language. Mature efforts in image captioning \cite{hossain2019comprehensive} paved way into more advanced tasks like visual question answering \cite{wu2017visual} and visual dialog \cite{das2017visual} , \cite{mostafazadeh2017image}. As an obvious next step from single shot image captioning lies the task of describing a sequence of images which are related to one another to form a story like narrative. This task was introduced as visual story telling by \citet{huang2016visual}, differentiating descriptions of images in isolation (image captions) and stories in sequences. The baseline model that we are leveraging to generate personality conditioned story generation is based on the model proposed by \citet{kim2018glac} for the visual story telling challenge. Another simple yet effective technique is late fusion model by \citet{smilevski2018stories}. In addition to static images, \citet{gella2018dataset} have also collected a dataset of describing stories from videos uploaded on social media. \citet{chandustoryboarding} recently introduced a dataset for generating textual cooking recipes from a sequence of images and proposed two models to incorporate structure in procedural text generation from images. \paragraph{Style Transfer: } One line of research that is closely related to our task is style transfer in text. Recently generative models have gained popularity in attempting to solve style transfer in text with non-parallel data \cite{hu2017toward, shen2017style, li2018delete}. Some of this work has also focused on transferring author attributes \cite{prabhumoye2018style}, transferring multiple attributes \cite{lample2018multipleattribute, logeswaran2018content} and collecting parallel dataset for formality \cite{rao2018dear}. Although our work can be viewed as another facet of style transfer, we have strong grounding of the stories in the sequence of images. \paragraph{Persona Based Dialog: } Persona based generation of responses has been studied by NLP community in dialog domain. \cite{li2016persona} encoded personas of individuals in contextualized embeddings that capture the background information and style to maintain consistency in the responses given. The embeddings for the speaker information are learnt jointly with the word embeddings. Following this work, \cite{zhou2018emotional} proposed Emotional Chatting Machine that generates responses in an emotional tone in addition to conditioning the content. The key difference between former and latter work is that the latter captures dynamic change in emotion as the conversation proceeds, while the user persona remains the same in the former case. \cite{zhang2018personalizing} release a huge dataset of conversations conditioned on the persona of the two people interacting. This work shows that conditioning on the profile information improves the dialogues which is measured by next utterance prediction. In these works, the gold value of the target response was known. For our work, we do not have gold values of stories in different personas. Hence we leverage annotated data from a different task and transfer that knowledge to steer our generation process. \paragraph{Multimodal domain: } With the interplay between visual and textual modalities, an obvious downstream application for persona based text generation is image captioning. \citet{chandrasekaran2018punny} worked on generating witty captions for images by both retrieving and generating with an encoder-decoder architecture. This work used external resources to gather a list of words that are related to puns from web which the decoder attempts to generate conditioned on phonological similarity. \citet{wang2015can} studied the statistical correlation of words associated with specific memes. These ideas have also recently penetrated into visual dialog setting. \citet{shuster2018engaging} have collected a grounded conversational dataset with 202k dialogs where humans are asked to portray a personality in the collection process. They have also set up various baselines with different techniques to fuse the modalities including multimodal sum combiner and multimodal attention combiner. We use this dataset to learn personas which are adapted to our storytelling model. \section{Models} \label{sec:models} We have a dataset of visual stories $\boldsymbol{S} = \{\boldsymbol{S_1}, \ldots, \boldsymbol{S_n} \}$. Each story $\boldsymbol{S_i}$ is a set of sequence of five images and the corresponding text of the story $\boldsymbol{S_i} = \{(\boldsymbol{I}_i^{(1)}, \boldsymbol{x}_i^{(1)}), \ldots, (\boldsymbol{I}_i^{(5)}, \boldsymbol{x}_i^{(5)})\}$. Our task is to generate the story based on not only the sequence of the images but also closely following the narrative style of a personality type. We have five personality types (described in Section \ref{sec:data}) $\boldsymbol{P} = \{\boldsymbol{p}_1, \ldots, \boldsymbol{p}_5\}$ and each story is assigned one of these five personalities as their target persona. Here, each $\boldsymbol{p}_i$ represents the one-hot encoding of the target personality for story i.e $\boldsymbol{p}_1 = [1, 0, 0, 0, 0]$ and so on till $\boldsymbol{p}_5 = [0, 0, 0, 0, 1]$. Hence, we create a dataset such that for each story, we also have a specified target personality type $\boldsymbol{S}_i = \{(\boldsymbol{I}_i^{(1)}, \boldsymbol{x}_i^{(1)}), \ldots, (\boldsymbol{I}_i^{(5)}, \boldsymbol{x}_i^{(5)}); \boldsymbol{p}_i\}$. The inputs to our models are the sequence of images and the target personality type. We build generative models such that they are able to generate stories in the specified target personality type from the images. In this section, we first briefly describe classifiers that are trained discriminatively to identify each of the personalities and then move on to the story generation models that make use of these classifiers. Here is an overview of the differences in the six models that we describe next. \begin{enumerate} \item The baseline model (Glocal) is a sequence to sequence model with global and local contexts for generating story sentence corresponding to each image. \item The Multitask Personality Prediction (MPP) model is equipped with predicting the personality in addition to generating the sentences of the story. This model also incorporates binary encoding of personality. \item The Latent Encoding of Personality in Context (LEPC) model incorporates an embedding of the personality as opposed to binary encoding. \item The Latent Encoding of Personality in Decoder (LEPD) model augments personality embedding at each step in the decoder, where each step generates a token. \item Stripped Encoding of Personality in Context (SEPC) is similar to LEPC but encodes personality embedding after stripping the mean of the story representation. \item Stripped Encoding of Personality in Decoder (SEPD) is similar to LEPD but encodes personality embedding after stripping the mean of the story representation. This is similar to the intuition behind SEPC. \end{enumerate} \subsection{Classification} \label{sec:classification} We use convolutional neural network (CNN) architecture to train our classifiers. We train five separate binary classifiers for each of the personality types. The classifiers are trained to predict whether a sentence belongs to a particular personality or not. We train the classifiers in a supervised manner. We need labeled data to train each of the classifiers. Each sample of text $\boldsymbol{x}$ in the respective datasets of each of the five personality types has a label in the set $\{0, 1\}$. Let $\boldsymbol{\theta}_{\text{C}}^{\boldsymbol{\boldsymbol{p}_j}}$ denote the parameters of the classifier for personality $\boldsymbol{p}_j$ where $j \in \{1, \ldots, 5\}$. Each classifier is trained with the following objective: \begin{equation} \boldsymbol{\mathcal{{L}}} (\boldsymbol{\theta}_{\text{C}}^{\boldsymbol{p}_j}) = \mathbb{E}_{\boldsymbol{X}} [\log q_{C} (\boldsymbol{p}_j |\boldsymbol{x})] \label{eq:class} \end{equation} We use cross entropy loss to calculate $\boldsymbol{\mathcal{{L}}}_{\text{C}}^{\boldsymbol{\boldsymbol{p}_j}}$ for each of the five classifiers. The classifiers accept continuous representations of tokens as input. \subsection{Story Generation} We present five extensions to incorporate personality based features in the generation of stories. \paragraph{(1) Baseline model (Glocal): } We first describe the baseline model that is used for visual story telling. This is based on the model \cite{kim2018glac} that attained better scores on human evaluation metrics. It follows an encoder-decoder framework translating a sequence of images into a story. From here on, we refer to this model as \textit{glocal} through the rest of the paper owing to the global and local features in the generation of story sequence at each step (described in this section). The image features for each of the steps are extracted with a ResNet-152 \cite{he2016deep} post resizing to 224 X 224. The features are taken from the penultimate layer of this pretrained model and the gradients are not propagated through this layer during optimization. These features are passed through a fully connected layer to obtain the final image features. In order to obtain an overall context of the story, the sequence of the image features are passed through a Bi-LSTM. This represents the global context of the story. For each step in the generation of the story, the local context corresponding to the specificity of that particular image is obtained by augmenting the image features (local context) to the context features from the Bi-LSTM (global context). These \textit{glocal features} are used to decode the story sentence at each step. This concludes the encoder part of the story. The decoder of each step in the story also uses an LSTM which takes the same glocal feature for that particular step at each time step. Hence there are 5 glocal features feeding into each time step in the decoder. For simplicity in understanding, we use the following notations throughout model descriptions to represent mathematical formulation of the generation models. Subscript \textit{k} indicates the \textit{$k^{th}$} step or sentence in a story. Subscript \textit{i} indicates the \textit{$i^{th}$} story example. The story encoder is represented as \textit{Encoder} which comprises of the features extracted from the penultimate layer of ResNet-152 concatenated with the global context features from the Bi-LSTM. The entirety of this representation in encoder and the glocal features obtained is represented using $\boldsymbol{z}_k$ for the \textit{$k_{th}$} step or sentence in the story. \begin{equation} \boldsymbol{z}_k = \textit{Encoder} (\boldsymbol{I}_k) \end{equation} Now, the generation of a sentence in the story is represented as follows: \begin{equation} \boldsymbol{\hat{x}}_k \sim \prod_t Pr(\boldsymbol{\hat{x}}_k^t | \boldsymbol{\hat{x}}_k^{<t}, \boldsymbol{z}_k) \end{equation} The generated sentence $\boldsymbol{\hat{x}}_k$ is obtained from each of the output words $\boldsymbol{\hat{x}}_k^t$ which is generated by conditioning on all of the prior words $\boldsymbol{\hat{x}}_k^{<t}$ and the glocal feature obtained as $\boldsymbol{z}_k$. \paragraph{Personality based Generation: } In the rest of the section, we are going to describe the incremental extensions to the baseline to adapt the model to perform persona based story generation. \paragraph{(2) Multitask Personality Prediction (MPP):} The intuition behind the hypothesis here is to provide the personality information to the model and also enable it to predict the personality along with the generation of the story. The obvious extension to provide personality information is to incorporate the one-hot encoding $\boldsymbol{p}_i \in \boldsymbol{P}$ of the five personas in the context before the decoder. The visual story telling data is split into five predetermined personalities as described in Section \ref{sec:data}. For each story, the corresponding personality is encoded in a one hot representation and is augmented to the glocal context features. These features are then given to the decoder to produce each step in the story. The model is enabled to perform two tasks: the primary task is to generate the story and the secondary task is to predict the personality of the story. The classifiers described in Section \ref{sec:classification} are used to perform personality prediction. Formally, the generation process is represented by: \begin{equation} \boldsymbol{\hat{x}}_k \sim \prod_t Pr(\boldsymbol{\hat{x}}_k^t | \boldsymbol{\hat{x}}_k^{<t}, \boldsymbol{z}_k, \boldsymbol{p}_i) \end{equation} Here, we condition the generation of each word on the glocal context features $\boldsymbol{z}_k$, binary encoding of the personality $\boldsymbol{p}_i$ and the words generated till that point. The cross entropy loss for generation is $\mathbf{\boldsymbol{\mathcal{L}_{g}}}$ and the loss for the prediction of each of the personalities is $\boldsymbol{L}_{\text{C}}^{\boldsymbol{\boldsymbol{p}_j}}$ given by Eq \ref{eq:class}. The overall loss optimized for this model is: \begin{align*} \boldsymbol{\mathcal{L}_{total}} = \alpha \cdot \boldsymbol{\mathcal{L}_{g}} + \frac{(1 - \alpha)}{5} \cdot \sum_{j=1}^{5} \boldsymbol{\mathcal{L}}_{\text{C}}^{\boldsymbol{\boldsymbol{p}_j}} \end{align*} The overall model is optimized on this total loss. We use cross entropy loss for each of the individual losses. We give a higher weight $\alpha$ to the story generation and equally distribute the remaining $(1 - \alpha)$ among each of the 5 personalities. \paragraph{(3) Latent Encoding of Personality in Context (LEPC): } This model is an incremental improvement over MPP model. The key difference is the incorporation of personality as an embedding that captures more centralized traits in the words belonging to that particular personality. For each of the five personality types, we have a latent representation of the personality ($\boldsymbol{\mathcal{P}}$), as opposed to the binary encoding in MPP model. Similar to the earlier setting, this average personality feature vector is concatenated with the glocal context vector The generation step is formally represented as: \begin{equation} \boldsymbol{\hat{x}}_k \sim \prod_t Pr(\boldsymbol{\hat{x}}_k^t | \boldsymbol{\hat{x}}_k^{<t}, [\boldsymbol{z}_k; \boldsymbol{\mathcal{P}}], \boldsymbol{p}_i) \end{equation} This means that $\boldsymbol{z}_k$ is concatenated with $\boldsymbol{\mathcal{P}}$ to give personality informed representation; and the generation of each word is conditioned on these concatenated features $\boldsymbol{z}_k$, binary encoding of the personality $\boldsymbol{p}_i$ and the words generated so far. \paragraph{(4) Latent Encoding of Personality in Decoder (LEPD): } Instead of augmenting the personality traits to the context as done in LEPC model, they could be explicitly used in each step of decoding. The latent representation of the personality ($\boldsymbol{\mathcal{P}}$) is concatenated with the word embedding for each time step in the decoder. \begin{equation} \boldsymbol{\hat{x}}_k \sim \prod_t Pr(\boldsymbol{\hat{x}}_k^t | [\boldsymbol{\hat{x}}_k^{<t}; \boldsymbol{\mathcal{P}}], \boldsymbol{z}_k, \boldsymbol{p}_i) \end{equation} The generation of each of the words is conditioned on the words generated so far that are already concatenated with the average vector for the corresponding personality, and the glocal features along with the binary encoding of the personality. \paragraph{(5) Stripped Encoding of Personality in Context (SEPC): } In order to orient the generation more towards the personality, we need to go beyond simple augmentation of personality. Deriving motivation from neural storytelling\footnote{\url{https://github.com/ryankiros/neural-storyteller}}, we use a similar approach to subtract central characteristics of words in a story and add the characteristics of the personality. Along the same lines of calculating an average representation for each of the personalities, we also obtain an average representation of the story $\boldsymbol{\mathcal{S}}$. This average representation $\boldsymbol{\mathcal{S}}$ intuitively captures the style of the story. Essentially, the story style is being stripped off the context and personality style is incorporated. The modified glocal feature that is given to the decoder is obtained as $\boldsymbol{m} = \boldsymbol{z}_k - \boldsymbol{\mathcal{S}} + \boldsymbol{\mathcal{P}} $. The generation process is now conditioned on $\boldsymbol{m}$ instead of $\boldsymbol{z}_k$. Hence, the generation of each word in decoding is conditioned on the words generated so far ($\boldsymbol{\hat{x}}_k^{<t}$), the binary encoding of the personality ($\boldsymbol{p}_i$) and the modified representation of the context features ($\boldsymbol{m}$). \begin{equation} \boldsymbol{\hat{x}}_k \sim \prod_t Pr(\boldsymbol{\hat{x}}_k^t | \boldsymbol{\hat{x}}_k^{<t}, \boldsymbol{m}, \boldsymbol{p}_i) \end{equation} Here, note that the context features obtained thus far are from the visual data and performing this operation is attempting to associate the visual data with the central textual representations of the personalities and the stories. \paragraph{(6) Stripped Encoding of Personality in Decoder (SEPD): } This model is similar to SEPC with the modification of performing the stripping at each word embedding in the decoder as opposed to the context level stripping. The time steps to strip features is at the sentence level in SEPC and is at word level in SEPD model. The LSTM based decoder decodes one word at a time. At each of these time steps, the word embedding feature $\boldsymbol{\mathcal{E}}$ is modified as $\boldsymbol{e}_k = \boldsymbol{\mathcal{E}} - \boldsymbol{\mathcal{S}} + \boldsymbol{\mathcal{P}} $. This modification is performed in each step of the decoding process. These modified features are used to generate each sentence in the full story. The model is trained to generate a sentence in the story as described below: \begin{equation} \boldsymbol{\hat{x}}_k \sim \prod_t Pr(\boldsymbol{\hat{x}}_k^t | \boldsymbol{e}_k^{<t}, \boldsymbol{z}_k, \boldsymbol{p}_i) \end{equation} The generation of each word is conditioned on the modified word embeddings using the aforementioned transformation ($\boldsymbol{e}_k^{<t}$), the binary encodings of the personalities ($\boldsymbol{p}_i$) and the glocal context features. \section{Datasets} \label{sec:data} Coalescing the segments of personality and sequential generation together, our task is to generate a grounded sequential story from the view of a personality. To bring this to action, we describe the two sources of data we use to generate personality based stories in this section. The first source of data is focussed on generic story generation from a sequence of images and the second source of data includes annotations for personality types for sentences. We tailor a composition of these two sources to obtain a dataset for personality based visual storytelling. Here, we note that the techniques described above can be applied for unimodal story generation as well. \paragraph{Visual Story Telling: } Visual Storytelling is the task of generating stories from a sequence of images. A dataset for this grounded sequential generation problem was collected by \citet{huang2016visual} and an effort for a shared task \footnote{\url{http://visionandlanguage.net/workshop2018/index.html\#challenge}} was led in 2018. The dataset includes 40,155 training sequences of stories. It comprises of a sequence of images, descriptions of images in isolation and stories of images in sequences. We randomly divide the dataset into 5 segments (comprising of 8031 stories each) and each segment is associated with a personality. \paragraph{Personality Dialog: }\citet{shuster2018engaging} have provided a dataset of 401k dialog utterances, each of which belong to one of 215 different personalities. The dataset was collected through image grounded human-human conversations. Humans were asked to play the role of a given personality. This makes this dataset very pertinent for our task as it was collected through engaging image chat between two humans enacting their personalities. For our task, we wanted to choose a set of five distinct personality types. Let the set of utterances that belong to each personality type be $U_p = \{u_p^{1}, \ldots, u_p^{n}\}$ where $p \in \{1, \ldots, 215\}$. We first calculate the pooled BERT representation \cite{devlin2018bert} of each of the utterances. To get the representation of the personality $\boldsymbol{\mathcal{P}}$, we simply average the BERT representations of all the utterances that belong to that personality. The representation of each personality is given by: \begin{equation} \boldsymbol{\mathcal{P}}_p = \frac{\Sigma_{k=1}^{n} BERT(u_{p}^{k})}{n}\\ \label{eq:perona_rep} \end{equation} This representation is calculated only on the train set of \cite{shuster2018engaging}. Since our goal is to pick five most distinct personality types, we have the daunting task of filtering the 215 personality types to 5. To make our task easier we want to group similar personalities together. Hence, we use K-Means Clustering to cluster the representations of the personalities into 40 clusters \footnote{We do not perform exhaustive search on the number of clusters. We tried $k$ values of 5, 20 and 40 and selected 40 as the ideal value based on manual inspection of the clusters.}. We get well formed and meaningful clusters which look like [Impersonal, Aloof (Detached, Distant), Apathetic (Uncaring, Disinterested), Blunt, Cold, Stiff]; [Practical, Rational, Realistic, Businesslike]; [Empathetic, Sympathetic, Emotional]; [Calm, Gentle, Peaceful, Relaxed, Mellow (Soothing, Sweet)] etc. We then build a classifier using the technique described in Section \ref{sec:classification} to classify the utterances to belong to one of the 40 clusters. We pick the top five clusters that give the highest accuracy for the 40-way classification. The five personality clusters selected are: \begin{itemize} \item Cluster 1 \textbf{(C1)}: Arrogant, Conceited, Egocentric, Lazy, Money-minded, Narcissistic, Pompous and Resentful \item Cluster 2 \textbf{(C2)}: Skeptical and Paranoid \item Cluster 3 \textbf{(C3)}: Energetic, Enthusiastic, Exciting, Happy, Vivacious, Excitable \item Cluster 4 \textbf{(C4)}: Bland and Uncreative \item Cluster 5 \textbf{(C5)}: Patriotic \end{itemize} We build five separate classifiers, one for each personality cluster. Note that these clusters are also associated with personalities and hence are later referred as P followed by the cluster id in the following sections. To build the five binary classifiers, we create label balanced datasets for each cluster i.e we randomly select as many negative samples from the remaining 4 clusters as there are positive samples in that cluster. We use the train, dev and test split as is from \cite{shuster2018engaging}. The dataset statistics for each of the five clusters is provided in Table \ref{tab:stat}. \begin{table}[h] \centering \begin{tabular}{l | r | r | r } \hline Cluster Type & Train & Dev & Test \\ \hline Cluster 1 & 26538 & 1132 & 2294 \\ Cluster 2 & 6614 & 266 & 608 \\ Cluster 3 & 19784 & 898 & 1646 \\ Cluster 4 & 6646 & 266 & 576 \\ Cluster 5 & 3262 & 138 & 314 \\ \hline \end{tabular} \caption{Statistics of data belonging to each of the persona clusters} \label{tab:stat} \end{table} Note that all the datasets have a balanced distribution of labels $0$ and $1$. For our experiments it does not matter that distribution of the number of samples is different because we build separate classifiers for each of the cluster and their output is treated as independent from one another. As seen in Table \ref{tab:class_stat}, all the classifiers attain good accuracies and F-scores on the test set. \begin{table}[h] \centering \begin{tabular}{l | r | r | r | r | r } \hline & C1 & C2 & C3 & C4 & C5 \\ \hline Acc. & 79.12 & 81.09 & 83.17 & 77.95 & 84.08 \\ F1 & 0.79 & 0.81 & 0.83 & 0.78 & 0.84 \\ \hline \end{tabular} \caption{Performance of classifiers for each of the persona clusters } \label{tab:class_stat} \end{table} We finally calculate the representation $\boldsymbol{\mathcal{P}}$ for each of the five clusters and the representation $\boldsymbol{\mathcal{S}}$ of stories using equation \ref{eq:perona_rep}. Note that $\boldsymbol{\mathcal{S}}$ is calculated over the visual story tellind dataset. These representations are used by our generative models \textbf{LEPC}, \textbf{LEPD}, \textbf{SEPC}, and \textbf{SEPD}. \begin{figure*}[h!] \centering \includegraphics[width=\linewidth]{analysis.pdf} \caption{ Comparison of generated \textit{stories} from all the described models. } \label{fig:analysis} \end{figure*} \section{Experiments and Results} This section presents the experimental setup for the models described in Section \ref{sec:models}. Each of the models are incremental extensions over the baseline glocal model. The hyperparameters used for this are as follows. \paragraph{Hyperparameters: } The hidden size of the Bi-LSTM encoder of the story to capture context is 1024. The dimensionality of the glocal context vector $\boldsymbol{z}_k$ is 2048. A dropout layer of 50\% is applied post the fully connected layer to obtain the image features and after the global features obtained from Bi-LSTM which is 2 layered. The word embedding dimension used is 256. The learning rate is 1e-3 with a weight decay of 1e-5. Adam optimizer is used with batch normalization and a momentum of 0.01. Weighting the loss functions differently is done to penalize the model more if the decoding is at fault as compared to not predicting the personality of the story. $\alpha$ is set to 0.5 and each of the individual personality losses are weighted by a factor of 0.1. The rest of the 5 models use the same hyperparameter setting with an exception to word embedding dimension. The average personality ($\boldsymbol{\mathcal{P}}$) and the average story ($\boldsymbol{\mathcal{S}}$) representations are obtained from pre-trained BERT model Hence this is a 768 dimensional vector. In order to perform the stripping of the story feature and adding the personality features to the word embeddings in the decoder, the word embedding dimension is matched to 768 in the SEPD model. \begin{table}[h!] \centering \begin{tabular}{l | r | r | r | r | r } \hline Model & C1 & C2 & C3 & C4 & C5 \\ \hline \textbf{Glocal} & 69.90 & 73.29 & 51.55 & 34.91 & 65.86 \\ \textbf{MPP} & 69.35 & 72.44 & 47.54 & 33.83 & 58.49 \\ \textbf{LEPC} & 70.10 & 73.24 & 52.13 & 34.59 & 66.42 \\ \textbf{LEPD} & 76.44 & 79.20 & 33.71 & 34.02 & 67.13 \\ \textbf{SEPC} & 76.76 & 77.00 & 32.84 & 44.53 & 60.08 \\ \textbf{SEPD} & 78.14 & 79.44 & 31.33 & 34.99 & 73.88 \\ \hline \end{tabular} \caption{Performance (in terms of accuracy) of generated stories to capture persona} \label{tab:res} \end{table} \iffalse \begin{table}[h] \centering \begin{tabular}{l | r } \hline Model & METEOR \\ \hline Glocal & 5.5\\ MPP & 4.9\\ LEPC & 5.5\\ LEPD & 4.9\\ SEPC & 4.9\\ SEPD & 5.0\\ \hline \end{tabular} \caption{METEOR scores for the generated stories by each of our models} \label{tab:meteor} \end{table} \fi \begin{table}[h] \centering \begin{tabular}{l | r } \hline Model & ROUGE\_L \\ \hline Glocal & 0.1805\\ MPP & 0.1713\\ LEPC & 0.1814\\ LEPD & 0.1731\\ SEPC & 0.1665\\ SEPD & 0.1689\\ \hline \end{tabular} \caption{ROUGE\_L scores for the generated stories by each of our models} \label{tab:meteor} \end{table} \subsection{Quantitative Results} We perform two sets of experiments: (1) evaluating the performance of the models on capturing the personalities in the story and (2) performance of story generation. The former evaluation is performed using the pre-trained classifiers (\ref{sec:classification}) on the personality dataset. We calculate the classification accuracy of the generated stories of the test set for the desired target personality. However, we need to note that the classification error of the models trained is reflected in this result as well. This evaluation is done at a sentence level i.e accuracy is calculated over each sentence of the story (each sentence of the story has the same target personality as that of the entire story). The performance of the generation is evaluated using the ROUGE score \footnote{We use the implementation from \url{https://github.com/Maluuba/nlg-eval}}. Although this captures the generic aspect of generation, the metric explicitly does not evaluate whether the story is generated on a conditioned personality. In future, we would also like to look at automatic evaluation of the generated stories with respect to incorporation of personalities. Table \ref{tab:res} shows the results of classification accuracy for each of the five personalities. Table \ref{tab:meteor} shows the results of ROUGE\_L evaluation. We acknowledge that there would be a deviation to this automatic score since optimizing the gold standard generation of story from training data is not our end goal. Rather our models make use of two distinct datasets and learn to transfer the traits annotated in personality dialog dataset into the visual story telling dataset. Despite this, we notice that LEPC model gives comparative results to that of the glocal model in terms of story generation. It is noticed that LEPC model also gives slight improvement on the classification accuracies for most of the clusters (each cluster representing a personality). However this is an insufficient result to generalize that incorporating personality at context level performs better than that at the word level since the inverted stance is observed in SEPC and SEPD models. We plan to investigate this further by performing ablations and examine which operation is causing these models to perform weakly. Note that the SEPC model performs the best in incorporating personality in three of the five personality types. But this model takes a hit in the automatic score. This is because our generative models are dealing with competing losses or reconstruction of classification. \subsection{Qualitative Results} We present an example of the story generated by each of the models proposed in Figure \ref{fig:analysis}. This example belongs to persona in cluster \textbf{C3}. The words corresponding to this cluster are highlighted with blue color in the persona conditioned generation of the stories. The main observation is that all of the five sentences in the story contain a word relevant to \textit{happiness} for each of the MPP, LEPC and LEPD models. SEPC and SEPD models capture these happiness features in only two and one sentences respectively. The glocal model does not cater explicitly to the personality while our proposed models attempt to capture the persona tone in generation. This is observed in the fourth generated sentence in the sequence by each of our proposed models. While the glocal model uses the word \textit{`silly'}, our models capture the tone and generate \textit{`excited'} and \textit{`great'}. Similarly for the fifth sentence, MPP, LEPC and LEPD generate \textit{`happy'}, \textit{`surprised'} and \textit{`happy'} respectively. It is observed that in most generated stories, the language model has taken a rough hit in the SEPD model. This is also substantiated in Figure \ref{fig:analysis}. This seems to be due to stripping away the essential word embedding features that contribute to linguistic priors or language model. This could be potentially corrected by retaining the word embedding feature as is and augmenting it with the stripped features. Having presented these results, we notice that there is a significant scope for improving the generation of the story while capturing high level persona traits in generation. \section{Conclusions and Future Work} Automatic storytelling is a creative writing task that has long been the dream of text generation models. The voice conveying this story is the narrative style and this can be attributed to different personalities, moods, situations etc. In the case of persona based visual storytelling, this voice not only is aware of the grounded content to be conveyed in the images, but also has a model to steer the words in the narrative to characterize the persona. A key challenge here is that there is no targeted data for this specific task. Hence we leverage annotations of persona from an external persona based dialog dataset and apply it on the visual storytelling dataset. We address this task of attribution of a personality while generating a grounded story by simple techniques of incorporating persona information in our encoder-decoder architecture. We propose five simple incremental extensions to the baseline model that captures the personality. Quantitatively, our results show that the LEPC model is improving upon the accuracy while at the same time not dropping the automatic scores. We also observe that the persona induced models are generating at least one word per sentence in the story that belong to that particular persona. While automatically evaluating this can be tricky, we adapt a classification based evaluation of whether the generated output belongs to the persona class or not. In the future, we hope to also perform human evaluations for measuring both the target personality type of the generated and story and its coherence. There is yet a lot of scope in incorporating the persona in the word embeddings. This is an ongoing work and we plan on investigating the relatively poor ROUGE performance of the SEPC and SEPD models and rectify them by equipping them with language model information. We also plan to work towards a stable evaluation protocol for this task in the future.
{'timestamp': '2019-06-18T02:02:42', 'yymm': '1906', 'arxiv_id': '1906.06401', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06401'}
arxiv
\section{Introduction}\label{sec:intro} \emph{Order diagrams}, also called \emph{line diagrams} or \emph{Hasse diagrams}, are a great tool for visualizing the underlying structure of ordered sets. In particular they enable the reader to explore and interpret complex information. In such diagrams every element is visualized by a point on the plane. Each edge of the covering relation is visualized as an ascending line connecting its points. These lines are not allowed to touch other points. These strong requirements are often complemented with further soft conditions to improve the readability of diagrams. For example, minimizing the number of crossing lines or the number of different slopes. Another desirable condition is to draw as many chains as possible on straight lines. Lastly, the distance of points to (non-incident) lines should be maximized. Experience shows that in order to obtain (human) readable drawings one has to balance those criteria. Based on this notion, there are algorithms that produce drawings of order diagrams optimizing towards some of the criteria mentioned above. Drawings produced by such algorithms are sufficient to some extent. However, they may not compete with those created manually by an experienced human. However, such an expert is often not available, too expensive, or not efficient enough to create a large number of order diagrams. Hence, finding efficient algorithms that draw diagrams at a suitable quality is still an open task. An exemplary requiring such algorithms is Formal Concept Analysis (FCA) \cite{fca-book}, a theory that can be used to analyze and cluster data through ordering it. In this work we present a novel approach which does not employ the optimization techniques as described above. For this we make use of the structure and its properties that are already encapsulated in the ordered set. We base our idea on the observation that ordered sets of order dimension two can be embedded into the plane in a natural way. Building up on this we show a procedure to embed the ordered sets of order dimension three and above by reducing them to the two-dimensional case. To this end we prove an essential fact about inclusion-maximal bipartite induced subgraphs in this realm. Based on this we link the naturally emerging $\mathcal{NP}$-hard computation problem to a formulation as a SAT problem instance. Our main contribution with respect to this is \Cref{thm:main}. We investigate our theoretical result on different real-world data sets using the just introduced algorithm \texttt{DimDraw}. Furthermore, we note how to incorporate heuristical approaches replacing the SAT solver for faster computations. Finally, we discuss in part surprising observations and formulate open questions. \section{Related Work} \label{sec:relatedwork} Order diagrams can be considered as acyclic (intransitive) digraphs that are drawn upward in the plane, i.e., every arc is a curve monotonically increasing in $y$-direction. A lot of research has been conducted for such upward drawings. A frequently employed algorithm-framework to draw such graphs is known as Sugiyama Framework \cite{Sug81}. This algorithm first divides the set of vertices of a graph into different layers, then embeds each layer on the same $y$-coordinate and minimizes crossings between consecutive layers. Crossing minimization can be a fundamental aesthetic for upward drawings. However the underlying decision problem is known to be $\mathcal{NP}$-hard even for the case of two-layered graphs \cite{eades1986edge}. A heuristic for crossing reduction can be found in~\cite{eades1986median}. The special case for drawing rooted trees can be solved using divide-and-conquer algorithms \cite{journals/tse/ReingoldT81}. Such divide-and-conquer strategies can also be used for non-trees as shown in~\cite{journals/tsmc/MessingerRH91}. Several algorithms were developed to work directly on order diagrams. Relevant for our work is the dominance drawing approach. There, comparable elements of the order relation are placed such that both Cartesian coordinates of one element are greater than the ones of the other \cite{kelly1975planar}. Weak dominance drawings allow a certain number of elements that are placed as if they were comparable \cite{journals/corr/abs-1108-1439} even when they aren't. Our approach is based on this idea. Previous attempts to develop heuristics are described in~\cite{conf/gd/KornaropoulosT12a}. If an ordered set is a lattice there are algorithms that make use of the structure provided by this. The authors in~\cite{stumme95geometrical} make use of geometrical representations for drawings of lattices. In~\cite{freese2004automated} a force directed approach is employed, together with a rank function to guarantee the ``upward property'' is preserved. A focus on additive diagrams is laid out in \cite{ganteradd}. \section{Notations and Definitions} \label{sec:notations} We start by recollecting notations and notions from order theory \cite{trotter1992combinatorics}. In this work we call a pair $(X,R)$ an \emph{ordered set}, if $R\subset X \times X$ is an \emph{order relation} on a set $X$, i.e., $R$ is reflexive, antisymmetric and transitive. In this setting $X$ is called the \emph{ground set} of $(X,R)$. In some cases, we write $(X,{\leq})$ instead of $(X,R)$ throughout this paper. We then use the notations $(a,b)\in {\leq}$, $a \leq b$ and $b \geq a$ interchangeably. We write $a<b$ iff $a \leq b$ and $a \neq b$. Alike, if $b \geq a$ and $b \neq a$, write $b > a$. We say that a pair $(a,b)\in X \times X$ is \emph{comparable}, if $a \leq b$ or $b \leq a$, otherwise it is \emph{incomparable}. An order relation on $X$ is called \emph{linear} (or total) if all elements of $X$ are pairwise comparable. For $(X,{\leq})$ the order relation $L$ on $X$ is called a \emph{linear extension} of $\leq$, iff $L$ is a linear order and ${\leq} \subset L$. If $\mathcal{R}$ is a family of linear extensions of $\leq$ and ${\leq}=\bigcap_{ L \subset \mathcal{R}}L$, we call $\mathcal{R}$ \emph{realizer} of $\leq$. The minimal $d$ such that there is a realizer of cardinality $d$ for $(X,{\leq})$ is called its \emph{order dimension}. We use the denotation of order dimension for ordered sets and order relations interchangeably. For a set $X$ and $\mathcal{C}\subset X \times X$ we denote $\mathcal{C}^{-1}:=\{(a,b) \mid (b,a)\in \mathcal{C}\}$. The \emph{transitive closure} of $R$ is denoted by $R^+$. For our work we consider simple graphs denoted by $(V,E)$, where $E \subset\binom{V}{2}$. For an ordered set $(X,{\leq})$, its \emph{comparability graph} is defined as the graph $(X,E)$, such that $\{a,b\}\in E$, if and only if $a,b\in X$ are comparable. Similary the \emph{cocomparability graph} (sometimes called incomparability graph) is the graph on $X$ where $\{a,b\}$ is an edge if and only if $a,b\in X$ are incomparable. Two order relations on the same ground set are called \emph{conjugate} to each other, if the comparability graph of one is the cocomparability graph of the other. We refrain from a formal definition of a \emph{drawing} of $(X,{\leq})$. However we need to discuss the elements of such drawings used in our work. Each element of the ground set is drawn as a point on the plane. The \emph{cover relation} is defined as ${\cover(X,{\leq})\coloneqq\{(a,b)\in {\leq}\mid \nexists c \in X : a < c < b\}}$. Each element of the cover relation is drawn as a monotonically increasing curve connecting the points. From here on some definitions are less common. For $(X,{\leq})$ we denote the set of incomparable elements by $\inc(X,{\leq})$. Two elements $(a,b),(c,d)\in \inc(X,{\leq})$ are called \emph{incompatible}, if their addition to $\leq$ creates a cycle in the emerging relation, i.e., if there is some sequence of elements $c_1,\ldots ,c_n\in X$, such that each pair ${(c_i,c_{i+1})\in{\leq}\cup(a,b)\cup(c,d)}$ with $i \in\{1,\ldots,n\}$ and $c_{n+1}=c_1$. We call the graph $((\inc(X,{\leq}),E)$ with $\{(a,b),(c,d)\}\in E$, iff $(a,b)$ and $(c,d)$ are incompatible the \emph{transitive incompatibility graph}. Denote this graph by $\tig(X,{\leq})$. We say a pair $(a,b)\in\inc(X,{\leq})$ \emph{enforces} another pair $(c,d)\in\inc(X,{\leq})$, iff $(c,d)\in ({\leq}\cup(a,b))^+$. If and $(a,b)$ enforces $(c,d)$ in $\leq$, we write $(a,b)\rightarrow(c,d)$. \section{Drawing Ordered Sets of Dimension Two} \label{sec:2d} Ordered sets of order dimension 2 have a natural way to be visualized using a realizer by their dominance drawings \cite{kelly1975planar}. Let $(X,{\leq})$ be an ordered set of dimension two. First define the \emph{position} for each $x\in X$ in a linear extension $L$ as the number of vertices that are smaller, i.e., $\pos_{L}(x)\coloneqq\{y\in X\mid y < x\}$. Now let $\mathcal{R}=|\{{\leq_1},{\leq_2}\}|$ be a realizer consisting of two linear extensions of $\leq$. Each element is embedded into a two-dimensional grid at the pair of coordinates $(\pos_{\leq_1}(x),\pos_{\leq_2}(x))$. Embedding this grid into the plane is done using the generating vector $(-1,1)$ for $x_1$ and $(1,1)$ for $x_2$. Each point now divides the plane into four quadrants using the two lines that are parallel to $x_1$ and $x_2$. It holds that $a < b$, if and only if the point $b$ is in the quadrant above the point $a$ by construction. Draw the elements of the cover relation as straight lines. This guarantees that all elements of the cover relation are drawn as monotonically increasing curves. In order to compute such drawings, a preliminary check of the two-dimensionality of the ordered set is required. If so computing a realizer in polynomial time is possible as a result of the following theorem. \begin{theorem}[Dushnik and Miller, 1941 \cite{dushnik1941partially}] \label{thm:dushnikmiller} The dimension of an ordered set $(X,{\leq})$ is at most 2, if and only if there is a conjugate order $\leq_C$ on $X$. A realizer of $P$ is given by $\leq$ given by $\mathcal{R}=\{{\leq}\cup{\leq_C},{\leq}\cup{\geq_C}\}$. \end{theorem} \noindent In 1977, Golumbic gave an algorithm \cite{golumbic1977complexity} to check whether a graph is transitive orientable, i.e., whether there is an order on its vertices, such that the graph is exactly the comparability graph of this order. It computes such an order, if it exists. This algorithm runs in $\mathcal{O}(n^3)$, with $n$ being the number of vertices of the graph. Combining this with \Cref{thm:dushnikmiller} provides an algorithm to compute whether an ordered set is two-dimensional. Furthermore, it also returns a realizer, in the case of two-dimensionality. For the sake of completeness, note that there are faster algorithms (as fast as linear) \cite{Mcconnell97linear-timetransitive}) for computing transitive orientations. However those only work if the graph is actually transitive orientable and return erroneous results otherwise. On a final note, deciding dimension $3$ or larger is known to be $\mathcal{NP}$-complete as shown by Yannakis in 1982 \cite{yannakakis1982complexity}. This is in contrast to the just stated fact about two-dimensional orders. \section{Drawing Ordered Sets of Higher Dimensions} \label{sec:3d} The idea of embedding two-dimensional orders does generalize in a natural way to higher dimensions, i.e., gives us a nice way to embed $n$-dimensional ordered sets into $n$-dimensional space (Euclidean space) by using an $n$-dimensional realizer. However, projecting an ordered set from a higher dimension into the plane turns out to be hard. See, for example, the projections of an ordered set in example \Cref{fig:project}. For this reason our algorithm makes use of a different method to compute drawings of order diagrams for higher dimensions. \begin{figure}[t] \centering \includegraphics[height=10em]{img0}\hfill \includegraphics[height=10em]{img1}\hfill \includegraphics[height=10em]{img2}\hfill \includegraphics[height=10em]{img3}\hfill \includegraphics[height=10em]{img4}\hfill \includegraphics[height=10em]{img5}\hfill \includegraphics[height=10em]{img6}\hfill \includegraphics[height=10em]{img7} \caption{A three-dimensional ordered set embedded -- based on its realizer -- into three dimensional Euclidean space and then projected into the plane using a parallel projection from multiple angles. Even though the structure of the ordered set is recognizable, the drawings are all not satisfactory.} \label{fig:project} \end{figure} In short, the main idea of this section is the following: for a given order relation we want to insert some number of additional pairs in order to make it two-dimensional. This allows the resulting order to be drawn using the algorithm for the two-dimensional case described in the previous section. Afterwards we once again remove all the inserted pairs. By construction, the property that if $a < b$, the point $a$ is inserted below $b$ is still preserved. Such drawings are sometimes called \emph{weak dominance drawings} \cite{journals/corr/abs-1108-1439}. However, for each inserted pair $(a,b)$, we obtain two points in the drawing that are drawn as if $a$ and $b$ were comparable. This poses the question for minimizing the number of inserted pairs. \begin{definition} Let $(X,{\leq})$ be an ordered set. A set $\mathcal{C}\subset \inc(X)$ is called a \emph{two-dimension-extension} of $(X,{\leq})$, iff ${\leq}\cup\mathcal{C}$ is an order on $X$ and the ordered set $(X,{\leq}\cup\mathcal{C})$ is two-dimensional. \end{definition} Such an extension always exists: a linear extension of dimension one always exists. If an order contains exactly one incomparable pair it has dimension two. It is known to be $\mathcal{NP}$-complete to decide whether an ordered set can be altered to be two-dimensional by inserting $k$ pairs \cite{Brightwell_2013}. Hence, we propose an algorithm that tackles the problem for approximating the corresponding optimization problem. The idea of the algorithm is based on the following theorem. \begin{theorem}[Doignon et.al., 1984 \cite{doignon1984realizable}]\label{thm:doignon} The ordered set $(X,{\leq})$ has order-dimension two if and only if $\tig(X,{\leq})$ is bipartite. \end{theorem} \noindent Thus, for $(X,{\leq})$ of dimension greater than two, $\tig(X,{\leq})$ is non-bipartite. We want to find a maximal induced bipartite subgraph of $\tig(X,{\leq})$. \begin{lemma}\label{thm:ring} Let $(X,{\leq})$ be an ordered set and $(a,b),(c,d)\in\inc(X,{\leq})$. Then the following are equivalent: \begin{enumerate}[label=\roman*)] \item $d \leq a$ and $b \leq c$. \item $(a,b)\rightarrow(d,c)$. \item $(c,d)\rightarrow(b,a)$. \item $(a,b)$ and $(c,d)$ are incompatible. \item $(b,a)$ and $(d,c)$ are incompatible. \end{enumerate} \end{lemma} \begin{proof} $(i)\Rightarrow(iv)$. Consider the relation $\prec \coloneqq{\leq} \cup (a,b) \cup (c,d)$. This yields $d \prec a \prec b \prec c \prec d$, i.e, $\prec$ contains a cycle. Analogously $(i) \Rightarrow (v)$.\\% $(iv)\Rightarrow(ii)$. The assumption directly implies that $(d,c) \in ({\leq}\cup(a,b))^+$ due to the cycle generated by $(a,b)$ and $(c,d)$. By the same argument $(v)\Rightarrow (iii)$.\\% $(ii)\Rightarrow(i)$. Assume $d\not \leq a$ or $b \not \leq c$. Since $(d,c)\in({\leq}\cup(a,b))^+$ it follows $(d,c)\in {\leq}$ which contradicts $(c,d)\in \inc(X,\leq)$. Similarly follows $(iii)\Rightarrow (i)$. \null\hfill $\square$ \end{proof} \noindent Recall the definition of $\tig(X,{\leq})$ defined on $\inc(X,{\leq})$ with incompatible pairs being connected. Call a cycle in $\tig(X,{\leq})$ \emph{strict}, iff for each two adjacent pairs $(a,b)$ and $(c,d)$ it holds that $d < a$ and $b < c$. A strict path is defined analogously. \begin{lemma}[Doignon et al., \cite{doignon1984realizable}] \label{thm:strict} Let $(X,{\leq})$ be an ordered set and let the pair $v\in\inc(X,{\leq})$. Then the following statements are equivalent: \begin{enumerate}[label=\roman*)] \item $v$ is in contained in an odd cycle in $\tig(X,{\leq})$. \item $v$ is contained in a strict odd cycle in $\tig(X,{\leq})$. \end{enumerate} \end{lemma} \begin{remark} This is stated implicitly in their proof of Proposition 2, verifying the equality between the two chromatic numbers of a hypergraph corresponding to our cycles and a hypergraph corresponding to our strict cycles. \end{remark} \begin{theorem}\label{thm:main} Let $(X,{\leq})$ an ordered set. Let $\mathcal{C}\subset\inc(X,{\leq})$ be minimal with respect to set inclusion, such that $\tig(X,{\leq})\backslash\mathcal{C}^{-1}$ is bipartite. Then $(X,{\leq}\cup\mathcal{C})$ is an ordered set. \end{theorem} \begin{proof} Refer to the bipartition elements of $\tig(X,{\leq})\backslash\mathcal{C}^{-1}$ with $P_1$ and $P_2$. \begin{claim} The arrow relation is transitive, i.e., if $(a,b)\rightarrow(c,d)$ and $(c,d) \rightarrow (e,f)$ then $(a,b)\rightarrow (e,f)$. If $(a,b)\rightarrow (c,d)$ then $c\leq a$ and $b\leq d$ by definition. Similarly $(c,d)\rightarrow (e,f)$ implies $e \leq c$ and $d \leq f$. By transitivity of $\leq$ this yields that $e\leq a$ and $b \leq f$ which in turn implies that $(a,b)\rightarrow(d,f)$. \end{claim} \begin{claim}[$\star$]Let $(a,b),(c,d)\in\inc(X,{\leq})$ with $(a,b)\not \in \mathcal{C}^{-1}$ and $(a,b)\rightarrow (c,d)$, then $(c,d)\not \in \mathcal{C}^{-1}$. Assume the opposite, i.e., $(c,d) \in \mathcal{C}^{-1}$. Without loss of generality let $(a,b) \in P_1$. As $(c,d) \in \mathcal{C}^{-1}$ there has to be a pair $(e,f)\in P_1$ that is incompatible to $(c,d)$, i.e., $(e,f)\rightarrow (d,c)$, otherwise $(c,d)$ can be added to $P_1$ without destroying the independet set. However $(a,b)\to (c,d)$ is equivalent to $(d,c)\rightarrow (b,a)$ and yields together with the transitivity of the arrow relation $(e,f)\rightarrow (b,a)$. But than $(e,f)$ and $(a,b)$ are incompatible, a contradiction since both are in the independent set $P_1$. \end{claim} \begin{claim}[$\star \star$] If $(x,y)\in \mathcal{C}$, then $(y,x)\not\in\mathcal{C}$. As $(y,x)\in \mathcal{C}^{-1}$, there is a pair $(a,b)$ in $P_1$, such that $(a,b)$ and $(y,x)$ are incompatible, i.e., $(a,b)\rightarrow (x,y)$, otherwise $(y,x)$ can be added to $P_1$. However, since $(a,b)\not \in \mathcal{C}^{-1}$ follows $(x,y)\not \in \mathcal{C}^{-1}$ by Claim ($\star$). \end{claim} \noindent Reflexivity: $\forall x\in X$ we have $(x,x)\in {\leq}\subset {\leq}\cup\mathcal{C}$. \noindent Antisymmetry: assume $(x,y)\in {\leq}\cup\mathcal{C}$ and $(y,x)\in{\leq}\cup\mathcal{C}$. We have to consider three cases. First, $(x,y)\in{\leq}$ and $(y,x)\in{\leq}$. Then $x=y$, as $\leq$ is an order relation. % Secondly, $(x,y)\in{\leq}$ and $(y,x)\in\mathcal{C}$. If $(x,y)\in{\leq}$, then $x$ and $y$ are comparable, i.e., the pair $(y,x)$ can't be in $\inc(P,{\leq})$. Then $(y,x)\not\in\mathcal{C}$, a contradiction. % Thirdly, $(x,y)\in \mathcal{C}$ and $(y,x)\in\mathcal{C}$. This may not occur by Claim~$(\star\star)$. \noindent Transitivity: let $(x,y)\in{\leq}\cup\mathcal{C}$ and $(y,z)\in{\leq}\cup\mathcal{C}$ we show $(y,z)\in{\leq}\cup\mathcal{C}$. We have to consider four cases. First, $(x,y)\in{\leq}$ and $(y,z)\in{\leq}$ implies $(x,z)\in{\leq}$. % Secondly, $(x,y)\in{\leq}$ and $(y,z)\in\mathcal{C}$ and assume that $(x,z)\not\in({\leq}\cup\mathcal{C})$. Then $(z,x)\not \in \mathcal{C}^{-1}$, but $(z,x)\rightarrow (z,y)$, as $(x,y)\in{\leq}$. From Claim $(\star)$ follows that $(z,y)\not\in\mathcal{C}^{-1}$, a contradiction to $(y,z)\in \mathcal{C}$. The case $(x,y)\in \mathcal{C}$ and $(y,z)\in{\leq}$ is treated analogously. % Lastly, $(x,y) \in \mathcal{C}$ and $(y,z) \in \mathcal{C}$ and assume $(x,z)\not \in \mathcal{C}$, i.e., $(z,x)\in \mathcal{C}^{-1}$. There has to be an odd cycle in $P_1\cup P_2$ together with $(y,z)$, otherwise $(y,z)$ can be added to $P_1\cup P_2$ to create a larger biparite graph. By \Cref{thm:strict}, there also hast to be a strict odd cycle. Let the neighbors of $(y,z)$ in $P_1\cup P_2$ be $(a,b)$ and $(c,d)$. Then $a < z$, $c < z$, $y < b$ and $y < d$, and the pairs $(a,b)$ and $(c,d)$ are connected by a strict path on an even number of vertices through the strict odd cycle. By the same argument there are pairs $(e,f)$ and $(g,h)$ with $e < y$, $g < y$, $x < f$ and $x < h$ and $(e,f)$ and $(g,h)$ connected by a strict odd path. We now show, that $(z,x)$ is in an odd cycle with $P_1\cup P_2$ to yield a contradiction. For this consider the following paths $A=(c,f)(z,x)(h,a)$, $B=(d,h)(h,g)$ and $C=(f,e)(e,b)$. Each of those is a path in $\tig(P,{\leq})$ by definition. \begin{claim} Between $(h,a)$ and $(d,h)$ there is a path on an even number of vertices in $P_1\cup P_2$. To show this, let $(a_1,b_1),\ldots ,(a_{2k},b_{2k})$ be the strict path on an even number of vertices connecting $(a,b)$ and $(d,c)$ such that $(a_1,b_1)$ = $(a,b)$ and $(a_{2k},b_{2k})=(d,c)$. This implies $a_{2i+1}< b_{2i+2}$, $a_{2i}< b_{2i+1}$, $b_{2i+1}> a_{2i+2}$ and $a_{2i}> b_{2i+1}$ and for each $i \in \{0,\ldots ,k-1\}$. However, this yields the path $(h,a)=(h,a_1)(b_2,h)(h,a_3)\cdots(b_{2k},h)=(d,h)$ which is even and connecting $(h,a)$ and $(d,h)$ in $P_1\cup P_2$, as required. \end{claim} \noindent Analogously we obtain a path between $(c,f)$ and $(b,f)$ on an even number of vertices. Moreover $(h,g)$ and $(f,e)$ are also connected by a path on an even number of vertices in $P_1\cup P_2$, since $(g,h)$ and $(e,f)$ are connected by an even path. Reversing all pairs of this path yields the required path. Combining the segments $A$, $B$ and $C$ with the paths connecting them yields an odd cycle in $P_1\cup P_2\cup \{(z,x)\}$, a contradiction. \null\hfill $\square$ \end{proof} \subsection{The Importance of Inclusion-Maximality} Consider the standard example $S_3=(X,{\leq})$ where the ground set is defined as $X=\{a_1,a_2,a_3,b_1,b_2,b_3\}$ and $a_i\not\leq a_j$ for $i \neq j$, $b_i \not \leq b_j$ for $i \neq j$ and $a_i\leq a_j$ if and only if $i \neq j$. This example is well known to be a three-dimensional ordered set. However, it becomes two-dimensional by inserting a single pair $(a_i,b_i)$ into the order relation $\leq$ for some index $i\in\{1,2,3\}$, i.e., the transitive incomparability graph becomes bipartite if we remove for example the pair $(b_1,a_1)$. Now assume we do not require to removing a set minimal with respect to set inclusion, take for example both pairs $(a_1,b_1)$ and $(b_1,a_1)$. However the set $(X,{\leq}\cup\{(a_1,b_1),(b_1,a_1)\})$ is not an ordered set, as both pairs $(a_1,b_1)$ and $(b_1,a_1)$ are in ${\leq}\cup\{(a_1,b_1),(b_1,a_1)\}$. This is a conflict with $a_1\neq b_1$, i.e., we do not preserve the order property as the resulting relation is not antisymmetric. \subsection{Bipartite Subgraph is not Sufficient} \label{sec:insuffic} From \Cref{thm:main} one might conjecture that finding an inclusion-minimal bipartite subgraph of $\tig(X,{\leq})$ is sufficient to find a two-dimensional extension of $(X,{\leq})$. However, it may occur that two pairs are not incompatible in $\tig(X,{\leq})$ and are incompatible in $\tig(X,{\leq}\cup\mathcal{C})$ with $\mathcal{C}$ being an inclusion-minimal set such that $\tig(X,{\leq})\backslash\mathcal{C}^{-1}$ is bipartite. This can arise in particular, if the following pattern occurs: the ordered set contains the elements $a,b,c$ and $d$, such that all elements are pairwise incomparable, except $b < d$ and $(c,a)\in \mathcal{C}$ exhibits this observation, see \Cref{fig:counterexample1}. Then $(a,b)$ and $(c,d)$ are not incompatible in $\tig(X,{\leq})$, but they become incompatible with the relation ${\leq}\cup\mathcal{C}$. An example for this is provided by the ordered set in \Cref{fig:counterexample2}. The transitive incomparability graph of this ordered set has 206 vertices. By removing pairs \begin{figure}[t]\centering \begin{minipage}[t]{0.4\textwidth} \centering \includegraphics{counterexample1.pdf} \caption{An example how new incompatibilities can arise. $\leq$ is the continous line, $\mathcal{C}$ is the dashed line. $(a,b)$ and $(c,d)$ are not incompatible in $\leq$ and incompatible in ${\leq} \cup \mathcal{C}$.} \label{fig:counterexample1} \end{minipage} \hfill \begin{minipage}[t]{0.55\textwidth} \centering \includegraphics{counterexample2.pdf} \caption{An example for an ordered set that has a transitive incompatibility graph with an inclusion-minimal bipartite subgraph of the transitive incompatibility graph that does not give rise to a two-dimension extension.} \label{fig:counterexample2} \end{minipage} \end{figure} \noindent \quad \texttt{\small (5,9), (3,13), (6,15), (17,15), (5,15), (5,13), (11,10), (9,6), (5,6), \\\null\quad(4,15), (1,8), (3,15), (11,12), (2,8), (11,7), (0,15), (1,16)}, \noindent the transitive incomparability graph of this ordered set becomes bipartite. However, if we once again compute the transitive incomparability graph of the new ordered set, we see that it is not bipartite, i.e., the new ordered set is once again not two-dimensional. We have to add the additional pair \texttt{(17,8)} to make the graph two-dimensional. It may be remarked at this point that it is in fact possible to make the transitive incomparability graph bipartite by adding only eleven pairs (in contrast to the seventeen added in this particular example), see \Cref{fig:counterexample_alg}. Those pairs give rise to a two-dimension extension. \section{Algorithm} \label{sec:alg} Building up on the ideas and notions from the previous sections we propose the Algorithm \texttt{DimDraw} as depicted in \Cref{alg:dimdraw}. Given an ordered set $(X,{\leq})$, one calls \texttt{Compute\_Coordinates}. Until this procedure identifies a conjugate order using the \texttt{Comupte\_Conjugate\_Order} (and in turn the algorithm of Golumbic \cite{golumbic1977complexity}), it computes bipartite subgraphs of the transitive incompatibility graphs. Furthermore it adds the so-computed pairs to the $\leq$. For finite ground sets the algorithm terminates after finitely many steps. \begin{algorithm}[t] \caption{\texttt{DimDraw}} \label{alg:dimdraw} Execute \texttt{Compute\_Coordinates} on the ordered set that is to be drawn. \hrule \begin{lstlisting}[mathescape=true] Input: Ordered set ($P$,$\leq$) Output: Conjugate order of ($P$,$\leq$) def Compute_Conjugate_Order($P$,$\leq$): $C$ $\coloneqq$ Cocomparability_Graph($P$,$\leq$) if Has_Transitive_Orientation($C$): ($P$,$\leq_C$) $\coloneqq$ Transitive_Orientation($C$) return $\leq_C$ else: return $\perp$ \end{lstlisting} \hrule \begin{lstlisting}[mathescape=true] Input: Ordered set ($P$,$\leq$) Output: Coordinates of the drawing of ($P$,$\leq$) def Compute_Coordinates($P,\leq$): $\leq_C$ $\coloneqq$ Compute_Conjugate_Order($P,\leq)$ $\mathcal{C}$ $\coloneqq$ $\emptyset$ while $\leq_C$ $=$ $\perp$: $I$ $\coloneqq$ Transitive_Incomparability_Graph($P,{\leq}\cup\mathcal{C}$) $B$ $\coloneqq$ Maximum_Bipartite_Subgraph($I$) $\mathcal{C}$ $=$ $\mathcal{C}\cup V(I\backslash B)^{-1}$ $\leq_C$ $\coloneqq$ Compute_Conjugate_Order($P$,${\leq} \cup \mathcal{C}$) $\leq_1$ $\coloneqq$ ${\leq}\cup{\leq_C}$ $\leq_2$ $\coloneqq$ ${\leq}\cup{\geq_C}$ for $x$ in $P$: Coord($x$,1) $\coloneqq$ $|\{k\mid k \leq_1 x\}|-1$ Coord($x$,2) $\coloneqq$ $|\{k\mid k \leq_2 x\}|-1$ return Coord \end{lstlisting} \end{algorithm} \subsection{Postprocessing} The algorithm does not prevent a point from being placed on top of lines connecting two different points. This however is not allowed in order diagrams. Possible strategies to deal with this problem are the following. One strategy is to modify the coordinate system, such that the marks of different integers are not equidistant. Another one is to perturb the points on lines slightly. A third way is to use splines for drawing the line in order to avoid crossing the point. \section{Finding large induced bipartite subgraphs} \label{sec:bip} Our algorithm has to compute an inclusion-minimal set of vertices, such that removing those vertices from the transitive incompatibility graph results in a bipartite graph. Deciding for a graph whether it is possible to make it bipartite by removing a set of cardinality $k$ is known to be $\mathcal{NP}$-complete \cite{LEWIS1980219}. Even approximations are known to be in this complexity class \cite{approx}. Therefore we propose different approaches. \subsection{Exact solution using a reduction to SAT} Even for small example, i.e., orders on less than 30 elements, a naive approach is infeasible. As we will see in \Cref{sec:evaluation} the question for computing $\mathcal{C}$ results in $\binom{182}{5}$ tests for an example on $19$ elements (\cref{fig:fische}) and $\binom{294}{29}$ tests for example (\cref{fig:car}) on 24 elements. Therefore we need a more sophisticated solution for the problem. We reduce the problem for finding biparite subgraphs to a SAT problem and then solve this problem with a SAT-Solver, in our case MiniSat \cite{minisat} in version 2.2. In other words we want to know for some graph $G=(V,E)$ on $n$ vertices and $m$ edges whether by deleting $k$ vertices we can make the graph bipartite. Solving is done by finding a partition of $V$ into the three sets $P_1,P_2,\mathcal{C}^{-1}$, such that $P_1$ and $P_2$ are independent sets and $|\mathcal{C}^{-1}|\leq k$. For this we construct a conjugative normal form as follows: for each vertex $v_i$ we have three variables, call them $V_{i,1},V_{i,2},V_{i,3}$. The first two variables indicate, whether the vertex is placed in $P_1$ or $P_2$, respectively and the third variable indicates, whether the vertex is placed in $\mathcal{C}^{-1}$. For each vertex we have to guarantees, that it is placed in at least one of $P_1$, $P_2$ or $\mathcal{C}^{-1}$, i.e., at least one of $V_{i,1},V_{i,2},V_{i,3}$ is true for each $i$. We achieve this with the clause $V_{i,1} \vee V_{i,2}\vee V_{i,3}$ for all $i \in \{1,\ldots,n\}$. Also we want to guarantee that $P_1$ and $P_2$ are independent sets, i.e., no two vertices in $P_1$ or $P_2$ are connected by an edge. We achive this by adding the two clauses $\neg V_{i,1} \vee \neg V_{j,1}$ and $\neg V_{i,2} \vee \neg V_{j,2}$ for each edge $\{v_i,v_j\}\in E$. This ensures that no two vertices connected by an edge are placed in set $P_1$ or $P_2$. Finally we have to guarantee, that there are at most $k$ vertices in $P_3$, i.e., that at most $k$ of the variables $\{V_{1,3},V_{2,3},\ldots,V_{n,3}\}$ are true. There are multiple ways to achieve this. We employ the method as described in~\cite{conf/cp/Sinz05}. This results in an additional $(n-1)\cdot k$ auxiliary variables and $2nk+n-3k-1$ clauses. Altogether our SAT instance has in total $(n-1)(k+3)+3$ variables and $2m+2nk+2n-3k-1$ clauses. For this CNF the following holds by construction. \begin{theorem} The SAT instance as constructed above is satisfiable if and only if $G$ has an induced bipartite subgraph on $n-k$ vertices. \end{theorem} \noindent Now we build this SAT instance for $k$ increasing from 1 until it is satisfiable. Then the set $\{v_i \mid V_{i,3}=\text{true} \}$ is exactly the subset of vertices we have to remove to make the graph bipartite. Obviously methods like binary search may be applied here. Furthermore, we may also plug heuristic procedures into our algorithm to find an inclusion-minimal set $\mathcal{C}$. We experimented on this with a greedy algorithm, a simulated annealing approach and a genetic algorithm with promising results, especially for the genetic algorithm. However, it is preferred to use the SAT algorithm as long as there is enough computational power and the problem instances are not too large. \section{Experimental evaluation} \label{sec:evaluation} \begin{figure}[t] \null\hfill \includegraphics[height=10em]{fische_hand2}\hfill \includegraphics[height=10em]{fische}\hfill\null \caption{Two drawings of the ``Living Beings and Water'' lattice, by hand (left) and with our algorithm (right).} \label{fig:fische} \end{figure} \begin{figure}[t] \null\hfill \includegraphics[height=10em]{cars_hand2} \hfill \includegraphics[height=10em]{car1} \hfill \includegraphics[height=10em]{car2} \hfill\null \caption{The ``Drive concepts for motorcars'' lattice. Drawn by an expert (left) and two drawings of our algorithm (middle and right).} \label{fig:car} \end{figure} The \texttt{DimDraw} algorithm was originally designed with the idea in mind to draw the order diagram of lattices. Those are employed in a particular in Formal Concept Analysis (FCA), a mathematical theory for analyzing data. Note that any complete lattice can be represented by a concept lattice in FCA. We tested our algorithm on all lattice examples from a standard literature book on FCA \cite{fca-book}. In all those cases the quality of the produced drawings came close to examples hand drawn by experts. For example, consider the lattice that arises from ``Living Beings and Water'' \cite[p.18]{fca-book}. In \Cref{fig:fische} we compare the hand-drawn example (left) to the result drawn by our algorithm (right). For \Cref{fig:car} \cite[p.40]{fca-book} there are two different solutions depicted, both having the minimal number of pairs inserted, note that the algorithm stops after it finds a single solution. Because of the importance of drawings in FCA we tested the algorithm on every lattice with eleven or less vertices. The reader might want to have a look at the document containing all 44994 drawings on 7499 pages \cite{durrschnabel_dominik_2019_3242627}. Concluding the experiments we want to present an example that our algorithm also works on non-lattices. Consider the ordered set from \Cref{fig:counterexample2}. While the hand-drawn version of this order diagram makes use of splines, our algorithm-generated version \Cref{fig:counterexample_alg} uses exclusively straight lines. An interesting observation during the experiments was the following: for all examples of that we are aware, even including those not presented in this work, one pass of the SAT solver was sufficient for reducing the order dimension to two. This is surprising, in particular in light of~\cref{fig:counterexample2} from~\cref{sec:insuffic}. \begin{figure}[t] \centering \includegraphics[height=10em]{counterexample_alg} \caption{A non-lattice example drawing produced by the algorithm. See \Cref{fig:counterexample2} for a hand-drawn version.} \label{fig:counterexample_alg} \end{figure} \section{Conclusion and Outlook} \label{sec:outlook} We presented in this work a novel approach for drawing diagrams of order relations. To this end we employed an idea by Doignon et al.\ relating order dimension and bipartiteness of graphs and proved an extension. Furthermore, we linked the naturally emerging problem to SAT. Finally, we demonstrated various drawings in an experimental evaluation. The drawings produced by the algorithm were, in our opinion, satisfying. We would have liked to compare our algorithm (exact and heuristic type) to the heuristics developed in~\cite{conf/gd/KornaropoulosT12a}. Unfortunately, we were not able to reproduce their results based on the provided description. A notable observation is the fact that in all our experiments the SAT-Solver blend of \texttt{DimDraw} was able to produce a solution in the first pass, i.e., the algorithm found a truly minimal two-dimension extension. This raises the natural question, whether the maximal induced bipartite subgraph approach does always result in a minimal two-dimension extension. Further open questions are concerned with employing heuristics and to improve the postprocessing stage. The SAT-solver version of \texttt{DimDraw} is included in the software conexp-clj\footnote{\url{https://github.com/tomhanika/conexp-clj}}. At a later time we also want to include heuristic versions. \subsection*{Acknowledgement} The authors would like to thank Torsten Ueckerdt for pointing out the research about diametral pairs and Maximilian Stubbemann for helpful discussions. \bibliographystyle{bib/splncs04}
{'timestamp': '2019-06-17T02:14:24', 'yymm': '1906', 'arxiv_id': '1906.06208', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06208'}
arxiv
\section{Introduction} We consider the problem of multi-hop reasoning on natural language data. For instance, consider the statements ``\textit{Socrates was born in Athens}'' and ``\textit{Athens belongs to Greece}'', and the question ``\textit{Where was Socrates born?}''. There are two possible answers following from the given statements, namely ``\textit{Athens}'' and ``\textit{Greece}''. While the answer ``\textit{Athens}'' follows directly from ``\textit{Socrates was born in Athens}'', the answer ``\textit{Greece}'' requires the reader to combine both statements, using the knowledge that \emph{a person born in a city $X$, located in a country $Y$, is also born in $Y$.} This step of combining multiple pieces of information is referred to as \emph{multi-hop reasoning}~\citep{welbl2017constructing}. In the literature, such multi-hop reading comprehension tasks are frequently solved via end-to-end differentiable (deep learning) models~\citep{sukhbaatar2015end, peng2015towards, seo2016query, raison2018weaver, henaff2016tracking, kumar2016ask, graves2016hybrid, dhingra2018neural}. Such models are capable of dealing with the linguistic variability and ambiguity of natural language by learning word and sentence-level representations from data. However, in such models, explaining the reasoning steps leading to an answer and interpreting the model parameters to extrapolate new knowledge is a very challenging task~\citep{46160,DBLP:journals/cacm/Lipton18,DBLP:journals/csur/GuidottiMRTGP19}. Moreover, such models tend to require large amounts of training data to generalise correctly, and incorporating background knowledge is still an open problem~\citep{rocktaschel2015injecting,weissenborn2017dynamic,rocktaschel2017end,evans2017learning}. In contrast, rule-based models are easily interpretable, naturally produce explanations for their decisions, and can generalise from smaller quantities of data. However, these methods are not robust to noise and can hardly be applied to domains where data is ambiguous, such as vision and language~\citep{Moldovan2003-kh,rocktaschel2017end,evans2017learning}. In this paper, we introduce \textsc{NLProlog}, a system combining a symbolic reasoner and a rule-learning method with distributed sentence and entity representations to perform rule-based multi-hop reasoning on natural language input.\footnote{\textsc{NLProlog} and our evaluation code is available at \url{https://github.com/leonweber/nlprolog}.} \textsc{NLProlog} generates partially interpretable and explainable models, and allows for easy incorporation of prior knowledge. It can be applied to natural language without the need of converting it to an intermediate logic form. At the core of \textsc{NLProlog} is a backward-chaining theorem prover, analogous to the backward-chaining algorithm used by Prolog reasoners~\citep{Russell2010-sf}, where comparisons between symbols are replaced by differentiable similarity function between their distributed representations~\cite{sessa2002approximate}. To this end, we use end-to-end differentiable sentence encoders, which are initialized with pretrained sentence embeddings~\citep{pagliardini2017unsupervised} and then fine-tuned on a downstream task. The differentiable fine-tuning objective enables us learning domain-specific logic rules -- such as transitivity of the relation \textit{is in} -- from natural language data. We evaluate our approach on two challenging multi-hop Question Answering data sets, namely \textsc{MedHop} and \textsc{WikiHop}~\citep{welbl2017constructing}. Our main contributions are the following: \begin{inparaenum}[\itshape i)\upshape] \item We show how backward-chaining reasoning can be applied to natural language data by using a combination of pretrained sentence embeddings, a logic prover, and fine-tuning via backpropagation, \item We describe how a Prolog reasoner can be enhanced with a differentiable unification function based on distributed representations (embeddings), \item We evaluate the proposed system on two different Question Answering (QA) datasets, and demonstrate that it achieves competitive results in comparison with strong neural QA models while providing interpretable proofs using learned rules. \end{inparaenum} \section{Related Work} \label{sec:related} Our work touches in general on weak-unification based fuzzy logic~\citep{sessa2002approximate} and focuses on multi-hop reasoning for QA, the combination of logic and distributed representations, and theorem proving for question answering. \paragraph{Multi-hop Reasoning for QA.} One prominent approach for enabling multi-hop reasoning in neural QA models is to iteratively update a query embedding by integrating information from embeddings of context sentences, usually using an attention mechanism and some form of recurrency~\citep{sukhbaatar2015end, peng2015towards,seo2016query,raison2018weaver}. These models have achieved state-of-the-art results in a number of reasoning-focused QA tasks. \citet{henaff2016tracking} employ a differentiable memory structure that is updated each time a new piece of information is processed. The memory slots can be used to track the state of various entities, which can be considered as a form of temporal reasoning. Similarly, the Neural Turing Machine~\citep{graves2016hybrid} and the Dynamic Memory Network~\citep{kumar2016ask}, which are built on differentiable memory structures, have been used to solve synthetic QA problems requiring multi-hop reasoning. \citet{dhingra2018neural} modify an existing neural QA model to additionally incorporate coreference information provided by a coreference resolution model. \citet{de2018question} build a graph connecting entities and apply Graph Convolutional Networks~\citep{kipf2016semi} to perform multi-hop reasoning, which leads to strong results on \textsc{WikiHop}. \citet{zhong2019coarse} propose a new neural QA architecture that combines a combination of coarse-grained and fine-grained reasoning to achieve very strong results on \textsc{WikiHop}. All of the methods above perform reasoning implicitly as a sequence of opaque differentiable operations, making the interpretation of the intermediate reasoning steps very challenging. Furthermore, it is not obvious how to leverage user-defined inference rules during the reasoning procedure. \paragraph{Combining Rule-based and Neural Models.} In Artificial Intelligence literature, integrating symbolic and sub-symbolic representations is a long-standing problem~\citep{besold2017neural}. Our work is very related to the integration of Markov Logic Networks~\citep{DBLP:journals/ml/RichardsonD06} and Probabilistic Soft Logic~\citep{DBLP:journals/jmlr/BachBHG17} with word embeddings, which was applied to Recognizing Textual Entailment (RTE) and Semantic Textual Similarity (STS) tasks~\citep{garrette2011integrating, garrette2014formal, beltagy2013montague, beltagy2014probabilistic}, improving over purely rule-based and neural baselines. An area in which neural multi-hop reasoning models have been investigated is Knowledge Base Completion (KBC)~\citep{das2016chains,cohen2016tensorlog,neelakantan2015compositional,rocktaschel2017end,das2017go,DBLP:journals/jair/EvansG18}. While QA could be in principle modeled as a KBC task, the construction of a Knowledge Base (KB) from text is a brittle and error prone process, due to the inherent ambiguity of natural language. Very related to our approach are Neural Theorem Provers (NTPs)~\citep{rocktaschel2017end}: given a goal, its truth score is computed via a continuous relaxation of the backward-chaining reasoning algorithm, using a differentiable unification operator. Since the number of candidate proofs grows exponentially with the length of proofs, NTPs cannot scale even to moderately sized knowledge bases, and are thus not applicable to natural language problems in its current form. We solve this issue by using an external prover and pretrained sentence representations to efficiently discard all proof trees producing proof scores lower than a given threshold, significantly reducing the number of candidate proofs. \paragraph{Theorem Proving for Question Answering.} Our work is not the first to apply theorem proving to QA problems. \citet{Angeli2016-jw} employ a system based on Natural Logic to search a large KB for a single statement that entails the candidate answer. This is different from our approach, as we aim to learn a set of rules that combine multiple statements to answer a question. Systems like Watson~\citep{Ferrucci2010-ta} and COGEX~\citep{Moldovan2003-kh} utilize an integrated theorem prover, but require a transformation of the natural language sentences to logical atoms. In the case of COGEX, this improves the accuracy of the underlying system by 30\%, and increases its interpretability. While this work is similar in spirit, we greatly simplify the preprocessing step by replacing the transformation of natural language to logic with the simpler approach of transforming text to triples by using co-occurences of named entities. \citet{Fader2014-nq} propose \textsc{OpenQA}, a system that utilizes a mixture of handwritten and automatically obtained operators that are able to parse, paraphrase and rewrite queries, which allows them to perform large-scale QA on KBs that include Open IE triples. While this work shares the same goal -- answering questions using facts represented by natural language triples -- we choose to address the problem of linguistic variability by integrating neural components, and focus on the combination of multiple facts by learning logical rules.% \section{Background} \label{sec:weak_unification} In the following, we briefly introduce the backward chaining algorithm and unification procedure~\citep{russell2016artificial} used by Prolog reasoners, which lies at the core of \textsc{NLProlog}. We consider Prolog programs that consists of a set of rules in the form of Horn clauses: \begin{equation*} \begin{aligned} h(& f^h_1, \ldots, f^h_n)\ \Leftarrow\ \\ & p_1(f^1_{1}, \ldots, f^1_m)\ \wedge\ \ldots\ \wedge\ p_B(f^B_{1}, \ldots, f^B_{l}), \end{aligned} \end{equation*} where $h, p_i$ are predicate symbols, and $f^i_j$ are either function (denoted in lower case) or variable (upper case) symbols. The domain of function symbols is denoted by $\mathcal{F}$, and the domain of predicate symbols by $\mathcal{P}$. $h(f^h_1, \ldots, f^h_n)$ is called the \emph{head} and $p_1(f^1_{1}, \ldots, f^1_m)\ \wedge\ \ldots\ \wedge\ p_B(f^B_{1}, \ldots, f^B_{l})$ the \emph{body} of the rule. We call $B$ the \emph{body size} of the rule and rules with a body size of zero are named \emph{atoms} (short for \emph{atomic formula}). If an atom does not contain any variable symbols it is termed \emph{fact}. For simplicity, we only consider function-free Prolog in our experiments, \textit{i}.\textit{e}.{} Datalog \citep{gallaire1978logic} programs where all function symbols have arity zero and are called \emph{entities} and, similarly to related work~\citep{sessa2002approximate, Julian-Iranzo2009-xa}, we disregard negation and disjunction. However, in principle \textsc{NLProlog} also supports functions with higher arity. A central component in a Prolog reasoner is the \emph{unification} operator: given two atoms, it tries to find variable substitutions that make both atoms syntactically equal. For example, the atoms $\textit{country}(\textit{Greece}, \textit{Socrates})$ and $\textit{country}(\textit{X}, \textit{Y})$ result in the following variable substitutions after unification: $\{X/\textit{Greece}, Y/\textit{Socrates}\}$. Prolog uses \emph{backward chaining} for proving assertions. Given a goal atom $g$, this procedure first checks whether $g$ is explicitly stated in the KB -- in this case, it can be proven. If it is not, the algorithm attempts to prove it by applying suitable rules, thereby generating subgoals that are proved next. To find applicable rules, it attempts to unify $g$ with the heads of all available rules. If this unification succeeds, the resulting variable substitutions are applied to the atoms in the rule body: each of those atoms becomes a subgoal, and each subgoal is recursively proven using the same strategy. For instance, the application of the rule $\textit{country}(X, Y) \Leftarrow \textit{born\_in}(Y, X)$ to the goal $\textit{country}(\textit{Greece}, \textit{Socrates})$ would yield the subgoal $\textit{born\_in}(\textit{Socrates}, \textit{Greece})$. Then the process is repeated for all subgoals until no subgoal is left to be proven. The result of this procedure is a set of rule applications and variable substitutions referred to as \emph{proof}. Note that the number of possible proofs grows exponentially with its depth, as every rule might be used in the proof of each subgoal. Pseudo code for weak unification can be found in Appendix~\ref{app:algorithms} -- we refer the reader to \cite{russell2010artificial} for an in-depth treatment of the unification procedure. \section{NLProlog} \label{sec:nlprolog} Applying a logic reasoner to QA requires transforming the natural language paragraphs to logical representations, which is a brittle and error-prone process. Our aim is reasoning with natural language representations in the form of triples, where entities and relations may appear under different surface forms. For instance, the textual mentions \emph{is located in} and \emph{lies in} express the same concept. We propose replacing the exact matching between symbols in the Prolog unification operator with a \emph{weak unification} operator~\citep{sessa2002approximate}, which allows to unify two different symbols $s_{1}, s_{2}$, by comparing their representations using a differentiable similarity function $s_{1} \sim_\theta s_{2} \in [0,1]$ with parameters $\theta$. With the weak unification operator, the comparison between two logical atoms results in an \emph{unification score} resulting from the aggregation of each similarity score. Inspired by fuzzy logic t-norms~\citep{Gupta:1991:TTN:107687.107690}, aggregation operators are \textit{e}.\textit{g}.{} the minimum or the product of all scores. The result of backward-chaining with weak unification is a set of proofs, each associated with a proof score measuring the truth degree of the goal with respect to a given proof. Similarly to backward chaining, where only successful proofs are considered, in \textsc{NLProlog} the final proof success score is obtained by taking the maximum over the success scores of all found proofs. \textsc{NLProlog} combines inference based on the weak unification operator and distributed representations, to allow reasoning over sub-symbolic representations -- such as embeddings -- obtained from natural language statements. Each natural language statement is first translated into a \emph{triple}, where the first and third element denote the entities involved in the sentence, and the second element denotes the \emph{textual surface pattern} connecting the entities. All elements in each triple -- both the entities and the textual surface pattern -- are then embedded into a vector space. These vector representations are used by the similarity function $\sim_\theta$ for computing similarities between two entities or two textual surface patterns and, in turn, by the backward chaining algorithm with the weak unification operator for deriving a proof score for a given assertion. Note that the resulting proof score is fully end-to-end differentiable with respect to the model parameters $\theta$: we can train \textsc{NLProlog} using gradient-based optimisation by back-propagating the prediction error to $\theta$. \cref{fig:overview} shows an outline of the model, its components and their interactions. \subsection{Triple Extraction} \label{ssec:triple_extraction} To transform the support documents to natural language triples, we first detect entities by performing entity recognition with \textsc{spaCy}~\cite{spacy2}. From these, we generate triples by extracting all entity pairs that co-occur in the same sentence and use the sentence as the predicate blinding the entities. For instance, the sentence ``Socrates was born in Athens and his father was Sophronicus'' is converted in the following triples: \begin{inparaenum}[\itshape i)\upshape] \item (\emph{Socrates}, \emph{ENT1 was born in ENT2 and his father was Sophronicus}, \emph{Athens}), \item (\textit{Socrates}, \textit{ENT1 was born in Athens and his father was ENT2}, \textit{Sophronicus}), and \item (\textit{Athens}, \textit{Socrates was born in ENT1 and his father was ENT2}, \textit{Sophronicus}). \end{inparaenum} We also experimented with various Open Information Extraction frameworks~\citep{DBLP:conf/coling/NiklausCFH18}: in our experiments, such methods had very low recall, which led to significantly lower accuracy values. \subsection{Similarity Computation} Embedding representations of the symbols in a triple are computed using an encoder $\ensuremath{\mathbf{e}}_\theta : \mathcal{F} \cup \mathcal{P} \mapsto \mathbb{R}^{d}$ parameterized by $\theta$ -- where $\mathcal{F}, \mathcal{P}$ denote the sets of entity and predicate symbols, and $d$ denotes the embedding size. The resulting embeddings are used to induce the similarity function $\sim_{\theta} : (\mathcal{F} \cup \mathcal{P})^2 \mapsto [0, 1]$, given by their cosine similarity scaled to $\left[ 0, 1\right]$: \begin{equation} \label{eq:sim} s_1 \sim_{\theta{}} s_2 = \frac{1}{2} \left( 1 + \frac{\ensuremath{\mathbf{e}}_{\theta}(s_1)^\top \ensuremath{\mathbf{e}}_{\theta}(s_2)}{||\ensuremath{\mathbf{e}}_{\theta}(s_1)|| \cdot ||\ensuremath{\mathbf{e}}_{\theta}(s_2)||} \right) \end{equation} In our experiments, for using textual surface patterns, we use a sentence encoder composed of a static pre-trained component -- namely, \textsc{Sent2vec}~\citep{pagliardini2017unsupervised} -- and a Multi-Layer Perceptron (MLP) with one hidden layer and Rectified Linear Unit (ReLU) activations~\citep{DBLP:conf/iccv/JarrettKRL09}. For encoding predicate symbols and entities, we use a randomly initialised embedding matrix. During training, both the MLP and the embedding matrix are learned via backpropagation, while the sentence encoder is kept fixed. Additionally, we introduce a third lookup table and MLP for the predicate symbols of rules and goals. The main reason of this choice is that semantics of goal and rule predicates may differ from the semantics of fact predicates, even if they share the same surface form. For instance, the query \triple{X}{parent}{Y} can be interpreted either as \triple{X}{is the parent of}{Y} or as \triple{X}{has parent}{Y}, which are semantically dissimilar. \begin{figure*}[t] \centering \includegraphics[width=0.6\linewidth]{overview-crop} \caption{Overview of \textsc{NLProlog} -- all components are depicted as ellipses, while inputs and outputs are drawn as squares. Phrases with red background are entities and blue ones are predicates.} \label{fig:overview} \end{figure*} \subsection{Training the Encoders} \label{ssec:training} We train the encoder parameters $\theta$ on a downstream task via gradient-based optimization. Specifically, we train \textsc{NLProlog} with backpropagation using a learning from entailment setting~\citep{muggleton1994inductive}, in which the model is trained to decide whether a Prolog program $\mathcal{R}$ entails the truth of a candidate triple $c \in C$, where $C$ is the set of candidate triples. The objective is a model that assigns high probabilities $p(c|\mathcal{R};\theta)$ to true candidate triples, and low probabilities to false triples. During training, we minimize the following loss: \begin{equation} \label{eq:loss} \begin{aligned} L(\theta) = & - \log p(a|\mathcal{R};\theta) \\ & - \log\left( 1 - \max_{c \in C \setminus \{a\}} p(c|\mathcal{R};\theta) \right), \end{aligned} \end{equation} where $a \in C$ is the correct answer. For simplicity, we assume that there is only one correct answer per example, but an adaptation to multiple correct answers would be straight-forward, \textit{e}.\textit{g}.{} by taking the minimum of all answer scores. To estimate $p(c|\mathcal{R};\theta)$, we enumerate all proofs for the triple $c$ up to a given depth $D$, where $D$ is a user-defined hyperparameter. This search yields a number of proofs, each with a success score $S_i$. We set $p(c|\mathcal{R};\theta)$ to be the maximum of such proof scores: \begin{equation*} p(c|\mathcal{R};\theta) = S_{\max} = \max_{i} S_{i} \in [0, 1]. \end{equation*} Note that the final proof score $p(c|\mathcal{R};\theta)$ only depends on the proof with maximum success score $S_{\max}$. Thus, we propose to first conduct the proof search by using a prover utilizing the similarity function induced by the current parameters $\sim_{\theta_t}$, which allows us to compute the maximum proof score $S_{\max}$. The score for each proof is given by the aggregation -- either using the \emph{minimum} or the \emph{product} functions -- of the weak unification scores, which in turn are computed via the differentiable similarity function $\sim_{\theta}$. It follows that $p(c|\mathcal{R};\theta)$ is end-to-end differentiable, and can be used for updating the model parameters $\theta$ via Stochastic Gradient Descent. \subsection{Runtime Complexity of Proof Search}\label{ssec:runtime} The worst case complexity vanilla logic programming is exponential in the depth of the proof~\citep{russell2010artificial}. However, in our case, this is a particular problem because weak unification requires the prover to attempt unification between all entity and predicate symbols. To keep things tractable, \textsc{NLProlog} only attempts to unify symbols with a similarity greater than some user-defined threshold $\lambda$. Furthermore, in the search step for one statement $q$, for the rest of the search, $\lambda$ is set to $\max(\lambda, S)$ whenever a proof for $q$ with success score $S$ is found. Due to the monotonicity of the employed aggregation functions, this allows to prune the search tree without losing the guarantee to find the proof yielding the maximum success score $S_{\max}$, provided that $S_{\max} \geq \lambda$. We found this optimization to be crucial to make the proof search scale on the considered data sets. \subsection{Rule Learning} In \textsc{NLProlog}, the reasoning process depends on rules that describe the relations between predicates. While it is possible to write down rules involving natural language patterns, this approach does not scale. Thus, we follow \citet{rocktaschel2017end} and use rule templates to perform Inductive Logic Programming (ILP)~\citep{muggleton1991inductive}, which allows \textsc{NLProlog} to learn rules from training data. In this setting, a user has to define a set of rules with a given structure as input. Then, \textsc{NLProlog} can learn the rule predicate embeddings from data by minimizing the loss function in \cref{eq:loss} using gradient-based optimization methods. For instance, to induce a rule that can model transitivity, we can use a rule template of the form $p_1(X, Z) \Leftarrow p_2(X, Y) \wedge p_3(Y, Z)$, and \textsc{NLProlog} will instantiate multiple rules with randomly initialized embeddings for $p_1$, $p_2$, and $p_3$, and fine-tune them on a downstream task. The exact number and structure of the rule templates is treated as a hyperparameter. Unless explicitly stated otherwise, all experiments were performed with the same set of rule templates containing two rules for each of the forms $q(X, Y) \Leftarrow p_{2}(X, Y)$, $p_{1}(X, Y) \Leftarrow p_{2}(Y, X)$ and $p_{1}(X, Z) \Leftarrow p_{2}(X, Y) \wedge p_{3}(Y, Z)$, where $q$ is the query predicate. The number and structure of these rule templates can be easily modified, allowing the user to incorporate additional domain-specific background knowledge, such as $\textit{born\_in}(X, Z) \Leftarrow \textit{born\_in}(X, Y) \wedge \textit{located\_in}(Y, Z)$ \section{Evaluation} We evaluate our method on two QA datasets, namely \textsc{MedHop}, and several subsets of \textsc{WikiHop}~\citep{welbl2017constructing}. These data sets are constructed in such a way that it is often necessary to combine information from multiple documents to derive the correct answer. In both data sets, each data point consists of a query $p(e, X)$, where $e$ is an entity, $X$ is a variable -- representing the entity that needs to be predicted, $C$ is a list of candidates entities, $a \in C$ is an answer entity and $p$ is the query predicate. Furthermore, every query is accompanied by a set of support documents which can be used to decide which of the candidate entities is the correct answer. \subsection{MedHop} \label{ssec:MedHop} \textsc{MedHop} is a challenging multi-hop QA data set, and contains only a single query predicate. The goal in \textsc{MedHop} is to predict whether two drugs interact with each other, by considering the interactions between proteins that are mentioned in the support documents. Entities in the support documents are mapped to data base identifiers. To compute better entity representations, we reverse this mapping and replace all mentions with the drug and proteins names gathered from \textsc{DrugBank}~\citep{wishart2006drugbank} and \textsc{UniProt}~\citep{apweiler2004uniprot}. \subsection{Subsets of WikiHop} \label{ssec:WikiHop} To further validate the effectiveness of our method, we evaluate on different subsets of \textsc{WikiHop}~\citep{welbl2017constructing}, each containing a single query predicate. We consider the predicates \textit{publisher}, \textit{developer}, \textit{country}, and \textit{record\_label}, because their semantics ensure that the annotated answer is unique and they contain a relatively large amount of questions that are annotated as requiring multi-hop reasoning. For the predicate \textit{publisher}, this yields 509 training and 54 validation questions, for \textit{developer} 267 and 29, for \textit{country} 742 and 194, and for \textit{record\_label} 2305 and 283. As the test set of \textsc{WikiHop} is not publicly available, we report scores for the validation set. \subsection{Baselines} \label{ssec:baselines} Following \citet{welbl2017constructing}, we use two neural QA models, namely \textsc{BiDAF}~\citep{seo2016bidirectional} and \textsc{FastQA}~\citep{weissenborn2017fastqa}, as baselines for the considered \textsc{WikiHop} predicates. We use the implementation provided by the \textsc{Jack}~\footnote{\url{https://github.com/uclmr/jack}} QA framework~\citep{weissenborn2018jack} with the same hyperparameters as used by \citet{welbl2017constructing}, and train a separate model for each predicate.\footnote{We also experimented with the AllenNLP implementation of \textsc{BiDAF}, available at \url{https://github.com/allenai/allennlp/blob/master/allennlp/models/reading_comprehension/bidaf.py}, obtaining comparable results.} To ensure that the performance of the baseline is not adversely affected by the relatively small number of training examples, we also evaluate the \textsc{BiDAF} model trained on the whole \textsc{WikiHop} corpus. In order to compensate for the fact that both models are extractive QA models which cannot make use of the candidate entities, we additionally evaluate modified versions which transform both the predicted answer and all candidates to vectors using the \textit{wiki-unigrams} model of \textsc{Sent2vec}~\citep{pagliardini2017unsupervised}. Consequently, we return the candidate entity which has the highest cosine similarity to the predicted entity. We use the normalized version of \textsc{MedHop} for training and evaluating the baselines, since we observed that denormalizing it (as for \textsc{NLProlog}) severely harmed performance. Furthermore on \textsc{MedHop}, we equip the models with word embeddings that were pretrained on a large biomedical corpus~\citep{Pyysalo2013DistributionalSR}. \subsection{Hyperparameter Configuration} \label{ssec:hyperparams} On \textsc{MedHop} we optimize the embeddings of predicate symbols of rules and query triples, as well as of entities. \textsc{WikiHop} has a large number of unique entity symbols and thus, learning their embeddings is prohibitive. Thus, we only train the predicate symbols of rules and query triples on this data set. For \textsc{MedHop} we use bigram \textsc{Sent2vec} embeddings trained on a large biomedical corpus~\footnote{\url{https://github.com/ncbi-nlp/BioSentVec}}, and for \textsc{WikiHop} the \textit{wiki-unigrams} model\footnote{\url{https://drive.google.com/open?id=0B6VhzidiLvjSa19uYWlLUEkzX3c}} of \textsc{Sent2vec}. All experiments were performed with the same set of rule templates containing two rules for each of the forms $p(X, Y) \Leftarrow q(X, Y)$, $p(X, Y) \Leftarrow q(Y, X)$ and $p(X, Z) \Leftarrow q(X, Y) \wedge r(Y, Z)$ and set the similarity threshold $\lambda$ to $0.5$ and maximum proof depth to $3$. We use Adam~\citep{kingma2014adam} with default parameters. \subsection{Results} The results for the development portions of \textsc{WikiHop} and \textsc{MedHop} are shown in Table~\ref{tab:results_countryhop}. For all predicates but \textit{developer}, \textsc{NLProlog} strongly outperforms all tested neural QA models, while achieving the same accuracy as the best performing QA model on \textit{developer}. We evaluated \textsc{NLProlog} on the hidden test set of MedHop and obtained an accuracy of 29.3\%, which is 6.1 pp better than FastQA and 18.5 pp worse than BiDAF.\footnote{Note, that these numbers are taken from \citet{welbl2017constructing} and were obtained with different implementations of \textsc{BiDAF} and \textsc{FastQA}}. As the test set is hidden, we cannot diagnose the exact reason for the inconsistency with the results on the development set, but observe that FastQA suffers from a similar drop in performance. \begin{table*}[ht] \centering \input{results_countryhop.tex} \caption{Accuracy scores in percent for different predicates on the development set of the respective predicates. +/- denote independent modifications to the base algorithm. } \label{tab:results_countryhop} \end{table*} \subsection{Importance of Rules} Exemplary proofs generated by \textsc{NLProlog} for the predicates \textit{record\_label} and \textit{country} can be found in \cref{fig:proof_trees}. To study the impact of the rule-based reasoning on the predictive performance, we perform an ablation experiment in which we train \textsc{NLProlog} without any rule templates. The results can be found in the bottom half of Table~\ref{tab:results_countryhop}. On three of the five evaluated data sets, performance decreases markedly when no rules can be used and does not change on the remaining two data sets. This indicates that reasoning with logic rules is beneficial in some cases and does not hurt performance in the remaining ones. \subsection{Impact of Entity Embeddings} \label{ssec:entity_mlp} In a qualitative analysis, we observed that in many cases multi-hop reasoning was performed via aligning entities and not by applying a multi-hop rule. For instance, the proof of the statement \textit{country(Oktabrskiy Big Concert Hall, Russia)} visualized in Figure~\ref{fig:proof_trees}, is performed by making the embeddings of the entities \textit{Oktabrskiy Big Concert Hall} and \textit{Saint Petersburg} sufficiently similar. To gauge the extent of this effect, we evaluate an ablation in which we remove the MLP on top of the entity embeddings. The results, which can be found in Table~\ref{tab:results_countryhop}, show that fine-tuning entity embeddings plays an integral role, as the performance degrades drastically. Interestingly, the observed performance degradation is much worse than when training without rules, suggesting that much of the reasoning is actually performed by finding a suitable transformation of the entity embeddings. \begin{figure}[t] \centering \includegraphics[width=1\linewidth]{proof_trees-crop} \caption{Example proof trees generated by \textsc{NLProlog}, showing a combination of multiple rules. Entities are shown in red and predicates in blue. Note, that entities do not need to match exactly. % The first and third proofs were obtained without the entity MLP (as described in Section~\ref{ssec:entity_mlp}), while the second one was obtained in the full configuration of \textsc{NLProlog}.} \label{fig:proof_trees} \end{figure} \subsection{Error Analysis}\label{ssec:error_analysis} We performed an error analysis for each of the \textsc{WikiHop} predicates. To this end, we examined all instances in which one of the neural QA models (with \textsc{Sent2Vec}) produced a correct prediction and \textsc{NLProlog} did not, and labeled them with pre-defined error categories. Of the 55 instances, $49\%$ of the errors were due to \textsc{NLProlog} unifying the wrong entities, mainly because of an over-reliance on heuristics, such as predicting a record label if it is from the same country as the artist. In $25\%$ of the cases, \textsc{NLProlog} produced a correct prediction, but another candidate was defined as the answer. In $22\%$ the prediction was due to an error in predicate unification, \textit{i}.\textit{e}.{} \textsc{NLProlog} identified the correct entities, but the sentence did not express the target relation. Furthermore, we performed an evaluation on all problems of the studied \textsc{WikiHop} predicates that were unanimously labeled as containing the correct answer in the support texts by ~\citet{welbl2017constructing}. On this subset, the micro-averaged accuracy of \textsc{NLProlog} shows an absolute increase of $3.08$ pp, while the accuracy of \textsc{BiDAF} (\textsc{FastQA}) augmented with \textsc{Sent2Vec} decreases by $3.26$ ($3.63$) pp. We conjecture that this might be due to \textsc{NLProlog}'s reliance on explicit reasoning, which could make it less susceptible to spurious correlations between the query and supporting text. \section{Discussion and Future Work} We proposed \textsc{NLProlog}, a system that is able to perform rule-based reasoning on natural language, and can learn domain-specific rules from data. To this end, we proposed to combine a symbolic prover with pretrained sentence embeddings, and to train the resulting system using backpropagation. We evaluated \textsc{NLProlog} on two different QA tasks, showing that it can learn domain-specific rules and produce predictions which outperform those of the two strong baselines \textsc{BiDAF} and \textsc{FastQA} in most cases. While we focused on a subset of First Order Logic in this work, the expressiveness of \textsc{NLProlog} could be extended by incorporating a different symbolic prover. For instance, a prover for temporal logic~\citep{Orgun1994-jt} would allow to model temporal dynamics in natural language. We are also interested in incorporating future improvements of symbolic provers, triple extraction systems and pretrained sentence representations to further enhance the performance of \textsc{NLProlog}. Additionally, it would be interesting to study the behavior of \textsc{NLProlog} in the presence of multiple \textsc{WikiHop} query predicates. \section*{Acknowledgments} Leon Weber and Jannes Münchmeyer acknowledge the support of the Helmholtz Einstein International Berlin Research School in Data Science (HEIBRiDS). We would like to thank the anonymous reviewers for the constructive feedback. We gratefully acknowledge the support of NVIDIA Corporation with the donation of a Titan X Pascal GPU used for this research.
{'timestamp': '2019-06-17T02:13:32', 'yymm': '1906', 'arxiv_id': '1906.06187', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06187'}
arxiv
\section{Proof of Lemma \ref{lemma:asymptotic_results}} \label{app:proof_lemma1} To prove this lemma, we will need the following result: \begin{lemma} \label{lemma:assumptions_duchi} Under Assumption \ref{ass:structure}, we have that: \begin{itemize} \item There exists a measurable function $M: \mX\times\mY \to \mathbb{R}^+$ such that for all $\xi \in \mX\times \mY, \ell(\xi, \cdot)$ is $M(\xi)$-Lipschitz with respect to some norm $||.||$ in $\Theta$. \item $\mathbb{E}_{\xi \sim P} \left[M(\xi)^2\right] < \infty$ and $\mathbb{E}_{\xi \sim P}\left[\ell(\xi, \theta)^2 \right] < \infty$ for $\theta \in \Theta$. \end{itemize} where the distribution $P=\nu\otimes \pi$ and the loss $\ell(\xi,\theta)\triangleq c(x,y)\min\left(M, \frac{\pi_\theta(y \vert x)}{\pi_0(y \vert x)}\right)$ and $\xi=(x,y)$. \end{lemma} \begin{proof} We recall that the policy space is restricted to exponential policies such that $\pi_\theta(y\vert x) \propto \exp\left( \theta^T \phi(x, y)\right)$ and that under Assumption \ref{ass:structure} the parameter space $\Theta$ is compact. Let $f(\xi, \theta) \triangleq c(x,y) \frac{\pi_\theta(y \vert x)}{\pi_0(y \vert x)}$. We have that: \begin{align*} \left\vert\ell(\xi,\theta_1)-\ell(\xi,\theta_2)\right\vert \leq \left\vert f(\xi,\theta_1)-f(\xi,\theta_2)\right\vert, \quad \forall \theta_1, \theta_2\in\Theta \end{align*} Note that $f(\xi,\cdot)$ is continuous derivable on $\Theta$ compact. We note: \begin{align*} M(\xi) \triangleq \underset{\theta \in \Theta}{\max} \ \lVert\nabla_\theta f(\xi, \theta)\rVert \end{align*} $f(\xi,\cdot)$ is therefore $M(\xi)$-Lipschitz in $\theta$ w.r.t. $||.||$ and, consequently so is $\ell(\xi,\cdot)$. As the function $M$ is continuous, by boundedness of the context space $\mathcal{X}$ (Assumption \ref{ass:structure}), we have $\mathbb{E}_{\xi \sim P} [M(\xi)^2] < \infty$ and $\mathbb{E}_{\xi \sim P} [\ell(\xi, \theta)^2] < \infty$ for $\theta \in \Theta$. \end{proof} Under Assumptions \ref{ass:coherence} and \ref{ass:structure} and using the result in Lemma \ref{lemma:assumptions_duchi}, we now verify all the assumptions of Proposition 1 in \cite{duchi2016}. Lemma \ref{lemma:asymptotic_results} is consequently a direct application of the latter. \paragraph{Remark} Note that this result does not apply only to exponentially parametrized policies. Indeed, sufficient conditions for Lemma \ref{lemma:assumptions_duchi} would be milder - we only used that $\pi_\theta$ is continuously derivable w.r.t. $\theta$. \section{Proof of Lemma \ref{lemma:asymptotic_expansion}}\label{app:proof_lemma2} Under Assumptions \ref{ass:coherence} and \ref{ass:structure} and using Lemma \ref{lemma:assumptions_duchi}, Lemma \ref{lemma:asymptotic_expansion} is a direct application of Theorem 2 of in \cite{duchi2016}. \section{Proof of Lemma \ref{lemma:svp_is_dro}}\label{app:proof_lemma3} To ease notations, we denote $Z\triangleq \ell(\xi,\theta)$, with $\xi=(x,y)$ as in the manuscript. Let's consider $\varphi$ a coherent information divergence and $\varphi^*(z) := \underset{t>0}{\sup} \ zt-\varphi(t)$ its \textit{convex conjugate}. By strong duality, we have: \begin{eqnarray*} \sup_{D_\varphi(Q\|\hat{P}_n) \le \epsilon}\mathbb E_{Q}[Z] = \inf_{\gamma \ge 0}\gamma\epsilon + \sup_Q \ (\mathbb E_{Q}[Z]-\gamma D_\varphi(Q\|\hat{P}_n)) \end{eqnarray*} From Proposition 3.1 in \cite{gotoh2018}, we have the following result: \begin{equation} \sup_{D_\varphi(Q\|\hat{P}_n) \le \epsilon}\mathbb E_{Q}[Z] = \inf_{\gamma \ge 0}\gamma\epsilon + \mathbb{E}_{\hat{P}_n}[Z] + \inf_{c \in \mathbb R}(c + \gamma \mathbb E_{\hat{P}_n}[\varphi^*((Z-c)/\gamma)]) \label{equation_proposition31} \end{equation} In the specific case of the modified $\chi^2$ divergence, $\varphi(z)= \frac{1}{2\sqrt{2}} (z-1)^2$. Its convex conjugate $\varphi^\star$ is defined such that $\varphi^\star(z) = z + z^2$. Therefore, $\varphi^\star$ twice continuous differentiable in a neighborhood of $0$. From Theorem 3.2 \cite{gotoh2018}, we know that optimality in Equation \eqref{equation_proposition31} is obtained at $c=0$ and we consequently have the following equalities: \begin{eqnarray} \begin{split} \sup_{D_\varphi(Q\| \hat{P}_n) \le \epsilon}\mathbb E_{Q}[Z] &= \mathbb E_{\hat{P}_n}[Z] + \inf_{\gamma \ge 0}\left(\gamma\epsilon + \frac{1}{2 \varphi^{''}(0)} V_n(Z) \right)\\ &= \mathbb E_{\hat{P}_n}[Z] + \inf_{\gamma \ge 0}\left(\gamma\epsilon + \frac{1}{\gamma} V_n(Z) \right)\\ &= \mathbb E_{\hat{P}_n}[Z] + \sqrt{\epsilon V_n(Z)} \end{split} \end{eqnarray} This yields the announced result in Lemma~\ref{lemma:svp_is_dro}. \section{Proof of Lemma~\ref{lemma:kl_dro}} \label{app:kl_dro_proof} To ease notations, we denote $Z\triangleq \ell(\xi,\theta)$, with $\xi=(x,y)$ as in the manuscript. Without loss of generality, we can make the assumption that the cost function $c$ is bounded by $1$; $\forall (x,y)\in\mX\times\mY$, $\vert c(x,y)\vert\leq 1$ (this is also in accordance with the optimal loss scaling \cite{swaminathan2015counterfactual} used in CRM). By definition of the loss function $l$, the random variable $Z$ is bounded by $M$ a.s. With slight abuse of notation, one has: $$ \max_{KL\left(Q \vert\vert \hat{P}_n\right) \le \epsilon}\mathbb E_Q[\ell(\xi;\theta)] = \max_{D_{\varphi_\text{KL}}\left(Q \vert\vert \hat{P}_n\right) \le \epsilon}\mathbb E_Q[Z] $$ The quantities mentioned above all exist, as any distribution $Q$ satisfying the constraint has finite support (it is uniformly continuous w.r.p to $\Pn$ which as finite support itself) and since $Z$ is bounded a.s. Applying the Envelope Theorem of \cite{rockafellar2013fundamental} one gets: $$ \max_{KL\left(Q \vert\vert \hat{P}_n\right) \le \epsilon}\mathbb E_Q[\ell(\xi;\theta)] = \inf_{\gamma \ge 0}\left\{\gamma\epsilon + \inf_{c \in \mathbb R}\left(c + \gamma\mathbb E_{\hat{P}_n}[\varphi^*_{\text{KL}}((Z-c)/\gamma)]\right)\right\} $$ Remember that $\varphi_{\text{KL}}(z) = z\log z +z - 1$. It is a classical convex analysis exercise to show that its convex conjugate is $\varphi^*_\text{KL}(z)=e^z -1$. Therefore: $$ \max_{KL\left(Q \vert\vert \hat{P}_n\right) \le \epsilon}\mathbb E_Q[\ell(\xi;\theta)] = \inf_{\gamma \ge 0}\left\{\gamma\epsilon + \inf_{c \in \mathbb R}\left(c + \gamma\mathbb E_{\hat{P}_n}[e^{(Z-c)/\gamma}-1]\right)\right\} $$ Solving $$ \inf_{c \in \mathbb R}\left(c + \gamma\mathbb E_{\hat{P}_n}[e^{(Z-c)/\gamma}-1]\right) $$ is straightforward and leads to: \begin{align} \max_{KL\left(Q \vert\vert \hat{P}_n\right) \le \epsilon}\mathbb E_Q[\ell(\xi;\theta)] = \inf_{\gamma \ge 0}\left\{\gamma\epsilon + \gamma\log\mathbb E_{\hat{P}_n}\left[e^{Z/\gamma}\right]\right\} \label{eq:solving_for_gamma} \end{align} Differentiating the r.h.s and setting to 0 shows that the optimal $\gamma$ is solution to the fixed-point equation: \begin{align} \gamma = \frac{\mathbb E_{\hat{P}_n^\gamma}[Z]}{\epsilon + \log(\mathbb E_{\hat{P}_n}[e^{Z/\gamma}])} \end{align} where $d\hat{P}_n^\gamma(z) := (1/\mathbb E_{\hat{P}_n}[e^{z/\gamma}])e^{z/\gamma}d\hat{P}_n(z)$ is the (density of the) Gibbs distribution at temperature $\gamma$ and state degeneracies $\hat{P}_n$. Replacing this value for $\gamma$ in the r.h.s of \eqref{eq:solving_for_gamma} yields the announced result. Let us note that this formula has been obtained in \cite{hu2012} using another line of proof. \section{Proof of Lemma~\ref{lemma:gamma}} \label{app:gamma_proof} Using notations from Appendix~\ref{app:kl_dro_proof}, consider the log moment generating function : \begin{align} \Phi:\alpha \to \log\bE_{\Pn}\left[e^{Z\alpha}\right] \end{align} well defined as $\Pn$ has finite support and $Z$ is bounded a.s. It checks the following equalities: $$ \begin{aligned} \Phi(0) &= 0 \\ \Phi'(0) &= \bE_{\Pn}\left[Z\right]\\ \Phi''(0) &= V_n(Z) \end{aligned} $$ and a second-order Taylor expansion around 0 yields: $$ \Phi(\alpha) = \alpha \bE_{\Pn}\left[Z\right] + \frac{\alpha^2}{2}V_n(Z) + o_{0}(\alpha^2) $$ With $\alpha=1/\gamma$ and injecting this result in the r.h.s of Equation~\eqref{eq:solving_for_gamma} yields: \begin{align} \max_{KL\left(Q \vert\vert \hat{P}_n\right) \le \epsilon}\mathbb E_Q[\ell^M(\xi;\theta)] = \inf_{\gamma \ge 0}\left\{\gamma\epsilon + \bE_{\Pn}\left[Z\right] +\frac{V_n(Z)}{2\gamma}+o_{\infty}(1/\gamma)\right\} \end{align} Solving (approximately) the r.h.s of the above equation yields the following relation: $$ \gamma \simeq \sqrt{\frac{V_n(Z)}{2\epsilon}} $$ as announced by Lemma~\ref{lemma:gamma}. \section{Experimental details} \label{app:exps} We hereinafter provide details on the experimental procedure we followed to obtain the results announced in Section~\ref{sec:exp}. This procedure is the one described in \cite{swaminathan2015counterfactual} - we used the code provided by its authors \footnote{\url{http://www.cs.cornell.edu/~adith/POEM/index.html}} for our experiments. For every of the four dataset we consider (Scene, Yeast, RCV1-Topics and TMC2009), the dataset is randomly split in two parts: 75\% goes to $\mathcal{D}^\star_{\text{train}}$ and 25\% to $\mathcal{D}^\star_{\text{valid}}$. The test dataset $\mathcal{D}_{\text{test}}$ is provided by the original dataset. The logging policy is a CRF is then trained on a fraction ($f$=5\%) of the training dataset $\mathcal{D}^\star_{\text{train}}$. The logged bandit dataset is generated by running this policy through $\mathcal{D}^\star_{\text{train}}$ for $\Delta=4$ times ($\Delta$ is the \emph{replay count}). As in \cite{swaminathan2015counterfactual, swaminathan2015batch, swaminathan2015self} we train linearly parametrized exponential policies: $$ \pi_\theta(y\vert x) = \frac{\exp\left(\theta^T\phi(x,y)\right)}{\mathbb{Z}(x)} $$ where ${\mathbb{Z}(x)}$ is a normalization constant. We use the same joint feature map $\phi(x,y)=x\otimes y$ with $y$ being a bit vector $\left\{0,1\right\}^L$ where $L$ describes the number of labels of the considered multi-label classification task. We optimize the objective of each algorithm (CIPS, POEM, \firstalgo, \secondalgo) with the L-BFGS routine. Their respective hyper-parameters are determined via cross-validation on $\mathcal{D}^\star_{\text{valid}}$ with the unbiased estimator \eqref{eq:ips_empirical_risk}. The different ranges used for this cross-validation step are detailed in Table~\ref{tab:hp_range}. \begin{table}[h] \centering \begin{tabular}{c|c|c} \textbf{Algorithm} & \textbf{Hyper-parameter} & \textbf{Logarithmic range} \\ \hline CIPS & - & - \\ POEM & $\lambda$ & [-6,0] \\ \firstalgo & $\gamma$ & [-3,4] \\ \secondalgo & $\epsilon$ & [-6, 0] \end{tabular} \caption{Logarithmic ranges for the cross-validation of hyper-parameters.} \label{tab:hp_range} \end{table} \section{Batch Learning from Logged Bandit Feedback} \label{sec:blbf} \subsection{Notation and terminology} We denote $x\in\mX$ arbitrary \emph{contexts} drawn from an unknown distribution $\nu$ and presented to the decision maker. Such a quantity can describe covariate information about a patient for a clinical test, or a potential targeted user in a recommender system. The variable $y\in\mY$ denotes the \emph{actions} available to the decision maker - the potential medications to give to the patient, or possible advertisements targeting the user for instance. A \emph{policy} is a mapping $\pi:\mX\to\mP\left(\mY\right)$ from the space of contexts to probabilities in the action space. For a given (context, action) pair $(x,y)$, the quantity $\pi(y\vert x)$ denotes the probability of the policy $\pi$ to take the action $y$ when presented with the context $x$. When picking the action $y$ for a given context $x$, the decision maker receives a \emph{reward} $\delta(x,y)$, drawn from an unknown distribution. In our examples, this reward could indicate a patient's remission, or the fact that the targeted user clicked on the displayed ad. This reward $\delta(x,y)$ can also be assumed to be deterministic - as in \cite{swaminathan2015batch, swaminathan2015counterfactual, swaminathan2015self}. We make this assumption in the rest of this manuscript. Finally, for a given context $x \in \mathcal{X}$ and an action $y \in \mathcal{Y}$, we define the cost function $c(x,y) \triangleq - \delta(x,y)$. In this paper, we try to find policies producing low expected costs. To make this search tractable, it is usual to restrict the search to a family of \emph{parametric} policies, henceforth tying policies $\pi_\theta$ to a vector $\theta\in\Theta$. The $\emph{risk}$ $R(\theta) \triangleq \bE_{x\sim \nu, y\sim \pi_\theta(\cdot\vert x)}\left[ c(x,y) \right] $of the policy $\pi_\theta$ corresponds to the expected cost obtained by the policy $\pi_\theta$, a quantity the decision maker will try to minimize. \subsection{Counterfactual Risk Minimization} \label{subsec:crm} In practical applications, it is common that one has only access to the \emph{interaction logs} of a previous version of the decision making system, also called a \emph{logging policy} (denoted $\pi_0$). More formally, we are interested in the case where the only available data is a collection of quadruplets $\mH\triangleq \left(x_i ,y_i, p_i, c_i\right)_{1\leq i \leq n}$, where the costs $c_i \triangleq c(x_i, y_i)$ were obtained after taking an action $y_i$ with probability $p_i\triangleq \pi_0(y_i\vert x_i)$ when presented with a context $x_i \sim \nu$. In order to search for policies $\pi_\theta$ with smaller risk than $\pi_0$, one needs to build counterfactual estimators for $R(\theta)$ from the historic $\mH$. One way to do so is to use \emph{inverse propensity scores} \cite{rosenblum1983central}: \begin{eqnarray} R(\theta) = \bE_{x\sim \nu, y\sim \pi_\theta(x)}\left[ c(x,y) \right] = \bE_{x \sim \nu, y \sim \pi_0(x)}\left[ c(x,y) \frac{\pi_\theta(y\vert x)}{\pi_0(y\vert x)} \right], \label{eq:ips_risk} \end{eqnarray} for any $\pi_\theta$ absolutely continuous w.r.t $\pi_0$. Henceforth, $R(\theta)$ can readily be approximated with samples $(x_i, y_i, p_i,c_i)$ from the interaction logs $\mH$ via the sample average approximation: \begin{align} R(\theta) \simeq \frac{1}{n}\sum_{i=1}^n c_i\frac{\pi_\theta(y_i\vert x_i)}{p_i}. \label{eq:ips_empirical_risk} \end{align} Bluntly minimizing the objective provided by the counterfactual risk estimator \eqref{eq:ips_empirical_risk} is known to be sub-optimal, as it can have \emph{unbounded} variance \cite{ionides2008truncated}. It is therefore a classical technique \cite{bottou2013counterfactual, cortes2010learning, strehl2010learning, swaminathan2015batch} to \emph{clip} the propensity weights . This leads to the Clipped Inverse Propensity Scores (CIPS) estimator: \begin{align} \hat{R}_n(\theta) \triangleq \frac{1}{n}\sum_{i=1}^n c_i \min\left(M, \frac{\pi_\theta(y_i\vert x_i)}{p_i}\right). \label{eq:empirical_clipped} \end{align} The variable $M$ is an hyper-parameter, balancing the variance reduction brought by weight clipping and the bias introduced in the empirical estimation of $R(\theta)$. The search for a minimal $\theta$ with respect to the estimator $\hat{R}_n^M(\theta)$ is often referred to as \emph{Counterfactual Risk Minimization} (CRM). \paragraph{Remark 1} Other techniques have been proposed in the literature to reduce the variance of the risk estimators. For instance, the doubly robust risk \cite{dudik2011doubly} takes advantage of both counterfactual estimators and supervised learning methods, while the self-normalized risk \cite{swaminathan2015self} was designed to counter the effect of a phenomenon known as propensity overfitting. We do not explicitly cover them in our analysis, but the results we derive hereinafter also hold for such estimators. \subsection{Sample-Variance Penalization} The main drawback of the CIPS estimator is that two different policies can have risk estimates of highly different variance - something the sample average approximation cannot capture. The authors of \cite{swaminathan2015counterfactual} developed a variance-sensitive action selection process, penalizing policies with high-variance risk estimates. Their approach is based on a sample-variance penalized version of the CIPS estimator: \begin{align} \hat{R}_n^{\lambda} (\theta) \triangleq \hat{R}_n(\theta) + \lambda \sqrt{V_n(\theta)/n}, \label{eq:poem_obj} \end{align} where $\lambda$ is an hyper-parameter set by the practitioner, and $V_n(\theta)$ denotes the empirical variance of the quantities $c_i \min\left(M, \frac{\pi_\theta(y_i \vert x_i)}{p_i}\right)$. The main motivation behind this approach is based on confidence bounds derived in \cite{maurer09}, upper-bounding with high-probability the true risk $R(\theta)$ by the empirical risk $\hat{R}_n(\theta)$ augmented with an additive empirical variance term. In a few words, this allows to build and optimize a pessimistic envelope for the true risk and penalize policies with high variance risk estimates. The authors of \cite{swaminathan2015counterfactual} proposed the Policy Optimization for Exponential Models (POEM) algorithm and showed state-of-the-art results on a collection of counterfactual tasks when applying this method to exponentially parametrized policies: \begin{eqnarray} \pi_\theta(y\vert x) \propto \exp\left( \theta^T \phi(x, y)\right), \label{eq:exponential_model} \end{eqnarray} with $\phi(x, y)$ a $d$-dimensional joint feature map and $\Theta$ a subset of $\mathbb{R}^d$. \section{Distributionally Robust Counterfactual Risk Minimization} \label{sec:dro} \subsection{Motivating distributional robustness for CRM} For more concise notations, let us introduce the variable $\xi=(x,y)$, the distribution $P=\nu\otimes \pi$ and the loss $\ell(\xi,\theta)\triangleq c(x,y)\min\left(M, \frac{\pi_\theta(y \vert x)}{\pi_0(y \vert x)}\right)$. The minimization of the counterfactual risk \eqref{eq:ips_risk}, now writes $\theta^\star \triangleq \argmin_{\theta\in\Theta}\bE_{\xi\sim P}\left[\ell(\xi,\theta)\right]$ and its empirical counterpart $\hat{\theta}_n \triangleq \argmin_{\theta\in\Theta}\hat{R}_n(\theta)$. The consistency of the estimator $\hat{\theta}_n$ holds under general conditions and the empirical risk converges to the optimal true risk \cite{vapnik1992principles, vapnik1999overview}: \begin{align} \mathbb E_{\xi \sim P}[\ell(\xi; \theta^\star)] - \hat{R}_n(\hat{\theta}_n) \underset{n\to\infty}{\longrightarrow} 0 \end{align} However, one of the major drawbacks of this approach is that the empirical risk $\hat{R}_n(\theta)$ cannot be used as a \emph{performance certificate} for the true risk $\mathbb E_{\xi \sim P}[\ell(\xi;\theta)]$. Indeed, one will fail at controlling the true risk of any parameter $\theta$ since by the Central Limit Theorem: \begin{equation}\label{eq:erm_drawback} \lim_{n \to \infty}\bP\left(\bE_{\xi \sim P}[\ell(\xi;\theta)] \le \hat{R}_n(\theta)\right) = 1/2 \end{equation} One way to circumvent this limitation is to treat the empirical distribution $\Pn$ with \emph{skepticism} and to replace it with an uncertainty set $\mU_\epsilon(\Pn)$ of distributions around $\Pn$ with $\epsilon > 0$ a parameter controlling the size of the uncertainty set $\mathcal U_\epsilon(\Pn)$. This gives rise to the \emph{distributionally robust} counterfactual risk: \begin{align} \Rrob{\mU}{\theta, \epsilon} \triangleq \max_{Q\in\mU_\epsilon(\Pn)} \bE_{\xi \sim Q}[\ell(\xi;\theta)]. \label{eq:robust_risk} \end{align} Minimizing this quantity w.r.t to $\theta$ yields the general DRO program: \begin{align} \Trob{} \triangleq \argmin_{\theta \in \Theta} \Rrob{\mU}{\theta, \epsilon} = \underset{\theta \in \Theta}{\argmin} \ \max_{Q \in \mathcal U_\epsilon(\Pn)}\mathbb E_{\xi \sim Q}[\ell(\xi;\theta)]. \label{eq:dro} \end{align} There is liberty on the way to construct the uncertainty set $\mathcal U_\epsilon(\Pn)$ including parametric \cite{madry2017towards, Xiao2018GeneratingAE} and non-parametric designs \cite{blanchet2016, parys17, sinha2018}. Moreover, for well chosen uncertainty sets \cite{duchi2016}, one can prove performance guarantees asserting that asymptotically (i.e in the limit $n \rightarrow \infty$), for all $\theta\in\Theta$: $$ \bE_{\xi \sim P}[\ell(\xi;\theta)] \le \Rrob{\mU}{\theta, \epsilon_n} \,\text{w.h.p}\quad \text{and} \quad \bE_{\xi \sim P}[\ell(\xi; \theta)] - \Rrob{\mU}{\theta, \epsilon_n} \rightarrow 0 $$ The robust risk therefore acts as a consistent certificate on the true risk. We believe that these properties alone are enough to motivate the use of DRO for the CRM problem, as it provides an elegant way to \emph{design consistent asymptotic upper bounds for the true risk} and ensure a small post-decision surprise. We detail such guarantees in the next subsection. Later, we draw links between DRO and the POEM, showing that a wide variety of DRO problems \emph{account for the empirical variance} of the samples, therefore mitigating the limitations of empirical averages as discussed in \ref{subsec:crm}. \subsection{Guarantees of robustified estimators with $\varphi$-divergences}\label{section:3.2} We are interested in DRO instances that are amenable to direct optimization. To this end, we focus here only on uncertainty sets $\mathcal U_\epsilon(\Pn)$ based on information divergences \cite{csiszar1967information}, since they strike a nice compromise between ease of implementation and theoretical guarantees that will reveal useful for the CRM problem. The use of information divergences for DRO has already been largely studied in several works (for example \cite{duchi2016,gotoh2018}). For the sake of completeness, we recall in Definition~\ref{def:inf_divergences} the definition of information divergences. \begin{definition}[$\varphi$-divergences] Let $\varphi$ be a real-valued, convex function such that $\varphi(1)=0$. For a reference distribution $P$, define the \textit{divergence} of another distribution $Q$ with respect to $P$ as \begin{align} D_\varphi(Q\|P) \triangleq \begin{cases}\int\varphi(dQ/dP)dP,&\mbox{ if }Q \ll P,\\+\infty,&\mbox{ else.}\end{cases}. \end{align} \label{def:inf_divergences} \end{definition} Subsequently, the definition of the uncertainty set $\mU_\epsilon$ relies only on $\varphi$-divergences as follows: \begin{align} \mathcal U_{\epsilon}(\hat{P}_n) = \left\{Q \mid D_\varphi(Q\|\Pn) \le \epsilon \right\}. \end{align} We need to ensure that the set of $\varphi$-divergences used to define the resulting robust risk $\Rrob{^{\varphi}}{\theta, \epsilon}$ satisfies some basic \emph{coherence} properties. We therefore make further assumptions about the measure of risk $\varphi$ to narrow the space of information divergences we consider: \begin{ass}[Coherence] $\varphi$ is a real-valued function satisfying: \vspace{-3pt} \begin{itemize} \itemsep-0.3em \item $\varphi$ is convex and lower-semi-continuous \item $\varphi(t) = \infty$ for $t < 0$, and $\varphi(t) \ge \varphi(1)=0$, \, $\forall t\in\mathbb R$ \item $\varphi$ is twice continuously differentiable at $t=1$ with $\varphi'(1)=0$ and $\varphi''(1)>0$ \end{itemize} \label{ass:coherence} \end{ass} The axioms presented in Assumption~\ref{def:inf_divergences} have been proposed and studied extensively in \cite{rockafellar2018}. Examples of coherent divergences include the Chi-Square, Kullback-Leibler divergences and the squared Hellinger distance. Before stating the announced asymptotic guarantees, we make further assumptions on the structure of both the context and parameter spaces. \begin{ass}[Structure]\textcolor{white}{.} \vspace{-5pt} \begin{itemize} \itemsep-0.3em \item $\Theta$ is a compact subset of some $\mathbb R^d$. \item $\mathcal{X}$ is a compact subset of some $\mathbb{R}^D$. \end{itemize} \label{ass:structure} \end{ass} We now state Lemma~\ref{lemma:asymptotic_results} which provides asymptotic certificate guarantees for the robust risk, asymptotically controlling the true counterfactual risk $\bE_{\xi \sim P}[\ell(\xi;\theta)]$ with high probability. It is easy to show that under Assumptions~\ref{ass:coherence} and \ref{ass:structure}, Lemma~\ref{lemma:asymptotic_results} can be obtained by a direct applications of Proposition~1 of \cite{duchi2016}. The full proof of this result is provided in Appendix~\ref{app:proof_lemma1}. \begin{lemma}[Asymptotic guarantee - Proposition 1 of \cite{duchi2016}] Under Assumption \ref{ass:coherence}, for a fixed level of confidence $\delta \in (0, 1]$, we have that $\forall \theta \in \Theta$: \begin{equation} \underset{n \to \infty}{\lim} \ \ \mathbb{P} \left( \mathbb E_{\xi \sim P} \left[ \ell(\xi;\theta) \right] \le \Rrob{^{\varphi}}{\theta, \epsilon_n} \right) \ge 1-\delta \end{equation} where $\epsilon_n$ is defined by the $(1-\delta)$ Chi-Squared quantile, $\epsilon_n(\delta) = \chi^2_{1, 1-\delta}/n$. \label{lemma:asymptotic_results} \end{lemma} For the CRM problem, this result is of upmost importance as it allows us to control the post-decision surprise suffered for a given policy $\pi_\theta$ and allows for a pointwise control of the true risk. \paragraph{Remark 2} A stronger result than Lemma \ref{lemma:asymptotic_results} would control with high probability the true risk of the robustified policy $\mathbb E_{\xi \sim P}[ \ell(\xi;\Trob{})]$ with the optimal value $\Rrob{\mU}{\Trob{}, \epsilon_n}$. It is easy to see that, if $P \in \mathcal{U}_\epsilon$, then $\mathbb E_{\xi\sim P} [\ell(\xi;\Trob{})] \le \Rrob{\mU}{\Trob{}, \epsilon_n}$, hence $\mathbb{P}(\mathbb E_{\xi\sim P} [\ell(\xi;\hat{\theta}_n)] \le \Rrob{\mU}{\Trob{}, \epsilon_n}) \ge \mathbb{P}(P \in \mathcal{U}_\epsilon)$. By exhibiting strong rates of convergence of the empirical distribution $\hat{P}_n$ towards the true distribution $P$, such a result could be reached. Under mild assumptions on $P$, this guarantee has been proved in \cite{esfahani2017} for Wasserstein based uncertainty sets. In our current case where $\mathcal{U}_\epsilon$ is defined by information divergences this result holds solely under the assumption that $P$ is finitely supported \cite{van2017data}, a plausible situation when the logging policy is defined on a finite number of (context, action) pairs. \subsection{Equivalences between DRO and SVP} \label{subsec:svpisdro} In this subsection, we focus on stressing the link between DRO and sample variance penalization schemes as used in the POEM algorithm. In Lemma~\ref{lemma:asymptotic_expansion}, we present an asymptotic equivalence between the robust risk (defined with coherent $\varphi$ divergences) and the SVP regularization used in POEM. This Lemma is a specific case of existing results, already detailed in \cite{duchi2016, namkoong2017variance} and \cite{gotoh2017, gotoh2018}. \begin{lemma} [Asymptotic equivalence - Theorem 2 of \cite{duchi2016}] Under Assumptions~\ref{ass:coherence} and \ref{ass:structure}, for any $\epsilon \ge 0$, integer $n > 0$ and $\theta \in \Theta$ we have: \begin{equation} \begin{aligned} \Rrob{^{\varphi}}{\theta, \epsilon_n} = \hat{R}_n(\theta) + \sqrt{\epsilon_n V_n(\theta)} + \alpha_n(\theta), \end{aligned} \end{equation} with $\sup_{\theta}\sqrt{n}|\alpha_n(\theta)| \overset{P}{\longrightarrow} 0$ and $\epsilon_n = \epsilon/n$. \label{lemma:asymptotic_expansion} \end{lemma} This expansion gives intuition on the practical effect of the DRO approach: namely, it states that the minimization of the robust risk $\Rrob{^{\varphi}}{\theta}$ based on coherent information divergences is \emph{asymptotically equivalent} to the POEM algorithm. This link between POEM and DRO goes further: the following Lemma states that sample-variance penalization is an \emph{exact} instance of the DRO problem when the uncertainty set is based on the chi-square divergence. \begin{lemma}[Non-asymptotic equivalence] Under Assumption \ref{ass:structure} and for $\chi^2$-based uncertainty sets, for any $\epsilon \ge 0$, integer $ n > 0$ and $\theta \in \Theta$ we have: \begin{equation} \begin{aligned} \Rrob{^{\chi^2}}{\theta, \epsilon} = \hat{R}_n(\theta) + \sqrt{\epsilon V_n(\theta)}. \end{aligned} \label{eq:svp_is_dro} \end{equation} \label{lemma:svp_is_dro} \end{lemma} The proof is detailed in Appendix \ref{app:proof_lemma3}. In the case of $\chi^2$-based uncertainty sets, the expansion of Lemma~\ref{lemma:asymptotic_expansion} holds non-asymptotically, and the POEM algorithm can be interpreted as the minimization of the distributionally robust risk $\Rrob{^{\chi^2}}{\theta, \epsilon}$. To the best of our knowledge, it is the first time that a connection is drawn between counterfactual risk minimization with SVP \cite{swaminathan2015batch} and DRO. \subsection{Kullback-Leibler based CRM} \label{subsec:kl_crm} Among information divergences, we are interested in the ones that allow tractable optimization. Going towards this direction, we investigate in this subsection the robust counterfactual risk generated by Kullback-Leibler (KL) uncertainty sets and stress its efficiency. The KL divergence is a \emph{coherent} $\varphi$-divergence, with $\varphi(z) \triangleq z\log(z)+z-1$ for $z>0$ and $\varphi(z)=\infty$ elsewhere. The robust risk $\Rrob{^{\text{KL}}}{\theta, \epsilon}$ therefore benefits from the guarantees of Lemma~\ref{lemma:asymptotic_results}. Furthermore, it enjoys a simple analytic formula stated in Lemma~\ref{lemma:kl_dro} that allows for direct optimization. For conciseness reasons, the proof of this Lemma is deferred to Appendix~\ref{app:kl_dro_proof}. \begin{lemma}[Kullback-Leibler Robustified Counterfactual Risk] \label{lemma:kl_dro} Under Assumption \ref{ass:structure}, the robust risk defined with a Kullback-Leibler uncertainty set can be rewritten as: \begin{align} \Rrob{^{\text{\upshape KL}}}{\theta, \epsilon} &= \inf_{\gamma > 0} \left( \gamma\epsilon + \gamma\log\mathbb E_{\xi \sim \Pn}[\exp(\ell(\xi;\theta)/\gamma)] \right) \\ &=\mathbb{E}_{\xi\sim \Pn^{\gamma^\star}(\theta)}[\ell(\xi;\theta)]. \label{eq:kl-dro} \end{align} where $\Pn^{\gamma}$ denotes the Boltzmann distribution at temperature $\gamma > 0$, defined by $$ \Pn^\gamma(\xi_i|\theta) = \frac{\exp(\ell(\xi_i; \theta)/\gamma)}{\sum_{j=1}^n\exp(\ell(\xi_j; \theta)/\gamma)}. $$ \end{lemma} A direct consequence of Lemma~\ref{lemma:kl_dro} is that the worst-case distribution in the uncertainty set (defined by the KL divergence) takes the form of a Boltzmann distribution. Henceforth, minimizing the associated robust risk is equivalent with the optimization of the following objective: \begin{align} \Rrob{^{\text{\upshape KL}}}{\theta} = \frac{\sum_{i=1}^n \ell(\xi_i; \theta)\exp(\ell(\xi_i; \theta)/\gamma^\star)}{\sum_{j=1}^n \exp(\ell(\xi_j; \theta)/\gamma^\star)}. \label{eq:kl_objective} \end{align} From an optimization standpoint this amounts to replacing the empirical distribution of the logged data with a Boltzmann adversary which re-weights samples in order to put more mass on hard examples (examples with high cost). In what follows, we call \firstalgo the algorithm minimizing the objective \eqref{eq:kl_objective} while treating $\gamma^\star$ as a hyper-parameter that controls the hardness of the re-weighting. A small value for $\gamma^\star$ will lead to a conservative behavior that will put more weight on actions with high propensity cost. In the limit when $\gamma^\star \to 0$, the robust risk only penalizes the action with highest propensity re-weighted cost. On the other end, a very large $\gamma^\star$ brings us back in the limit to the original CIPS estimator where the samples have equal weights. In a naive approach, this parameter can be determined through \emph{cross-validation} and kept constant during the whole optimization procedure. Lemma~\ref{lemma:gamma} goes further into the treatment of the optimal temperature parameter $\gamma^*$ and provides an \emph{adaptive} rule for updating it during the robust risk minimization procedure. \begin{lemma} The value of the optimal temperature parameter $\gamma^*$ can be approximated as follows: \begin{align} \gamma^* \approx \sqrt{\frac{V_n(\theta)}{2\epsilon}}. \end{align} \label{lemma:gamma} \end{lemma} The proof relies on a second-order Taylor approximation of the log moment-generating function of the loss, more precisely, of the convex one-dimensional function and is deferred to Appendix~\ref{app:gamma_proof}. This results implies that $\gamma^*$ should be updated concurrently to the parameter $\theta$ during the minimization of the robustified risk \eqref{eq:kl_objective}. This leads to an algorithm we call adaptive \firstalgo, or aKL-CRM. Pseudo-code for this algorithm is provided in Algorithm~\ref{algo:adaptive_kl_crm}. As for POEM and \firstalgo, its hyper-parameter $\epsilon$ can be determined through cross-validation. \begin{algorithm} \caption{\secondalgo} \label{algo:adaptive_kl_crm} \SetKwBlock{Sampling}{\mdseries \textit{(Sampling)}}{} \SetKwBlock{CMA}{\mdseries\textit{(CMA-ES iteration)}}{} \SetKwBlock{GNN}{\mdseries\textit{(NICE iteration)}}{} \SetKwBlock{PEN}{\mdseries\textit{(Penalty update)}}{} \SetKwComment{Comment}{//}{} \SetKwInOut{Input}{inputs} \SetKwInput{HP}{hyper-parameters} \SetKwInOut{Output}{output} \Input{ $\mathcal H=\{(x_1,y_1,p_1,c_1),\ldots,(x_n,y_n,p_n,c_n)\}$, parametrized family of policies $\pi_\theta$} \HP{clipping constant $M$, uncertainty set size $\epsilon$} \Repeat{convergence} { \textbf{compute} the counterfactual costs $z_i\leftarrow c_i\pi_\theta(y_i\vert x_i)/p_i$ for $i=1,\hdots,n$\\ \textbf{compute} the optimal temperature $\gamma^\star \leftarrow \sqrt{\sum_{j=1}^n\left(z_i-\bar{z}\right)^2/(2\epsilon)}$, where $\bar{z} = \sum_{j=1}^n z_i/n$\\ \textbf{compute} the normalized costs $s_i \leftarrow e_i/\sum_{j=1}^n e_j$ for $i=1,\hdots,n$, where $e_i = e^{z_i/\gamma^\star}$\\ \textbf{compute} the re-weighted loss $L \leftarrow \sum_{i=1}^n z_is_i$\\ \textbf{update} $\theta$ by applying an L-BFGS step to the loss $L$ } \end{algorithm} \section{Experimental results} \label{sec:exp} To evaluate and compare the two algorithms we previously introduced to existing solutions, we rigorously follow the experimental procedure introduced in \cite{swaminathan2015counterfactual} and used in several other works \cite{swaminathan2015batch, swaminathan2015self} since then. It relies on a supervised to unsupervised dataset conversion \cite{agarwal2014taming} to build bandit feedback from multi-label classification datasets. As in \cite{swaminathan2015counterfactual}, we train exponential models $$ \pi_\theta(y\vert x) \propto \exp\left(\theta^T\phi(x,y)\right) $$ for the CRM problem and use the same datasets taken from the LibSVM repository. \subsection{Methodology} For any multi-label classification tasks, let us note $x$ the input features and $y^\star\in\{0,1\}^q$ the labels. The full supervised dataset is denoted $\mathcal{D}^\star\triangleq \left\{(x_1,y_1^\star),\hdots, (x_N, y_N^\star)\right\}$, and is split into three parts: $\mathcal{D}^\star_{\text{train}}$, $\mathcal{D}^\star_{\text{valid}}$, $\mathcal{D}^\star_{\text{test}}$. As in \cite{swaminathan2015counterfactual}, we use joint features maps $\phi(x,y) = x\otimes y$ and train a Conditional Random Field \cite{lafferty2001conditional} (CRF) on a fraction (5\%, randomly constituted) of $\mathcal{D}^\star_{\text{train}}$. This CRF has access to the full supervised feedback and plays the role of the logging policy $\pi_0$. That is, for every $x_i\in \mathcal{D}^\star$, a label prediction $y_i$ is sampled from the CRF with probability $p_i$. The quality of this prediction is measured through the Hamming loss: $c_i = \sum_{l=1}^q \vert y_l - y_l^\star\vert$. Repeating this procedure $\Delta$ times through $\mathcal{D}^\star_{\text{train}}$ enables us to construct the bandit dataset $\mathcal{H}$. After training, the performances of the different policies $\pi$ are reported as their expected Hamming loss on the held-out set $\mathcal{D}^\star_{\text{test}}$. Every experiment is run 20 times with a different random seed (which controls the random training fraction for the logging policy and the creation of the bandit dataset). For each dataset we compare our algorithm with the naive CIPS estimator and the POEM. For all four algorithms (CIPS, POEM, \firstalgo, \secondalgo), the numerical optimization routine is deferred to the L-BFGS algorithm. As in \cite{swaminathan2015counterfactual}, the clipping constant $M$ is always set to the ratio of the 90\%ile to the 10\%ile of the propensity scores observed in logs $\mathcal{H}$. Other hyper-parameters are selected by cross-validation on $\mathcal{D}^\star_{\text{valid}}$ with the unbiased counterfactual estimator \eqref{eq:ips_empirical_risk}. In the experimental results, we also report the performance of the logging policy $\pi_0$ on the test set as an indicative baseline measure, and the performance of the CRF despite of its unfair advantages over the other algorithms. Further details on our experimental set-up can be found in Appendix~\ref{app:exps}. \subsection{Results} Table~\ref{tab:results} reports the expected Hamming loss of the policies obtain with different algorithms on the Scene, Yeast, RCV1-Topics and TMC2007 dataset, averaged on 20 random seeds. The results reported for the baselines are coherent with \cite{swaminathan2015counterfactual, swaminathan2015batch}. On each dataset, \secondalgo comes out at one of the best algorithm (according to a one-tailed paired difference t-test at significance level 0.05 ) and outperforming the POEM baseline on three out of four datasets. The results for \firstalgo are more mitigated: it outperforms POEM on two datasets, but shows weaker performance on the two others. As in \cite{swaminathan2015counterfactual}, we can further evaluate the quality of the learned policies by evaluating the Hamming loss of their \emph{greedy} version (selecting only the arm that is attributed the most probability mass by the policy). This comes at less expense that sampling from the policy as this does not require to compute the normalizing constant in \eqref{eq:exponential_model}. These results are reported in Table~\ref{tab:greedy_results}, and are consistent with the conclusions of Table~\ref{tab:results}. One can note that the improvement brought by \secondalgo over POEM is even sharper under this evaluation lense. \begin{table} \centering \begin{tabular}{c?c|c|c|c?} & \textbf{Scene} & \textbf{Yeast} & \textbf{RCV1-Topics} & \textbf{TMC2009} \\ \Xhline{1.5pt} $\pi_0$ & 1.529 & 5.542 & 1.462 & 3.435\\ \hline \hline CIPS & 1.163 & 4.658 & 0.930 & 2.776\\ POEM & 1.157 & \textbf{4.535}& 0.918 & 2.191\\ \firstalgo & 1.146 & 4.604 & 0.922 & 2.136\\ \secondalgo & \textbf{1.128} & \textbf{4.553} & \textbf{0.783}& \textbf{2.126} \\ \hline \hline CRF & 0.646 & 2.817& 0.341 & 1.187 \end{tabular} \caption{Expected Hamming loss on $\mathcal{D}^*_{\text{test}}$ for the different algorithms, averaged over 20 independent runs. Bold font indicate that one or several algorithms are statistically better than the rest, according to a one-tailed paired difference t-test at significance level of 0.05 - as in \cite{swaminathan2015counterfactual}.} \label{tab:results} \end{table} \begin{table} \centering \begin{tabular}{c?c|c|c|c?} & \textbf{Scene} & \textbf{Yeast} & \textbf{RCV1-Topics} & \textbf{TMC2009} \\ \Xhline{1.5pt} CIPS & 1.163 & 4.369 & 0.929 & 2.774\\ POEM & 1.157 & \textbf{4.261}& 0.918 & 2.190\\ \firstalgo & 1.146 & 4.316 & 0.922 & 2.134\\ \secondalgo & \textbf{1.128} & \textbf{4.271} & \textbf{0.779}& \textbf{2.034} \end{tabular} \caption{Hamming loss on $\mathcal{D}^*_{\text{test}}$ for the different greedy policies, averaged over 20 independent runs. Bold font indicate that one or several algorithms are statistically better than the rest, according to a one-tailed paired difference t-test at significance level of 0.05 - as in \cite{swaminathan2015counterfactual}.} \label{tab:greedy_results} \end{table} \begin{figure}[!htp] \centering \begin{subfigure}{0.45\linewidth} \includegraphics[width=\linewidth]{rep_count_yeast} \caption{Yeast} \end{subfigure} \hfill \begin{subfigure}{0.45\linewidth} \includegraphics[width=\linewidth]{rep_count_scene} \caption{Scene} \end{subfigure} \caption{Impact of the replay count $\Delta$ on the expected Hamming loss. Results are average over 10 independent runs, that is 10 independent train/test split and bandit dataset creation.} \label{fig:rep_count} \end{figure} Another experiment carried in \cite{swaminathan2015counterfactual} focuses on the size of the bandit dataset $\mathcal{H}$. This quantity can be easily modulated by varying the \emph{replay count} $\Delta$ - the number of times we cycle through $\mathcal{D}^\star_{\text{train}}$ to create the logged feedback $\mH$. Figure~\ref{fig:rep_count} reports the expected Hamming loss of policies trained with the POEM, \firstalgo and \secondalgo algorithms for different value of $\Delta$, ranging from 1 to 256, and based on the Yeast and Scene datasets. Results are averaged over 10 independent runs. If for large values of $\Delta$ (that is large bandit dataset) all algorithms seem to confound, it stands out that for small bandit dataset size, the KL-based ones outperforms the POEM algorithm. \section{Introduction} \label{sec:intro} Learning how to act from historical data is a largely studied field in machine learning \cite{dudik2011doubly, li2015counterfactual, li2011unbiased, strehl2010learning}, spanning a wide range of applications where a system interacts with its environment (e.g search engines, ad-placement and recommender systems). Interactions are materialized by the actions taken by the system, themselves rewarded by a feedback measuring their relevance. Both quantities can be logged at little cost, and subsequently used to improve the performance of the learning system. The Batch Learning from Bandit Feedback \cite{ swaminathan2015batch, swaminathan2015counterfactual, swaminathan2015self} (BLBF) framework describes such a situation, where a \emph{contextual} decision making process must be improved based on the logged history of \emph{implicit} feedback observed only on a subset of actions. Counterfactual estimators \cite{bottou2013counterfactual} allow to forecast the performance of any system from the logs, as if it was taking the actions by itself. This enables the search for an optimal system, even with observations biased towards actions favored by the logger. A natural approach to carry out this search consists in favoring systems that select actions with high empirical counterfactual rewards. However, this initiative can be rather burdensome as it suffers a crucial caveat intimately linked with a phenomenon known as the optimizer's curse \cite{capen1971competitive, smith2006optimizer, thaler2012winner}. It indicates that sorting actions by their empirical reward average can be sub-optimal since the resulting expected \emph{post-decision surprise} is non-zero. In real life applications where the space of possible actions is often extremely large and where decisions are taken based on very low sample sizes, the consequence of this phenomenon can be dire and motivates the design of principled \emph{robust} solutions. As a solution for this Counterfactual Risk Minimization (CRM) problem, the authors of \cite{swaminathan2015batch} proposed a modified action selection process, penalizing behaviors resulting in high variance estimates. In this paper, we argue that another line of reasoning resides in using Distributional Robust Optimization (DRO) for the CRM. It has indeed proven to be a powerful tool both in decision theory \cite{esfahani2018data, blanchet2016, duchi2016} and the training of robust classifiers \cite{Xiao2018GeneratingAE, madry2017towards}. Under the DRO formulation, one treat the empirical distribution with skepticism and hence seek a solution that minimizes the worst-case expected cost over a family of distributions, described in terms of an uncertainty ball. Using distributionally robust optimization, one can thus control this post-decision surprise, critical to the counterfactual analysis. We motivate the use of DRO for the CRM problem with asymptotic guarantees and bring to light a formal link between the variance penalization solution of~\cite{swaminathan2015batch, swaminathan2015counterfactual} and a larger DRO problem for which the uncertainty set is defined with the chi-square divergence. Building from this, we propose the use of other uncertainty sets and introduce a KL-based formulation of the CRM problem. We develop a new algorithm for this objective and benchmark its performance on a variety of real-world datasets. We analyze its behavior and show that it outperforms existing state-of-the-art methods. The structure of the paper is the following: in Section~\ref{sec:blbf} we formally introduce the BLBF framework and the CRM problem. In Section~\ref{sec:dro} we present the DRO framework, motivate it for CRM and re-derive the POEM \cite{swaminathan2015batch} algorithm as one of its special cases and introduce a new CRM algorithm. In Section~\ref{sec:exp} we compare this new algorithm with state-of-the-art CRM algorithms on four public datasets and finally summarize our findings in Section~\ref{sec:conclusion}. \section{Conclusion} \label{sec:conclusion} We presented in this work a unified framework for counterfactual risk minimization based on the distributionally robust optimization of policies and motivated it by asymptotic guarantees available when the uncertainty measure is based on $\varphi$-divergences. We showed that this new framework generalizes existing solutions, like sample-variance penalized counterfactual risk minimization algorithms \cite{swaminathan2015batch, swaminathan2015counterfactual}. Our work therefore opens a new avenue for reasoning about counterfactual optimization with logged bandit feedback as we showed that a KL-divergence based formulation of the counterfactual DRO problem can lead to tractable and efficient algorithms for the CRM problem, outperforming state-of-the-art results on a collection of datasets. The authors of \cite{swaminathan2015counterfactual} also proposed a modification to the POEM algorithm that can be optimized at scale using stochastic gradient descent. Future work should therefore aim at developing stochastic optimization schemes for both \firstalgo and \secondalgo so that they could handle large datasets. From the perspective of experimental evaluation, measuring the impact of the DRO formulation on the doubly robust \cite{dudik2011doubly} and the self-normalized \cite{swaminathan2015self} estimators would further validate its relevance for real world problems. Finally, a more theoretical line of work could focus on proving finite-samples performance certificate guarantees for distributionally robust estimators based on coherent $\varphi$-divergences, further motivating their use for counterfactual risk minimization. \section{Related Work}\label{sec:related} We discuss in this paper the design of robustified counterfactual estimator for the clipped propensity risk \eqref{eq:ips_empirical_risk}, as in \cite{bottou2013counterfactual, swaminathan2015counterfactual, swaminathan2015batch} and showed its link with sample variance penalized objective. Other risk estimators have been proposed, namely by the authors of \cite{swaminathan2015self} who introduce the \emph{self-normalized} counterfactual risk to counter a phenomenon called \emph{propensity overfitting}.
{'timestamp': '2019-06-17T02:14:25', 'yymm': '1906', 'arxiv_id': '1906.06211', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06211'}
arxiv
\section*{Introduction} According to recent studies, a significant surge of mobile-connected devices per capita is expected to occur. Mobile network operators (MNOs) are anticipating that by the end of 2021 every person will own about 1.6 mobile-connected devices~\cite{1}. Triggered by their need to increase their network capacity, MNOs have embraced regional and national roaming, which allow for the sharing of resources. Moreover, the revenue of data roaming is expected to exceed US\$50 billion by 2021 \cite{2}. Roaming offers both challenges and opportunities for operators, in areas such as technical feasibility, associated cost, and commercial implications of introducing regional, national, and international roaming for voice and data services. Although researchers and the industry have identified several roaming frameworks through authentication, authorization and accounting, still there remain critical issues associated with roaming. They are as follows \cite{3}-\cite{6}:\\ \begin{itemize} \item \textbf{Trust:} The illegal access to information related to the roaming user is not addressed in the existing architectures, which is considered a serious breach of the user protection Act. Precisely, the visitor network operator (VNO) may have differing policies than what is accepted by the users in their home network operator (HNO). This requires re-accepting the roaming privacy terms before providing any services. \item \textbf{Security:} The roaming user must be authenticated with the VNO through the HNO before gaining access. Through this procedure, the illegal users are thwarted from accessing the network. Indeed, there are many proposed user authentications and key exchange protocols for roaming services, however, these protocols only focus on mutual authentication between the roaming user and the VNO. \item \textbf{Scalability:} There is an increased interest by both MNOs and governing bodies to find ways to share resources efficiently. However, the peer-to-peer service agreement which is exercised by the MNOs is quite inefficient. Considering \textit{n} number of MNOs seeking roaming agreements, this requires $n(n-1)/2$ agreements in total, and $(n - 1) $ agreements for each MNO. This makes it impractical for a universal roaming service. \end{itemize} The cellular roaming scenario can be addressed by a blockchain approach. Precisely, the roaming procedures can be described as several smart contracts between the roaming user, HNO, and VNO. In this article, the blockchain approach is explored for roaming models in future cellular networks ~\cite{7}. In particular, agreements between subscribers and home network operators (HNO) are logged through the agency of smart contracts on a blockchain, such as Ethereum~\cite{7}. These agreements associate a charging record with roaming (national and international) permissions and service instructions to be executed on an external database (i.e. the visitor network operator VNO). The motivating problem, which this article focuses on, is how to use blockchain to manage contracts between users and VNO, while maintaining the roaming agreements between MNOs. The proposed framework is based on developing trust between the parties to undergo trade, while maintaining full control over their respective user traffic in terms of quality-of-service (QoS), charging, and all the user's records (pre-approved privacy terms). Table \ref{Table 1} provides a comparison between the existing roaming model and the proposed blockchain based model. Further, the contributions of this paper can be summarized as follows: \begin{itemize} \item Proposing a blockchain architecture to the core mobile network. \item Introducing a mechanism that addresses the existing technological disadvantages of national and international roaming. \item Use Case: Evaluating the business implications of the European Union (EU) roaming charging model based on the blockchain from mobile operators' and users' point of views. \end{itemize} The rest of this article is organized as follows: A background on the blockchain and smart contracts is provided and then the existing roaming architecture is presented with an explanation of its functionality. Afterwards, the proposed blockchain-based architecture for roaming is presented with its corresponding challenges. Finally, the new architecture is evaluated using a use case of the EU, before the article is concluded. \newcommand{\cent}[1]{\begin{tabular}{l} #1 \end{tabular}} \begin{table*}[] \caption{\label{Table 1}Roaming in the existing 3GPP standards \cite{8} versus blockchain} \centering \begin{tabular {|c|p{0.32\linewidth} |p{0.32\linewidth}|} \hline \textbf{Aspect} & \multicolumn{1}{c|}{\textbf{Current 3GPP Standards}} & \multicolumn{1}{c|}{\textbf{Blockchain Approach}} \\ \hline Ecosystems requirements & \begin{tabular}{p{0.95\linewidth}}Needs commercial agreements including technical connections to support the IP signaling infrastructure \end{tabular}& \begin{tabular}{p{0.95\linewidth}}Needs predefined requirements to be implemented using an open-source software and commercial off-the-shelf (COTS) servers \end{tabular}\\ \hline Security & \begin{tabular}{p{0.95\linewidth}}IP border gateways and Diameter Edge Agents should be used for user paths and signaling can be utilized to securely connect roaming-related network interfaces to the roaming exchange network.\end{tabular} & \begin{tabular}{p{0.95\linewidth}}Offers a potentially more reliable network for roaming, free from security threats such as denial of service attacks that exist on public networks. \end{tabular}\\ \hline Performance and quality of experience (QoE)& \begin{tabular}{p{0.95\linewidth}}Partner operator networks cannot guarantee the same levels of operations and billing support, meaning the user experience can be negatively impacted.\end{tabular} & \begin{tabular}{p{0.95\linewidth}}Offers certainty about roaming data charges and avoid the potential for billshock when returning home. \end{tabular}\\ \hline Data and voice & \begin{tabular}{p{0.95\linewidth}}Requires managing multiple interfaces, routing calls (using circuit switch fallback or VoLTE), and allowing for redirections. \end{tabular} & \begin{tabular}{p{0.95\linewidth}}All data and voice calls are handled by the VNO and no routing to the HNO is required. \end{tabular}\\ \hline \end{tabular}% \end{table*} \section*{Background} The blockchain was originally designed to introduce a decentralized financial ledger ~\cite{9}. However, its paradigm was extended to provide several generalized frameworks for implementing decentralized compute resources~\cite{7}. In particular, the blockchain technology can be utilized to automate and track certain state transitions through the use of ``smart contracts"~\cite{10}. Thus, it allows alleviating the complexity of the modern charging control framework. Blockchain consists of three main elements: \begin{itemize} \item {\em Transaction}: all the valuable information (e.g. ownership) can act as a transaction to be recorded in the blockchain. Therefore, it is not restricted to trading information. \item {\em Block}: storage units to record transactions, which are created and broadcast by those users authorized by consensus mechanism. Also, each block is identified uniquely by its hash value, which is referenced by the block to come after it. \item {\em Chain}: the link between the blocks that creates a chain of blocks which is called a blockchain. The cost of attack and malicious modification increases exponentially as the blocks accumulate sequentially. \end{itemize} Furthermore, the {\em consensus mechanism} in the blockchain, plays an indispensable role by resolving the trust concern. This is achieved by identifying the authorized parties to insert the next block into the blockchain. Several consensus mechanisms have been proposed for different types of blockchains such as Proof of Work (PoW) and Proof of Stake (PoS): \begin{itemize} \item {\em PoW}: The core idea of PoW is the competition of computing power. In particular, the node performing the consensus mechanism (called {\em miner}) uses its computing resources for the hashing operation to compete for the right to generate the new block with bonuses. The winner is the first one who obtains a hash value lower than the announced target. \item {\em PoS}: The coin age is used in PoS blockchain to avoid the high computational complexity of the hash operation. The coin age of an unspent transaction output (i.e. destination address and the amount of coin) is equal to its value multiplied by the time period after it was created. In PoS, a higher coin age will lead to a higher probability for the node to win the right of creating a new block, and in turn, the coin age would be consumed (reset as zero) when the owner wins. \end{itemize} The blockchain concept has been widely adopted in various applications outside the financial ledger in the form of smart contracts. Anything expressible in digital form (e.g. computer program) can be seen as a smart contract. This computer program can use data from the blockchain records as inputs and then generate outputs. These outputs can be written to either the same blockchain or a separate one. In short, this computer program can digitally facilitate, verify, and enforce the contracts made between multiple parties on blockchain. Several attempts in the recent literature have used similar concepts for smart contracts, however, Ethereum~\cite{7} is considered the first full implementation of this concept. Table \ref{Table 2} provides a comparison between Ethereum and two other leading smart contract options. \begin{table*}[!htbp] \caption{\label{Table 2}Differences among the three major smart contracts options} \centering \begin{tabular}{|c|p{0.36\linewidth}|p{0.36\linewidth}|} \hline \textbf{Name} & \multicolumn{1}{c|}{\textbf{Description}} & \multicolumn{1}{c|}{\textbf{Advantages}} \\ \hline Corda R3 \cite{11} & \begin{tabular}{p{0.95\linewidth}}\\A private permissioned distributed ledger technology (DLT) where smart contracts are written in legal prose to mimic legally binding contracts. Participation is controlled by a trusted source and ledgers are private to those included on transactions.\end{tabular} & \begin{tabular}{p{0.95\linewidth}}\\1) Data is private to only those authorized to view it. \\ 2) Consensus is two-fold: TX validity and uniqueness/ double spend prevention. No PoW or PoS. \\ 3) No need for incentives. \\ 4) Provides higher TX/second. \\ 5) Smart contracts are associated with legal prose to account for high regulation environments.\end{tabular} \\ \hline Ethereum \cite{12} & \begin{tabular}{p{0.95\linewidth}}\\A public ledger blockchain that can be either permissioned or permissionless. Consensus requires PoW, thus, miners and incentives are required (ETHER/ Tokens). Allows anyone to build smart contracts on it \end{tabular} & \begin{tabular}{p{0.95\linewidth}}\\1) Can be either private or public. \\ 2) Records are anonymized. \\ 3) Rewards users with Ether or even customized reward schemes. \\ 4) Versatile in a wide variety of use cases.\end{tabular} \\ \hline Hyperledger Fabric \cite{13} & \begin{tabular}{p{0.95\linewidth}}\\Private permissioned blockchain with unique roles. Nodes can be either clients, orders or peers. Clients invoke transactions, peers maintain the ledger, and the orderer orders the new transactions. A special type of peer known as endorsers check the provision of signatures on a transaction \end{tabular} & \begin{tabular}{p{0.95\linewidth}}\\1) Data is private to only those 'subscribed' to a channel. \\ 2) Finer grain control over consensus. (\emph{i.e.} it can use Byzantine fault tolerance (BFT) consensus algorithm for faster performance and higher scalability than PoW or PoS blockchains). \\ 3) Can be used with or without incentive tokens.\end{tabular} \\ \hline \end{tabular}% \end{table*} \section*{Existing Roaming Models} The main objective of a mobile roaming service is to provide a service for any user with a valid international mobile subscriber identity (IMSI). In principle, subscribers of a specific service might go outside the pre-scheduled coverage zone by their home network operator (HNO). Consequently, an indirect connection for accessing such services is entailed via visitor network operators (VNOs). This is referred to as regional or national roaming which requires a service agreement to be set up between the home and visited networks. There are three parties involved in such a scenario: a roaming subscriber, the subscriber's HNO, and the VNO. In addition to the roaming service agreement, an essential authentication process concurring with the roaming registration procedures must be accomplished to ensure legitimate access to the visitor network resources and proper billing to roaming service-subscribed users~\cite{14}. One known key challenge introduced by the authentication process pertains to its latency. As defined by the IEEE standard ~\cite{15}, to maintain persistent connectivity for roaming users the hand-over latency has to be bounded by a delay constraint of 50 msec. Thus, highly efficient authentication mechanisms are needed especially with today’s highly dense cellular networks. Further, these aforementioned procedures should be done with all legacy trust mechanisms which require a complex and costly infrastructure to maintain. In general, there are two models of roaming as follows: \begin{enumerate} \item {\it International roaming}: It is a service through which a user of a given MNO (i.e. HNO) can obtain service from a MNO (i.e. VNO) of another country which is subject to inter-MNO agreements. \item {\it National roaming}: It is a service through which a user of a given MNO (i.e. HNO) can obtain service from an alternate MNO (i.e. VNO) of the same country, on a regional or everywhere basis. This roaming type depends on the agreement between the HNO of the requesting user and the VNO while being independent from user subscription arrangements. \end{enumerate} Regardless of the different interfaces between home and visited MNOs, based on the 3GPP model, these two roaming services utilize the same network architecture. Currently, the 3GPP standards support two roaming models as described in the following subsections~\cite{8} and shown in Fig. \ref{Drawing12}: \begin{enumerate} \item {\em Home-routed roaming architecture}: users' data traffic is serviced by their home network and gives the network operator more control over the users' traffic. \item {\em Local breakout architecture}: users' data is serviced by the network they are visiting. Therefore, it delivers more efficient routing in terms of bandwidth and latency~\cite{8}. \end{enumerate} \begin{figure*}[htbp] \centering {\includegraphics[width=1\textwidth,height=7cm]{./Pictures/Drawing5.pdf}} \caption{Block diagram of the home routed and local breakout roaming models.} \label{Drawing12} \end{figure*} \section*{Proposed Blockchain Roaming Model} In terms of roaming, there are many potential opportunities for operators to use the blockchain concept. In particular, by ensuring that proper agreements and users' records or users' transaction records are efficiently shared/maintained among fellow operators, it becomes possible to generate new revenues through innovative roaming service offerings. In addition, the deployment of such common architecture across operators will define a new universal roaming platform on which existing and new operators can better serve their clients everywhere with minimal to no changes in their existing infrastructure. Regardless of the roaming model chosen, a blockchain can enable a unified and flexible service offering for the roaming users. As shown in Fig. \ref{Drawing14}, this can be achieved among different core network operators using smart contracts among themselves and predefining their relative share of roaming users. Consequently, the user can register with any operator given that the operator is among the network sharing partners. The selection of an operator among those network sharing partners should be done manually beforehand to allow the accepting or rejecting of the roaming terms for the user (e.g. for roaming privacy and charging tariff). It is noteworthy that, the charging tariff in this system will be more transparent to the user than in the existing one. For example, if the cryptocurrency is used and the user pays half cryptocurrency in the HNO, it will be easier for the user to decide when the VNO offers the same service by quarter cryptocurrency. The specific agreement is represented by a state-object, which can be considered the main building block in this system. Below, are three main tools to achieve a blockchain roaming-based consensus: \begin{itemize} \item {\em Smart contract}: Logic which specifies constraints that ensure that the state transitions are valid according to the roaming agreement among the operators. \item {\em Transaction}: Showing the transition state-objects through a lifecycle of the roaming user. \item {\em Flow framework}: A component to simplify coordinating actions without a central controller among the sharing network partners. \end{itemize} \subsection{Blockchain System Model} The smart contracts can be referred to as a generalized state-machine of the blockchain based on cryptographically-secured transactions. Precisely, the blockchain paradigm is implementing decentralized compute resources whereas each MNO as a computing resource node can be considered as a state-machine entity. A state transition is determined to be valid by the MNO nodes encoding logic. This occurs for every newly generated state-machine and then uploaded onto the blockchain. In this blockchain, the data permissions (such as ownership and view) is presented as block content and shared by members of the network sharing partners. As a consequence, the blocks account a series of valid transactions. These transactions, utilize the previous block’s state to incrementally transform the state-machine into its ultimate state. All nodes engaged in the system receive this information through the PoW consensus algorithm. Furthermore, the PoW secures the state-machines’ state and transitioning logic against any changes. It is noteworthy that MNO nodes are capable to query the state-machines at any time and the obtained results would be accepted by the entire network. \begin{figure*}[htbp] \centering {\includegraphics[width=1\textwidth,height=8cm]{./Pictures/Drawing14.pdf}} \caption{Architecture of the proposed blockchain roaming model.} \label{Drawing14} \end{figure*} In the proposed system, the Ethereum's smart contracts are used to establish smart representations for the users roaming records which are shared among operators on the shared network. These contracts contain parameters such as ownership, permissions and data integrity which are recorded in the form of metadata. Also, all legitimate transactions are cryptographically signed in order to manage these records. Depending on these transactions, the contract's state-transition functions will be able to enforce data alteration and carry out any policies. These policies are represented computationally and can implement several rules which administer a specific roaming record. In particular, a policy can enforce the granting of roaming permissions after a separate transaction sent from the VNO verifies the user's acceptance. As shown in Fig.~\ref{Drawing14}, there are three types of contracts which are implemented in order to navigate the expected volume of record representations. The details for these contracts are provided in the following subsections. \subsubsection{Mobile Network Operator Contract (MNOC)} This contract is issued between two operators when a user attempts to register in a VNO. The MNOC defines a collection of data pointers that identify the records held by the HNO as well as the associated access permissions. Each of these data pointers consists of query string which retrieves the user data when executed on the HNO's database. The hash of the data subset is append to the query string to prevent any data alteration at the source. Also, more information such as the QoS attributes could be accessible to the VNOs through the HNO's database. It is noteworthy that, a design based on generic strings can simplify the interface with the different string queried database implementation for each operator on the network. \subsubsection{Cursory Contract (CC)} This contract depicts all the users' past and current interactions with any operator in the system by holding a reference list to all Mobile Network Operator Contracts. \begin{itemize} \item {\em Users}: their CC would be populated with references to all operators they have interacted with. \item {\em HNOs}: would have references to their users and all VNOs with which their users have established authorized data sharing. \end{itemize} The CC goes on the distributed network to add functionality such as backup, restoring, and enable user notifications. Also, to further establish a user acceptance, a status variable is stored with each roaming relationship to indicate whether this relationship is recently formed or awaiting updates. The HNO has the capacity to set a roaming status in their users' CC while updating records or while creating a new roaming activity. Hence, the user can poll their CC and be notified in the case a new roaming activity is suggested which is crucial in enhancing the QoE through providing additional national roaming options. Ultimately, users can accept or reject the suggested roaming activity. \subsubsection{Registrar Contract} Users and operators identification (ID) strings are mapped to their Ethereum address identity with this global contract. These strings are equivalent to a public key and allow the users to use a unique serial number ( \emph{i.e.,} the Integrated Circuit Card Identifier (ICCID)). In general, if policies are coded into this contract they regulate both new identities being registered and changes in the mapping of existing ones. Consequently, identity registration can be limited to participant operators. Furthermore, identity strings are mapped to an address located on the blockchain by this contract. \section*{System Description} Agreements between subscribers and HNO are logged through the agency of smart contracts on the Ethereum blockchain. These agreements associate a charging record with roaming permissions and data retrieval instructions for execution on an external database (i.e. VNO). Once the agreement is settled, the remaining step for the MNO to allow roaming is having the HNO's permission to access the subscriber’s charging record. Any of the MNOs on the network can be designated as a VNO by obtaining access to the charging record of the subscriber. Consequently, a temporary agreement will be issued between the VNO, HNO, and U. This new temporary agreement will allow the VNO to make additions to the subscriber record. This operation will include accepting the new additional terms from the subscriber and notifying the HNO. Charging between the MNOs is done inside the network using their own cryptocurrency. Furthermore, implementing a universal charging system means applying a conversion rate between subscribers' currency and the MNO cryptocurrency, which the subscriber will be notified of by the VNO. Consequently, the subscriber will have the option to either accept or reject the additional temporary terms and charges imposed by the VNO. This scenario will be helpful in the case of international roaming, however, in the case of regional or national roaming charges will be excluded in the temporary terms but handled between the MNOs. As shown in Fig. \ref{Drawing14}, the proposed system orchestration is based on four software components which create a coherent and distributed system as follows: \begin{itemize} \item {\em Backend Library}: Facilitates the system's operations by abstracting the communications with the blockchain. \item {\em Ethereum Client}: Implements the required functionality to join the blockchain network such as encoding and sending transactions, maintaining a local copy of the blockchain, and connecting to the P2P network. \item {\em Gatekeeper}: This is a database which implements an off-chain access interface to the MNO local database as well as listening to query requests from other MNOs by running a server. \item {\em Charging System}: It renders data from a local database for reviewing, and presents a notification to the roaming user to either accept or reject the roaming terms. \end{itemize} By implementing the modular interoperability protocol, any new operator can participate in the network, as the previous section has outlined. Also, by following the CC, missing data can be recovered from the network on demand. \section*{Model and Performance Analysis } Since 2017, the European parliament enforced free roaming in order to achieve a unified digital market. In fact, this goal has had an impact on both users and MNOs through the pricing strategies and transit payments between MNOs in different EU countries. As a consequence, the model in ~\cite{16} is adopted to analyze the depending parameters from the users, VMOs and HNOs perspective. This can be considered a practical example for the proposed framework with the ultimate goal of having a global digital market based on the Blockchain approach. From the MNO's perspective, revenue is the performance metric to optimize, which can be expressed in a high-level, for country \textit{i}, as: \begin{equation}\label{equ:Rev} \begin{array}{l} {R_i} = \,{\rm{domestic\, usage\, revenue\, for\, }}MN{O_i}\,{\rm{ + }}\\ {\rm{\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, roaming\, usage\, revenue\, for\, }}MN{O_i}\,\,{\rm{ + }}\\ {\rm{\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, transit\, usage\, revenue\, for\, }}MN{O_i}\,\,\,\,\,\,{\rm{ - }}\\ {\rm{\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, transit\, usage\, cost\, incurred\, by\, }}MN{O_i}{\rm{ }} \end{array} \end{equation} where the four summands reflect three revenue components and one cost component. To simplify the understanding of \eqref{equ:Rev}, each component is defined as follows: \begin{itemize} \item The \textbf{domestic usage revenue} is the flat-rate subscription payment paid by domestic customers to their HNO for domestic use. This revenue component is proportional to ${m_i}\,{p_i}\,\frac{1}{{{\lambda _i}\,{{\overline \theta }_i}}}$, where $m_i$ is the total number of potential users in country \textit{i}, $p_i$ is the flat-rate subscription price for the domestic service of the MNO in country \textit{i}, $\lambda_i$ is the wealth parameter of country $i$ and defined as the rate of the (assumed) exponential distribution for the users' willingness-to-pay, $\theta_i$ (a measure in monetary units per month) in country $i$. Finally, $\overline \theta_i$ is the minimum willingness-to-pay value to consider a user as a potential subscriber with the MNO in $i$. Given the assumed exponential distribution of $\theta_i$, the country's wealth parameter $\lambda_i$ is the reciprocal of the country's average wealth. \item The \textbf{roaming usage revenue} is the payments from domestic users to their HNO for roaming use. This revenue component is proportional to $m_i c_i\,\frac{1}{{{\lambda _i}\,{\overline \theta_i}}}$, where $c_i$ is the fixed per-volume price for the roaming service of the MNO in country \textit{i}. \item The \textbf{transit usage revenue} is the payments (transit fees) to MNO$_i$ for the roaming costs incurred by foreign roaming users for having their traffic traversing MNO$_i$'s infrastructure. This revenue component is proportional to ${m_j}\,{t_i}\,\frac{1}{{{\lambda _j}\,{{\overline \theta }_j}}},\,\forall j \ne i$, where $t_i$ is the transit price decided by $\rm{MNO_i}$ to charge counterpart MNOs in other countries for using its network infrastructure. \item An Alternative to transit usage revenue is the \textbf{transit usage cost} which is the payment from $\rm{MNO_i}$ for the roaming costs incurred by their domestic customers for roaming on foreign networks. This cost component is proportional to ${m_i}\,{t_j}\,\frac{1}{{{\lambda _i}\,{{\overline \theta }_i}}},\,\forall j \ne i$. \end{itemize} Conversely, from the users' perspective, the consumer surplus (CS) is used to measure the aggregated satisfaction level of all subscribed users, across all countries, and can be expressed as: \begin{align}\label{equ:CS} \begin{array}{l} {\rm{CS}} = \,{\rm{net\, utility\, for\, domestic\, usage\, + }}\\ {\rm{\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,net\, utility\, for\, roaming\, usage}} \end{array} \end{align} where both summands represent, in order from left, the users' satisfaction level (and essentially the users' subscription decision) about the MNO's flat subscription price for the domestic service and the fixed per-volume price for the roaming service, respectively. In particular, the utility for domestic usage is equal to $\theta _i{-}p_i$ whereas the utility for roaming usage is proportional to ${({\theta _i} - {c_i})^2}$. The values of $p_i$ and $c_i$ are selected to maximize the operator's revenue expressed in (\ref{equ:Rev}), whereas $t_i$ is decided by two possible schemes. The first scheme involves leaving the transit price decision to the regulator to maximize the CS. The authors in~\cite{16} have concluded that zero transit prices (i.e. $t_i$= 0, $\forall i$) is likely to be the optimal scenario where the CS is maximized. The second scheme, alternatively, finds the transit price at which a Nash equilibrium for a non-cooperative game is reached between MNOs. The performance comparison between the traditional roaming system and the proposed blockchain-based roaming system is conducted by evaluating equations (\ref{equ:Rev}) and (\ref{equ:CS}) for both systems. On the one hand, for the traditional roaming system, both equations are analyzed for the paid roaming and free transit case as in \cite{16} (i.e. the transit revenue and cost components in (\ref{equ:Rev}) are equal to 0). On the other hand, the evaluation for both equations in the case of our proposed system is discussed in the following two paragraphs while explaining its relative performance. To ensure fair comparison between both systems, we set the pricing model (i.e. explained in (\ref{equ:Rev}) and (\ref{equ:CS})) parameters to similar values as taken in \cite{16} (i.e. $m_1= 1$, $m_2= 2$ and $\lambda_2= 1$). As such, the impact of the wealth parameter for operator 1 (i.e. $\lambda_1$), as well as the rest of the roaming model parameters, on the operators' revenue and consumer surplus is depicted in Tables \ref{fig:op_rev} and \ref{fig:cs}, respectively. In Table \ref{fig:op_rev}, we notice that increasing $\lambda_1$ the operator's revenue for MNO$_1$, $R_1$, becomes negatively impacted in case of both traditional and proposed roaming models. This pertains to the fact that the smaller the average wealth the smaller the number of potential subscribers for the MNO service. In addition, MNO$_1$ is able to gain higher revenues when implementing the proposed blockchain-based model than in the case of traditional roaming. This can be justified by the higher roaming revenue gained from MNO$_2$ subscribers roaming to MNO$_1$. In other words, in the case of traditional roaming, the roaming revenue for MNO$_1$ comes from their own subscribers which decreases by increasing $\lambda_1$. However, in the case of blockchain roaming, the roaming revenue for MNO$_1$ comes from MNO$_2$ customers roaming to MNO$_1$. keeping in mind that $\lambda_2$ is constant and equal to 1 and $m_2>m_1$, hence, the roaming revenue from MNO$_2$ roaming subscribers (in case of blockchain roaming) is relatively greater than that from MNO$_1$ roaming subscribers (in case of traditional roaming) with increasing $\lambda_1$. In essence, in the blockchain-based roaming system, the roaming process is highly flexible such that the user seamlessly receives the required service from the VNO by directly paying for it under the smart-contract authorization system without intervention from the HNO. On the other hand, the revenue for the traditional roaming MNO$_2$ is not affected by the average wealth in country 1. However, the proposed blockchain roaming improves MNO$_2$ revenue only when $\lambda_1<\lambda_2$ (i.e. at $\lambda_1= 0.5$) which implies that MNO$_1$ subscribers roaming to MNO$_2$ are wealthier than MNO$_2$ domestic subscribers and would contribute more to the roaming usage revenue for MNO$_2$ (as illustrated in (\ref{equ:Rev})) compared to the traditional roaming case. In general, improving $R_1$ on the expense of $R_2$ when implementing the proposed blockchain roaming system is consistent with the relative difference between $\lambda_1$ and $\lambda_2$. \begin{table}[ht] \caption{\label{fig:op_rev} Operator's revenue analysis} \centering \begin{tabular}{|p{1.4cm}|p{1cm}|p{1cm}|p{1cm}|p{1cm}|p{1cm}|} \hline \multicolumn{6}{|c|}{\includegraphics[scale=0.33]{./Pictures/fig5_BC.pdf}} \\ \hline \textbf{Parameter} & $p_i$ & $c_i$ & $t_i$ & $\lambda_i$ & $\theta_i$\\ [1ex] \hline \textbf{Operator's revenue} & Increases & Increases & Incr./Decr. & Decreases & Increases \\ \hline \end{tabular} \end{table} From the users' perspective, the effect of $\lambda_1$ on the consumer surplus is illustrated in Table \ref{fig:cs}. The results illustrate that the CS drops with increasing $\lambda_1$ due to the fact that the larger the $\lambda_1$ the larger the density of small values for $\theta_1$, and hence, inversely affects the CS. As highlighted in the previous paragraph, due to the flexible nature of the proposed blockchain-based roaming which allows roaming subscribers to pay for the service on-the-go with the selected VNO, the traditional roaming charge for the HNO drops to 0. With this in mind, the roaming usage utility in (\ref{equ:CS}) is maximized, and hence, the aggregated CS as depicted in Table \ref{fig:cs}. \begin{table}[ht] \caption{\label{fig:cs} Consumer surplus analysis} \centering \begin{tabular}{|p{1.4cm}|p{1cm}|p{1cm}|p{1cm}|p{1cm}|p{1cm}|} \hline \multicolumn{6}{|c|}{\includegraphics[scale=0.33]{./Pictures/fig6_BC.pdf}} \\ \hline \textbf{Parameter} & $p_i$ & $c_i$ & $t_i$ & $\lambda_i$ & $\theta_i$\\ [1ex] \hline \textbf{Consumer surplus} & Decreases & Decreases & Decreases & Decreases & Increases \\ \hline \end{tabular} \end{table} \section*{Conclusion and Future Directions} The blockchain vision for telecommunication networks enables multiple applications and services to run across a common layer of identity, business logic, and governance. Operators can deploy one or multiple blockchain infrastructures which can transact for various purposes while maintaining fortified privacy. In this article, the concept of blockchain and the benefits of integrating it into the Roaming systems have been presented. The main ideas and basic roaming procedures based on smart contacts have been illustrated. Further, a comparison among the state-of-the-art smart contract-based distributed ledgers have been provided in terms of their main characteristics. A case study for the proposed model has also been presented. From the operators' perspective, the MNOs will still be able to achieve a reasonable revenue while providing ubiquitous connectivity for numerous mobile devices with minimal changes in their infrastructure which will drastically reduce the OPEX. From the users' perspective, the user will be able to obtain the maximum QoE through the capability of choosing the service and accepting the cost. \bibliographystyle{IEEEtran}
{'timestamp': '2019-06-18T02:01:04', 'yymm': '1906', 'arxiv_id': '1906.06350', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06350'}
arxiv
\section{Introduction} Recent years have witnessed a growing academic interest in the field of blockchain technology, which is the cornerstone behind cryptocurrencies such as Bitcoin \cite{nakamoto2008bitcoin} and Ethereum \cite{wood2014ethereum}. This technology has been envisioned as a trustless and decentralized platform on which developers are building various applications beyond cryptocurrencies. However, today's public blockchains (often referred to as permissionless blockchains, such as Bitcoin and Ethereum) are hindered by many challenges for web-scale adoption. One of the most fundamental challenges is scalability, which is caused by blockchain's nature of decentralization. In a permissionless blockchain, every node validates every transaction, which consequently imposes a fundamental limit on the throughput (i.e., the number of transactions that can be processed per second) \cite{croman2016scaling}. In addition, since every single move of the execution of a transaction consumes resources (e.g., storage, bandwidth, computation, etc.) of the network, the fees charged by miners could be expensive. A common approach to scale permissionless blockchains is to enact transactions ``off-chain'', i.e. execute transactions outside the blockchain. Off-chain solutions consider the existing blockchains as the base layer (referred to as ``layer 1''), or the ``mainchain'', and arbitrary transaction functions as the upper layer (referred to as ``layer 2''). In order to transfer from layer 1 to layer 2, participants are required to deposit some funds on-chain so that the money will be frozen on the mainchain and be ``recreated'' off-chain. After that, they update their off-chain status by performing arbitrary transactions following the off-chain protocols. Malicious behaviors could happen in off-chain networks, but when this situation happens, participants could complain to the mainchain by providing justifications which are verified by the mainchain. Therefore, the mainchain plays the role of a ``judge'' by running smart contracts which bridge the mainchain and the upper protocol. By minimizing the use of the underlying blockchain itself, this off-chain approach can achieve ``scale-out'' throughput as the throughput will increase as the size of the network grows \cite{Ren_2018}. \subsection{Motivation} One off-chain proposal is called payment channel networks (PCN) \cite{poon2016bitcoin} which enable two users to perform unlimited transactions off-chain only touching the mainchain during the deposit and withdrawal process. In a nutshell, two parties open a payment channel by making some deposits to the mainchain and then they can do off-chain transactions without touching the mainchain until they want to close the channel. Furthermore, even if two users have no direct payment channel established, they can still pay each other through a set of intermediaries. While numerous contributions have been made to improve the performance of PCN \cite{miller2017sprites}\cite{perun2019}\cite{revive2017}, they still face multiple challenges such as costly routing, expensive channel setup and rebalance requirement. Due to these obstacles, PCNs are mainly used in peer-to-peer micropayment scenarios. In this paper, we focus on a different approach called sidechains \cite{back2014enabling}, which has much wider application scenarios because it allows any participant to build a sidechain with specific purpose. Sidechains also share a deposit-withdraw scheme like PCN, but instead of building a channel between two parties, a sidechain is a new blockchain with its own rules and two-way pegged\footnote{Two-way peg is a cross-chain mechanism where assets are transferred between two blockchains at a fixed or deterministic exchange rate \cite{back2014enabling}} with the mainchain. Another difference to PCN is that in order to guarantee the correctness of the sidechain, block proposers make commitments to the mainchain periodically, enforcing the state of the sidechain in the mainchain \cite{Eberhardt}. To summarize, a sidechain protocol is essentially a compression mechanism that periodically executes transactions, persists state, and anchors it in the mainchain, thereby achieving scale-out throughput. Plasma \cite{poon2017plasma} and NOCUST \cite{rami2018nocust} are two of the most promising sidechain approaches which employ the smart contract technology to achieve two-way peg. They allow a centralized operator to manage the sidechain (or ``commit-chain'' in NOCUST) while guaranteeing that users always retain control over their assets. On one hand, they can achieve the same magnitude of throughput as centralized fiat payment processing systems, such as MasterCard and Visa. On the other hand, they ensure that end-users can always exit the sidechain if the operator is compromised as long as the mainchain is secure. Despite the above two clear advantages, sidechain-based solutions are still in its infancy, facing several limitations. \setitemize{leftmargin=*} \begin{itemize} \item \textit{A failure-prone operator.} Although the operator can be trustless, its failure or misbehavior still has critical impact on user experience. In particular, once the operator is compromised, so is the sidechain. Users have to perform mass-exit in order to keep their assets safe, which will probably cause congestion in the mainchain. \item \textit{Withholding attack.} This attack, originated from \textit{Selfish Mining}, has emerged as a critical attack against PoW-based blockchains \cite{7728010} \cite{Eyal:2018:MEB:3234519.3212998} \cite{niu2019selfish}, where selfish miners withhold blocks for unfair mining competition. In the sidechain context, the withholding attack consists of the block proposer forging an arbitrary block, not propagating it to other nodes, but making the commitment to the mainchain. From the mainchain's perspective, the committed block is always accepted since it does not verify the correctness of its content. Current solutions include either instructing the users to exit the sidechain or forcing the proposer providing the data through the smart contract. Both two solutions require users to be online and the latter will involve multiple on-chain transactions. \item \textit{Online requirement.} Existing off-chain proposals, including sidechains and PCN, require the users to be online to receive the payment or to verify the block at the end of each block time for trustless operation. Otherwise, sidechain assets might be stolen. This requirement is impractical to fulfill. There are some potential solutions such as ``watch towers'' \cite{mccorry2018pisa}, where users could outsource their data to a trusted third party. However, this introduces additional trust assumptions and costs. \end{itemize} \subsection{Our Solutions and Contributions} In order to address the above issues, we propose to design new consensus algorithms for sidechains. Although some existing work \cite{croman2016scaling}\cite{poon2017plasma} has discussed the possibility of consensus mechanisms for sidechain (e.g., PoS, PoA, PBFT, etc.), a consensus protocol specially designed for sidechains with formal security proof is still missing in the literature. To fill this research gap, we present Vulcan: a low overhead, high efficiency, security provable sidechain protocol. To the best of our knowledge, Vulcan is the first formal specification of a sidechain-based protocol with high performance and rigorous security proof. More specifically, Vulcan\footnote{Vulcan is a fictional planet of the \textit{Star Trek} universe. Vulcans, residents of that planet, are noted for their attempt to live by logic and reason with as little interference from emotion as possible.} (i) allows organizations to run separate sidechains and provides various off-chain services to their end-users, and (ii) gives a guarantee to clients that their assets on sidechains are always safe without online requirement and they can always exit with their coins back to the mainchain. The key idea behind Vulcan is that we can leverage mainchain security properties in the design of sidechain consensus, leading to high-performance protocols which are previously impossible. Our contributions can be summarized as follows: \textbf{A BFT-based consensus algorithm specially designed for sidechain.} We developed a new algorithm to solve the well-known Byzantine consensus problem \cite{Lamport:1982:BGP:357172.357176} in the sidechain context, where the creation of a block is stricted to a fixed set of $n$ authority nodes, called \textit{validators} in our protocol, among which a maximum of $f<\frac{n}{2}$ can be Byzantine. To avoid inconsistency, each committed block is enforced on the mainchain through smart contracts and considered as a \textit{checkpoint}. A checkpoint is only considered valid when it is approved by more than half validators. Thus we adopt the \textit{aggregate signature} to assemble multiple signatures, i.e., approvals, from different validators into a single signature. We also employ a ``lazy-challenge'' mechanism to delay the verification of the checkpoint until some party complains. Since each pending checkpoint can be viewed on the mainchain, every party can run the verification locally and request a challenge when they find the checkpoint is invalid. A validator will be removed out of the committee if it is successfully challenged. Therefore, in order to stay in the committee, a block proposer has to reveal the content of the block to other validators for approval, which prevents withholding attack. \textbf{Safe Cross-Chain Transfer.} Apart from consensus algorithms, Vulcan supports safe cross-chain transfer. Users can easily issue a forward transfer (from mainchain to sidechain) to join the sidechain since every party can verify on-chain transactions. However, it becomes complicated vice versa because of the opacity of off-chain transactions. In Vulcan, the balances of each user are constructed in a Merkle Patricia Trie (MPT) with the address as the \textit{key} and the balance as the \textit{value}. Over a block time, the balances are enforced by the latest checkpoint, which includes the root hash of the MPT. Our protocol ensures that as long as the security assumption ($n\geq2f+1$) holds, users can always withdrawal/exit from the latest checkpoint by submitting the correct merkle path to the smart contract without online requirement. \textbf{Security Model and Formal Proof.} To be able to rigorously analyze the security properties of our protocol, we employ a general-purpose definitional framework called the Universally Composable Security (UCS) framework by Canetti \cite{canetti2001universally}. By using the UCS framework, we formally define the security properties of our protocol and provide detailed proof. \subsection{Outline} Section \ref{sec:system-model} presents the system model. Section \ref{sec:system-overview} describes the protocol in a high level. Section \ref{sec:security} gives a formal definition of Vulcan under UCS model. Section \ref{sec:implementation} evaluates the performance. Section \ref{sec:related-work} discusses the related work and Section \ref{sec:conclusion} concludes this paper. \section{System Model} \label{sec:system-model} In this section we introduce basic notations, key elements, communication model, adversary model and assumptions used in our protocol. \subsection{Main Elements} Vulcan involves the following roles: \textbf{Mainchain}: We introduce a tamper-proof and smart contract enabled ledger (e.g., Ethereum) as our mainchain denoted by $\mathbb{MC}$. In our protocol, $\mathbb{MC}$ serves as the base layer, which keeps all the data including smart contracts, accounts, balances and transactions. \textbf{Smart Contract}: A smart contract is a piece of code deployed on $\mathbb{MC}$ acting as the bridge between $\mathbb{MC}$ and the sidechain (denoted by $\mathbb{SC}$) and providing dispute-solving services. We use $\mathbb{C}$ to denote a set of contracts designated to a specific $\mathbb{SC}$. In order to meet specific requirements of different sidechains, each sidechain has a set of exclusive smart contracts containing a group of functions. \textbf{Validators}: A set of validators $\mathcal{V}=\{V_1, V_2,...,V_n\}$ run validations and consensus algorithms in $\mathbb{SC}$, where $n$ is the number of validators. Each of them is identified by a unique pair of public/private key in the sidechain network. Validators take turns to propose blocks, one block at an epoch. During each epoch, the validator who is responsible to propose the block is called the \textit{leader}, while the rest are called \textit{followers}. The order of rotation is prefixed. \textbf{Clients}: A set of clients $\mathcal{C}=\{C_1, C_2,...,C_m\}$ are actual users of $\mathbb{SC}$, where $m$ is the number of clients inside $\mathbb{SC}$ network. They can share the same public/private key pair between $\mathbb{MC}$ and $\mathbb{SC}$. Clients issue transactions directly to validators. In order to increase the success rate of acceptance, clients can multicast transactions to a group of validators they trust. \subsection{Communication Model} We assume our protocol under a synchronous communication network, where there is a known upper bound on the message transmission delay. We assume all parties have access to $\mathbb{MC}$ and $\mathbb{C}$, which are always available. All the transactions sent to $\mathbb{MC}$ and $\mathbb{C}$ will be finalized within time $\Delta$. We assume parties can instantaneously acquire the status of $\mathbb{MC}$ so that they are always aware of the current epoch of the protocol. \subsection{Adversary Model} We consider the adversary can compromise all the clients and $f$ validators, where $f \leq \frac{n-1}{2}$. Faulty parties may deviate from their normal behavior in arbitrary ways, e.g., hardware/software crash, nonsensical read and write to $\mathbb{MC}$, colluding with each other to cheat honest parties, etc. However, we assume they do not have enough computation power and money to compromise $\mathbb{MC}$. We also assume that all messages are signed by their individual senders and adversaries can not break collision resistant hashes and signatures used both in $\mathbb{MC}$ and $\mathbb{SC}$. \subsection{Cryptografic Primitives} Our protocol utilizes \textit{aggregate signatures} which enables distributed signing among $n$ participants $\{P_1,P_2,...,P_n\}$. An aggregate signature scheme consists of four algorithms: \textsf{KeyGen}, \textsf{Sign}, \textsf{Combine}, and \textsf{Verify}. The former two algorithms are the same as the standard signature scheme. Algorithm \textsf{Combine} takes a vector of $n$ triples ($pk_i$, $m_i$, $\sigma_i$) as input, where $pk_i$ is the public-key for $C_i$, $m_i$ is the message, and $\sigma_i$ is the signature signed on $m_i$. The output is a single aggregate signature $QA$, whose length is the same as a signature on a single message. Algorithm \textsf{Verify} takes $n$ pairs ($pk_i$, $m_i$) and the aggregate signature $QA$ as input and outputs ``True'' only if $\sigma$ was generated as an aggregate of $n$ valid signatures. \section{System Overview} \label{sec:system-overview} In this section, we present Vulcan from a high-level overview. Analogous to Ethereum \cite{wood2014ethereum}, Vulcan is also an account-based protocol, where each participant has an account referring to their properties (e.g., balance, non-fungible tokens, etc.). Therefore, the whole protocol can also be viewed as a state machine. For simplicity, in this paper, the state only refers to account balances. The protocol begins with a genesis state and proceeds by executing transactions periodically until it terminates. The sidechain$\mathbb{SC}$ is set up by $\mathcal{V}$ deploying $\mathbb{C}$ on $\mathbb{MC}$, and any validator can be the owner. The owner of $\mathbb{C}$ sets an endpoint in $\mathbb{C}$ indicating when $\mathbb{SC}$ will be closed. When it passes the endpoint, the protocol will halt, after which users can exit with the balance according to the latest agreed checkpoint. In Vulcan, we rely on a fixed set of validators to maintain $\mathbb{SC}$. After $\mathbb{C}$ is deployed on $\mathbb{MC}$, $\mathbb{C}$ will keep the public key as the id of each validator for future verification. Validators collect signed transactions from clients, execute them, and package them along with the outcome into a block during each epoch. The leader of current epoch should propose that block by broadcasting it to followers. If the leader gets majority of votes after validators running the mPoA consensus algorithm (cf. Sec. \ref{sec:poa}), then he commits the digest of the block header, along with a \textit{quorum certificate} (QC), which is an aggregate of approvals form followers, to $\mathbb{MC}$ via an online transaction to enforce the state of the epoch. A QC is valid only if it is an aggregate of more than $f$ signatures on the same hash of the block header from different validators (including the leader itself). Meanwhile, the validators publish the whole content of that block for every parties to query through an API. A Byzantine leader might propose different blocks at a time and send them to different followers. In this case, the leader cannot cause a fork for two reasons: one leader can only commit once during its tenure and only one block can gain majority votes since non-faulty validators will not vote for two different blocks at a time. A validator ignores the inconsistency in the committed block and the received block as long as the former gains a valid QC. Another case is that a Byzantine leader might commit a faulty block without revealing it to the followers, performing withholding attack. To achieve this attack, the leader has to obtain an approval from at least one honest follower (assuming other $f$ validators are compromised) to generate a valid QC. However, this cannot happen because an honest validator will not sign an incorrect block. As for clients, they can always withdraw certain amount of money or exit with their assets from the latest checkpoint. Fig. \ref{fig:overview} shows a system overview of Vulcan. \begin{figure} \begin{center} \includegraphics[width=1.0\linewidth]{images/overview.pdf} \caption{An overview of transaction flow in Vulcan.} \label{fig:overview} \end{center} \end{figure} \subsection{Epochs} \label{sec:epoch} Vulcan proceeds in epochs. An epoch is a slot of time during which a block is generated from transaction collection to the acceptance by $\mathbb{C}$. Epochs are numbered consecutively. Let $e$ denote as the epoch number and $l$ as the index of the leader of the corresponding epoch such that $l=e\mod{|n|}$. Note that a view-change (a new leader to collect transactions and propose it to followers for a new epoch) happens no matter the epoch succeeds or not (more details are described in Sec. \ref{sec:poa}). Each \text{epoch} has four terms described as follows: \begin{itemize} \item \textit{Collecting term.} Validators collect transactions from clients during this term. This term starts at the beginning of the \textit{committing term} and ends right after the success of last epoch. \item \textit{Proposing term.} At the beginning of this term, the leader $l$ packages the collected transactions from the last term into a block and proposes it by broadcasting the block to the followers. If the proposal fails (the leader receives less than $f$ approvals within a constant time), this round is abandoned, and a new round (from collecting term) will begin. Otherwise, the epoch proceeds to the next term. \item \textit{Committing term.} This term begins by the leader committing the block to $\mathbb{C}$. After the commitment being confirmed by $\mathbb{MC}$, the epoch proceeds to the pending term. \item \textit{Pending term.} During this term, every participant from $\mathcal{V}$ and $\mathcal{C}$ can send \textit{complaints} against the pending commitment, and it is the only term during which $\mathbb{C}$ handles \textit{withdrawal/exit} requests from clients. If no messages are received during this term, then the epoch ends and the pending checkpoint is finalized. Otherwise, the duration of this term will be increased until the dispute is resolved (after a certain number of on-chain confirmations). If the challenge is successful, the current epoch will restart. Otherwise the protocol proceeds to epoch $e+1$. \end{itemize} Note that two epochs overlap each other to reduce latency without causing any conflicts. An epoch starts after the end of the proposing term of the previous one. On the other hand, the proposing term of the next epoch starts after the previous epoch ends. An example of how each epoch proceeds is depicted in Fig. \ref{fig:epoch}. \textit{Epoch} 1 shows a normal epoch, which ends in one round, no malicious events being observed. \textit{Epoch} 2 starts at the beginning of the committing term of \textit{epoch 1}, and the proposing term of \textit{epoch} 2 starts after \textit{epoch 1} ends. We can observe that the pending term of \textit{epoch} 2 lasts longer than that of \textit{epoch} 1. This is because the leader might be compromised and honest followers successfully ``challenge'' him. Hence, following that is a new round of \textit{epoch} 2. Due to the long duration of \textit{epoch} 2, the collecting term of \textit{epoch} 3 is sustaining until the \textit{epoch} 2 ends. However, the first round of \textit{epoch} 3 fails at the proposing term, so another round comes instead. Then \textit{epoch} 4 starts at the beginning of the committing term of \textit{epoch 3} and survives 4 terms in one round. We can learn from the above example that if every party is well-behaved, each epoch will only take one round to finish. Otherwise, it might take several rounds to finish. To ensure liveness, honest validators will vote out the leader if the epoch can not finish within certain rounds. We discourage malicious behaviors by instructing validators to deposit some money as collateral. If the leader is successfully challenged by more than $f$ validators, it will be removed from the committee with monetary punishment. The design of punishment mechanism is the scope of this paper. \begin{figure} \begin{center} \includegraphics[width=1.0\linewidth]{images/epoch.pdf} \caption{An example of how epochs proceed} \label{fig:epoch} \end{center} \end{figure} \subsection{BFT-based Consensus} \label{sec:poa} Vulcan adopts a BFT-based algorithm for validators to reach consensus. Other than tolerate up to $\frac{n-1}{3}$ Byzantine nodes, Vulcan can ensure security and liveness with a maximum of $\frac{n-1}{2}$ Byzantine nodes. Even though all of the validators are compromised (the protocol might halt unexpectedly), Vulcan still guarantees that funds in $\mathbb{SC}$ are safe under conditions that clients come online at least once per epoch to verify their balance (cf. Sec. \ref{sec:interactive-exit}). In Vulcan, we follow a \textit{leader rotation} procedure which has been widely used to fairly distribute the responsibility of block production among validators \cite{soton411996}\cite{8123568}. The order of validators taking the lead is predetermined in $\mathbb{C}$ before deployed. We argue that it is nonsignificant how this order is decided. For example, we could follow the order of validators joining $\mathbb{SC}$. Once $\mathbb{C}$ is deployed, the order is settled unless some validators are voted out for Byzantine behaviors. The owner of $\mathbb{C}$ also determines a \textit{validity time} indicating when $\mathbb{SC}$ is closed. When it passes the validity time, the protocol will halt waiting for clients to exit from the latest checkpoint. Then the funds will be fairly distributed and $\mathbb{SC}$ will terminate. The algorithm proceeds in epochs which are identified in Fig. \ref{fig:epoch}. Every party in the sidechain has a global view of who is the leader of the current epoch by querying $\mathbb{C}$, and the leader will be automatically passed to the next one at the end of each epoch. \begin{algorithm} \caption{The consensus algorithm at $v_i$}\label{mpoa} \begin{algorithmic}[1] \State \textbf{Global State}: \State\hspace{\algorithmicindent} $\mathcal{V}=\{v_1,v_2,...,v_n\}$: the set of validators identified by their public keys \State\hspace{\algorithmicindent} \texttt{current\_leader}: the public key of current leader \State \State \textbf{Local State}: \State\hspace{\algorithmicindent} $Q_{txn}=\{tx_1, tx_2,...,tx_k\}$: the set of transactions in the transaction queue, where $k$ is the total number \State \Function{propose}{$ $}: \If{$v_i=$\texttt{current\_leader}} \State $block:=$\textsf{execute}$(Q_{txn})$ \State $block:=$\textsf{sign}$(block)$ \State \textsf{broadcast}$(block)$ \State $approvals:=$\textsf{receive}$()$ \State $QC:=$\textsf{combine}$(approvals)$ \If{$approvals.length \ge \frac{n+1}{2}$} \State \textsf{commit}$(QC)$ \EndIf \EndIf \EndFunction \State \Function{deliver}{$block$}: \If{\textsf{verify}$(block)$} \State $approval:=$\textsf{approve}$(block)$ \State $approval:=$\textsf{sign}$(approval)$ \EndIf \State \textsf{send}$(approval$, \texttt{current\_leader}$)$ \EndFunction \end{algorithmic} \end{algorithm} Algorithm \ref{mpoa} shows a simplified version of the consensus algorithm. We omit details of the verification of transactions and blocks (e.g., signature, timestamp, balance). Each validator maintains a transaction queue $Q_{txn}$ locally. During the \textit{collecting term} of each epoch, once a validator receives a transaction, he broadcasts it with a timestamp (indicating which epoch it belongs to) to the other validators after verifying its validity\footnote{Malicious validators may hide transactions or ignore all the transactions from some particular participants. As such, participants could send their transactions to multiple validators or choose the one they trust the most.}. When the \textit{collecting term} ends, the leader executes all transactions in $Q_{txn}$ and constructs a block with the outcome (cf. Sec. \ref{sec:block}). Then he \textsf{proposes} that block by broadcasting it to all the followers (see function \textsf{propose}). On receiving the proposed block, followers verify its validity (see function \textsf{deliver}). If that block is correct, the validator approves this block by sending the leader an \textit{approval} message which is the signature on the hash of the block header. If the leader receives more than $f$ \textit{approvals} from different validators (including itself), it aggregates the signatures into a single \textit{aggregate signature} and commits it along with the digest of the block to $\mathbb{C}$ to create a checkpoint. Each checkpoint consists of a hash of the committed block header, \textit{aggregate signature}, and a \textit{bit index}. We use \textit{aggregate signature} as a proof that the committed block is approved by more than half of the validators. The \textit{bit index} is an integer, every bit of which represents whether or not the indexed validator signed the \textit{approval}. For example, we have $5$ validators in total, indexed by $v_0,v_1,v_2,v_3,v_4$. The \textit{bit index} of a certain checkpoint is $11$ whose binary format is $01011$, meaning that $v_1,v_3,v_4$ signed the \textit{approvals}. Let $cp_i=\{H(B_i),QA(H(B_i)),\text{\textsc{index}}\}$ denote the $i$th checkpoint, where $H(B_i)$ is the hash of the header of block $B_i$, $QA(H(B_i))$ is a constant-sized aggregate signature on $H(B_i)$, and \textsc{index} is an integer which contains the indexes of a list of validators that signed the $QA(H(B_i))$. The basic workflow is as follows: \textit{Aggregation.} The leader calls the \textsf{Combine} function to aggregate $m$ signatures on block $B_i$ from $m$ different validators into one. This signature will convince any verifier that the exact $m$ validators approved the commitment of the block. There are several signature constructions to achieve signature aggregation \cite{lysyanskaya}\cite{boldyreva}\cite{boneh}. In order to reduce the length of a checkpoint, we apply the one based on the short signature scheme of Boneh, Lynn, and Shacham \cite{shortsignature}. \textit{Verification.} We invoke the \textsf{Verify} function to execute the aggregate verification algorithm, verifying whether the committed block is actually approved by more than half of the validators. Given a checkpoint $cp_i=\{H(B_i),QA(H(B_i)),\text{\textsc{index}}\}$ which can be queried from $\mathbb{C}$, verifiers first find a set of public keys via \textsc{index}, then they verify that $QA(H(B_i))$ is a valid aggregate signature on $H(B_i)$ under the given keys. We apply a \textit{lazy-challenge} mechanism to verify the correctness of each checkpoint. After $\mathbb{C}$ receives the commitment, $\mathbb{C}$ will not verify the checkpoint until some party submits a \textit{challenge}. Given that all parties can view the content of the pending checkpoint by querying $\mathbb{C}$, they will run the verification algorithm locally. Any party can submit a challenge before the \textit{pending term} ends. On receiving a challenge, $\mathbb{C}$ will run the verification algorithm itself to make a binary decision. Either the leader or the challenger will win, and the loser will be punished (i.e., loose the bounty), but the details of punishment mechanism is not the focus of this paper. In order to ensure the liveness of the protocol, validators can also submit \textit{challenges} to vote out a non-responsive leader. If there is no block proposed or the proposed block is not committed after a local time-out, a validator can gossip the challenge message (i.e., essentially a signature) to other validators, which can be seen as a vote. Anyone who collects more than $f$ votes aggregates them into one signature and submits the signature to $\mathbb{C}$ and let it decide how to deal with the leader. \subsection{Block Construction} \label{sec:block} A block in our protocol contains all the transactions happened in $\mathbb{SC}$ during a specific epoch\footnote{Transactions may be assigned to the next epoch due to network latency and Byzantine validators may arbitrarily discard transactions.}, as well as the updated states (i.e., balances) after executing those transactions. As such, a block is a basic unit of a state transition in $\mathbb{SC}$. More precisely, after a block is published, either all of the transactions complete (all transactions are computed correctly), or they fail, and the state of $\mathbb{SC}$ remains unchanged. \begin{figure}[h!] \begin{center} \includegraphics[width=1.0\linewidth]{images/block.pdf} \caption{The construction of $\mathbb{SC}$ blocks. $\mathbb{SC}$ is ``stitched'' onto $\mathbb{MC}$.} \label{fig:block} \end{center} \end{figure} The design goal of constructing a block in $\mathbb{SC}$ is (i) to include all the information needed for a participant to withdraw or exit, (ii) that when a participant wants to withdraw or exit, $\mathbb{C}$ should be able to efficiently verify the proof of possession of the funds, and (iii) that all of the finalized blocks should follow a strict order according to when they are confirmed in $\mathbb{MC}$. To fulfill those requirements, Vulcan's blocks consist of a list of transactions, a list of updated accounts, along with the metadata required for verification. Fig. \ref{fig:block} depicts how $\mathbb{SC}$ blocks are constructed and ``stitched'' onto $\mathbb{MC}$. \subsubsection{Block Header} The block header contains metadata including the epoch number, a hash of the previous block, the reference of the last checkpoint confirmed on $\mathbb{MC}$, and the merkle roots of transactions and balances of accounts. The \textit{last checkpoint} refers to the hash of the previous block's header. The reason to include this field in the block header is to provide a reference to the last checkpoint, and indicate this block is published after the previous block is confirmed on $\mathbb{MC}$. \subsubsection{Block Body} The block body consists of two merkle trees, a transaction tree and an account tree. The transaction tree is a regular \textit{Merkle Tree} (MT) used in Bitcoin \cite{nakamoto2008bitcoin}, where hashes of transactions forms leaf nodes and every non-leaf node is labelled with the hash of its two child nodes. Verifiers can efficiently and securely verify the existence of a leaf node in a large data structure by providing a MT proof which is the path consisting of all the hashes going up from the leaf node to the root. For the account tree, we introduce the \textit{Merkle Patricia tree} (MPT) structure -- used in Ethereum \cite{wood2014ethereum}, to merkleize the accounts. In the context, the account id is the key and the balance of the account is the value in the MPT. Verifiers can efficiently and securely verify the existence of a key and the correctness of the expected value to the key using a MPT proof. \subsection{Withdrawal/Exit} The withdrawal/exit procedure can be viewed as a cross-chain protocol to transfer assets from $\mathbb{SC}$ to $\mathbb{MC}$. This part is more complex than deposit (i.e., transferring assets reversely) because the updates in $\mathbb{SC}$ are unknown to $\mathbb{MC}$. Therefore, participants have to provide sufficient proofs to $\mathbb{MC}$ about the funds they want to withdraw. The difference between a withdrawal and an exit is that a participant withdraws a certain amount of money equal or less than the balance without notifying any malicious behaviors (from a participant's view), while a participant exit with all of his money left in $\mathbb{SC}$ when some obvious maliciousness happens. In Vulcan, participants withdraw or exit by sending a withdrawal/exit request to $\mathbb{C}$ containing the value to withdraw and a \textit{Proof of Possession} (PoP) which is to prove a participant owns certain balance of assets in $\mathbb{SC}$. A standard PoP consists of following components: \begin{itemize} \item \textit{Block Header.} It is a regular block header, whose hash should equal to the checkpoint. \item \textit{Balance.} The balance of the account at the time of the checkpoint. \item \textit{Merkle Path.} It is for $\mathbb{C}$ to verify whether the provided balance matches the expected value in the account tree with the MPT root included in the block header field. \end{itemize} Now, we start to describe the withdrawal/exit procedure assuming every party is honest. Parties can only withdraw from the current epoch. For example, after the \textit{proposing term} of current epoch, the latest balance of $C_i$ is $x$ and it wants to withdraw $y$ coins. $C_i$ initiates the withdrawal by sending a withdrawal request directly to $\mathbb{C}$ containing a withdrawal value (i.e., $y$ coins), as well as the PoP certifying he is the owner of $x$ coins. After the verification, $\mathbb{C}$ unfreezes $y$ coins on $\mathbb{MC}$ and send them to $C_i$. On another site, validators are always aware of the withdrawal. After it is finalized, validators will change the balance of $C_i$ on $\mathbb{SC}$ to $x-y$ and generate a transaction indicating the balance change which will be included in the next block. An exit procedure works the same except indicating the withdrawal value. If the number of Byzantine validators remains less than $\frac{n}{2}$, we assume that honest validators or clients can address malicious behaviors by issuing a \textit{challenge} request (cf. Sec. \ref{sec:poa}), even though the duration of the echo might be longer than usual. Therefore, participants can always withdraw/exit through a normal procedure. However, when the number of Byzantine validators is more than $\frac{n}{2}$ (e.g., all of the validators are compromised), it means it is no longer safe to stay in this $\mathbb{SC}$. At this point, end-users can go through an interactive procedure to exit, but we assume the users would verify their balances at the end of every epoch (cf. Appendix \ref{sec:interactive-exit}). \section{Formal Security Definition of Vulcan} \label{sec:security} \subsection{Modeling Vulcan} In this section, we formally present our sidechain in the Universally Composable Security (UCS) framework. In particular, we follow the work of \cite{general-state-channel} applying a synchronous version of the global UC framework (GUC) \cite{guc}, an extension of standard UC model allowing for a globally available set-up. Under this model, all the deposits (from $\mathbb{MC}$ to $\mathbb{SC}$) and the withdrawal/exit (from $\mathbb{SC}$ to $\mathbb{MC}$) are handled via a global ideal functionality $\mathcal{L}(\Delta)$, the state of which is globally accessible by all parties. $\mathcal{L}(\Delta)$ can freely add and remove money in user's accounts and the parameter $\Delta$ models that any interaction with $\mathcal{L}(\Delta)$ has a maximal delay $\Delta$. A full definition of $\mathcal{L}(\Delta)$ can be found in \cite{dziembowski2018foundations}. In the UCS framework, a protocol is defined as a set of computing entities, each representing an actual component of the system, including an adversary (which models all the possible attacks that the protocol may suffer) and an environment (which models the external interactions that the protocol may have). The kind of computing entities that are used are \textit{interactive Turing machines} (ITMs), which are basically traditional Turing machines with the added capability of interchanging information with other machines. Thus, the system of the present work is modeled as a protocol in the framework. For a protocol to fulfill its intended security goals, two different protocols have to be designed: one representing an idealized model and one representing a real implementation. The ideal protocol will encompass all the functionality as a single entity, operating as desired, either normally or under any kind of attack. In the real protocol, each element is modeled as a separate computing entity. The security goal is achieved if any environment in which the protocol is deployed, cannot distinguish if it has interacted with the ideal model, or the realistic implementation. The concept of distinction between the two protocols has a concrete definition, in terms of ensembles of probability distributions. An ensemble of probability distributions is a set of random variables $\mathcal{X} = \{X(z,k) : z \in \{0,1\}^* \}$, i.e., for all possible choices of $z \in \{ 0,1\}^*$ and $k \in \mathbb{N}$, there is a random variable $X(z,k)$ in the set. \begin{defn} We say that two probability distribution ensembles $\mathcal{X}$ and $\mathcal{Y}$ are \textit{indistinguishable}, denoted by $\mathcal{X} \approx \mathcal{Y}$, if for any $a, b \in \mathbb{N}$, there exists $k_0 \in \mathbb{N}$ such that, for any $k > k_0$, \begin{equation} |P(X(z) = 1) - P(Y(z) = 1) | < \frac{1}{k^a} \end{equation} with $z \in \{ 0,1\}^\lambda$ and $\lambda \leq k^b$. \end{defn} Although this definition is slightly technical, in the context of the UCS framework, it essentially means that any polynomially bounded machine (PPT) in $k$ (i.e., an ITM that is computationally bounded by a polynomial of $k$), cannot obtain different outputs after performing computations that are represented by random variables from the ensembles $\mathcal{X}$ and $\mathcal{Y}$ (for a given $k$ and $z$), except with negligible probability, for an input $z$ whose length is also polynomial in $k$. We denote the ideal protocol with $\mathcal{I}$, and the real protocol with $\Pi$. The random variable that represents the output of the protocol $\Pi$ in conjunction with an adversary $\mathcal{A}$ and an environment $\mathcal{E}$, with inputs $k$ and $z$, is denoted by $\text{EXEC}_{{\Pi}, \mathcal{A}, \mathcal{E}}(k,z)$. To avoid complicating the notation, $\text{EXEC}_{{\Pi}, \mathcal{A}, \mathcal{E}}$ will represent the ensemble of probability distributions, for all possible choices of $k$ and $z$. With this, we can state our security definition. \begin{defn} \label{EmulationDef} The concept of security of the protocol $\Pi$ is achieved if for any adversary $\mathcal{A}$ and any environment $\mathcal{E}$, we can always find an adversary $\mathcal{S}$ (typically referred to as the ``simulator'') such that: \begin{equation} \text{EXEC}_{{\Pi}, \mathcal{A}, \mathcal{E}} \approx \text{EXEC}_{{\mathcal{I}}, \mathcal{S}, \mathcal{E}} \end{equation} \end{defn} The ensembles of the execution of the protocol with environment $\mathcal{E}$ and adversary $\mathcal{A}$ are indistinguishable from the ensembles of the execution of the ideal functionality $\mathcal{I}$ with the same environment $\mathcal{E}$ and adversary $\mathcal{S}$. Part of the security proof, is to build a simulator $\mathcal{S}$ for any given adversary $\mathcal{A}$. Whenever the conditions of definition \ref{EmulationDef} are met, we say that $\Pi$ UC-realizes the ideal $\mathcal{I}$. \begin{thm} \label{SecurityThm} There exists a protocol $\Pi$, such that it UC-realizes the ideal protocol $\mathcal{I}$ for the ideal funcionality $\mathcal{F}$. \end{thm} We assume synchronous communication network, where there is a known upper bound on the message transmission delay. To simplify the modeling, we assume that the operation of the protocol proceeds in units. The communication between any two of four computation entities takes exactly one unit (e.g., It takes one unit of time for a message sent from some party to reach $\mathbb{C}$ or other parties), while the communication between entities and the environment $\mathcal{E}$ takes zero units. As we describe the elements of the protocol, we present all the parameters that they require to work, and the mathematical notation for them. \newenvironment{myFrame}[1] {\mdfsetup{ frametitle={\colorbox{white}{\space#1\space}}, innertopmargin=10pt, frametitleaboveskip=-\ht\strutbox, frametitlealignment=\center, leftmargin = 10pt, rightmargin = 10pt, innertopmargin=10pt, innerbottommargin=10pt, innerrightmargin=10pt, innerleftmargin=10pt, } \begin{mdframed}% } {\end{mdframed}} \begin{figure*}[h!] \begin{myFrame}{\textbf{Ideal Functionality $\mathcal{F}$}} The ideal functionality $\mathcal{F}$ encompass all the functions of $V_1, \ldots, V_n$, $C_1, \ldots, C_m$, $\mathbb{C}$ and $\mathcal{L}$. It communicates with $\mathcal{E}$ via dummy parties $V_1^*, \ldots, V_n^*$, $C_1^*, \ldots, C_m^*$. For a fixed time $\Delta$, $\mathcal{E}$ gives turns to the clients to make deposits (or join), make withdraws, exit or challenge the checkpoint. It also gives turns to the validators to also challenge the checkpoint. \begin{center} (I) \underline{\textbf{Deposit}} \end{center} A. Upon receiving $(\texttt{depositRequest}, \text{id}_{C_i^*},x)$ from $\mathcal{E}$: \begin{enumerate} \item If the timer $\Delta$ has not expired, $\text{id}_{C_m^*} \notin \mathcal{C}^*$, and the mainchain balance for that ID is enough, invoke a dummy machine $C_m^*$ for the client, update $\mathcal{C}^*:= \mathcal{C}^*\cup \{\text{id}_{C_m^*}\}$, update the balance for the client $B(\text{id}_{C_i^*},e):=x$ and send $(\texttt{endOfTurn})$ to $\mathcal{E}$. \item If the timer $\Delta$ has not expired and $\text{id}_{C_i} \in \mathcal{C}$, send $(\texttt{existingClient})$ to $\mathcal{E}$. \end{enumerate} B. Upon receiving $(\texttt{turnToTalk})$ for a deposit of an amount $x$ through $\mathcal{C}_i^*$: \begin{enumerate} \item If the timer $\Delta$ has not expired, update the balance for the client $B(\text{id}_{C_i^*},e):=B(\text{id}_{C_i^*},e)+x$ and send $(\texttt{endOfTurn})$ to $\mathcal{E}$ through $C_i^*$. \end{enumerate} \begin{center} (II) \underline{\textbf{Withdraw/Exit}} \end{center} A. Upon receiving $(\texttt{turnToTalk})$ for a withdraw of an amount $x$ from $\mathcal{E}$ through $C_i$: \begin{enumerate} \item If the timer $\Delta$ has not expired, verify if $B(\text{id}_{C_i^*},e) \geq x$. If so, transfer $x$ to $C_i^*$ mainchain account, then send $(\texttt{endOfTurn})$ to $\mathcal{E}$. Else send $(\texttt{endOfTurn})$ to $\mathcal{E}$. \end{enumerate} B. Upon receiving $(\texttt{turnToTalk})$ from $\mathcal{E}$ through $C_i^*$ for it to exit: \begin{enumerate} \item If the timer $\Delta$ has not expired, verify if $B(\text{id}_{C_i^*},e) \geq x$. If so, transfer $x$ to $C_i^*$ mainchain account and halt the machine $C_i^*$. Else, send $(\texttt{endOfTurn})$ to $\mathcal{E}$. \item If $\mathcal{C}^* = \emptyset$, halt the machines $V_1^*, \ldots V_n^*$, send $(\texttt{executionEnd},1)$ if the remaining balance $b=0$ or $(\texttt{executionEnd},0)$ if the remaining balance $b \neq 0$ and halt. Else, send $(\texttt{endOfTurn})$ to $\mathcal{E}$. \end{enumerate} \begin{center} (III) \underline{\textbf{Transaction}} \end{center} A. Upon receiving $(\texttt{turnToTalk})$ from $\mathcal{E}$ through any $C_i^*$ and when timer $\Delta$ has expired: \begin{enumerate} \item Increase the epoch count $e:=e+1$, reset the transactions accumulators $b_i^s:=0$ and $b_j^r:=0$, the transactions queue $Q_{txn}=\emptyset$, reset the transactions count $n_{txn}:=0$, reset the transactions timer $t_{txn}$ and send $(\texttt{Ready})$ to $\mathcal{E}$ to indicate that the Transactions term has started. \end{enumerate} Upon receiving $(\texttt{turnToTransfer})$ from $\mathcal{E}$ through $C_i$ to transfer an amount $x$ to $C_j^*$: \begin{enumerate} \item Verify if $B_l(\text{id}_{C_i^*},e) \geq x$. If so, update the accumulators $b_i^s:=b_i^s+x$, $b_j^r:=b_j^r+x$, the transactions queue $Q_{txn}:=Q_{txn} \cup \{txn\}$, the counter $t_{txn}:=t_{txn}+1$. Repeat this $n$ times to store an internal registry for each validator. \item Evaluate if $t_{txn} \geq t_{max}$ or $n_{txt} \geq n_{max}$. If so, compare the j-th registry against the rest. If more than $\frac{n}{2}$ registries agree with the j-th, compile the block $B_e$ and the checkpoint for the epoch with the information of the j-th registry, and send $(\texttt{blockReceived})$ to $\mathcal{E}$. If not, send $(\texttt{ready})$ to $\mathcal{E}$. \end{enumerate} \begin{center} (IV) \underline{\textbf{Pending}} \end{center} A. Upon receiving $(\texttt{blockReceived})$, $\mathcal{E}$ starts giving sequentially the turn to the validators and clients to request operations. Upon receiving $(\texttt{turnToTalk})$ from $\mathcal{E}$ through $V_k^*$ for a challenge for an invalid checkpoint, and the timer $\Delta$ has not expired: \begin{enumerate} \item Remove the wager amount $w$ from $V_k^*$ mainchain account, and use $B_{e-1}$ to verify if the claim is valid. \item If the claim is valid, invoke a new machine $V_l'$ to replace $V_l^*$ (the machine that is the leader of the epoch), update $\mathcal{V}:=\mathcal{V} \setminus \{V_l^*\} \cup \{V_l'\}$, return the wager $w$ to $V_k$ mainchain account, reset the transactions registry $B(\text{id}_{C_i^*},e):=0$, $B(\text{id}_{C_j^*},e):=0$, $Q_{txn}=\emptyset$ and send $(\texttt{ready})$ to $\mathcal{E}$. Otherwise send $(\texttt{ready})$ to $\mathcal{E}$ \end{enumerate} B. Upon receiving $(\texttt{turnToTalk})$ from $\mathcal{E}$ through $C_i^*$, for invalid transaction(s) and the timer $\Delta$ has not expired: \begin{enumerate} \item Remove the wager amount $w$ from $C_i$ mainchain account, and use $PP$ to verify if the claim is valid. \item If the claim is valid, invoke a new machine $V_l'$ to replace $V_l^*$ and update $\mathcal{V}$, return the wager $w$ to $C_i^*$ , reset the $n$ transactions registries $b_i^s:=0$, $b_j^r:=0$, $Q_{txn}=\emptyset$ and send $(\texttt{ready})$ to $\mathcal{E}$. Otherwise send $(\texttt{ready})$ to $\mathcal{E}$ \end{enumerate} C. Upon receiving ANY message and the timer $\Delta$ has expired: \begin{enumerate} \item Update $B(\text{id}_{C_i^*},e):=B(\text{id}_{C_i^*},e)-x$ and $B(\text{id}_{C_j^*},e):=B(\text{id}_{C_i^*},e)+x$, reset $b_i^s:=0$, $b_j^r:=0$, $Q_{txn}=\emptyset$, increase the epoch $e:=e+1$, $j:=j+1$ (the leading registry) and send $(\texttt{ready})$ to $\mathcal{E}$. \end{enumerate} \end{myFrame} \caption{Ideal functionality $\mathcal{F}^{\mathcal{L}(\Delta)}_{sc}(\mathcal{V},\mathbb{C})$ for the Sidechain in Vulcan.} \label{fig:ideal-functionality} \end{figure*} \subsection{Security and Efficiency Properties} \label{sec:security-property} We emphasize that our scheme provides both \textit{safety} and \textit{liveness} assuming no more than $\frac{n-1}{2}$ validators are faulty without online requirement. Even if the number of Byzantine validators is more than $\frac{n}{2}$, our scheme ensures safety by sacrificing liveness (i.e., the protocol might terminate) and it requires clients to be online at least once within an epoch (some techniques like watchtowers \cite{mccorry2018pisa} can be used). Here, safety means that all honest parties can always retrieve the assets from $\mathbb{SC}$ to $\mathbb{MC}$. More specifically, safety can be divided in to the following security guarantees: \textit{Consensus on sidechain update.} A proposed block containing transactions happened during a single epoch should go through a consensus process, where more than a half of followers should approve that block before it is committed by the leader. If the committed block does not receive sufficient approvals, it might be reversed or the whole sidechain will be terminated. \textit{Guaranteed withdrawal/exit.} The end-users of a sidechain are guaranteed that they can always withdraw a certain amount of coins less than or equal to the balance, or exit the sidechain with all the assets from the latest agreed checkpoint. In addition to safety, we introduce efficient goals by identifying the duration of an epoch in both optimistic and pessimistic cases. Every transaction\footnote{Mainly depends on the average block production time of the $MC$, e.g., about 10 min in Bitcoin and 3 min in Ethereum.} sent to $\mathbb{MC}$ is handled in time $O(\Delta)$ and the consensus time, denoted by $\tau$ (much smaller than $\Delta$), is constantly set according to the use case. We can see from Fig. \ref{fig:epoch} that in optimistic case, one epoch can end in one round, which includes four distinct terms, while in pessimistic case, it might take several rounds (with limit to 3) to finish an epoch. Therefore, an epoch ends in time $O(\Delta+\tau)$ in both optimistic and pessimistic cases. \subsection{The Ideal Functionality} \begin{figure*}[h!] \begin{myFrame}{} The smart contract only accepts messages during the Commit and Pending terms. \begin{center} (I) \underline{\textbf{Commit}} \end{center} A. Upon receiving $(\texttt{commit}, cp_e)$ to $\mathbb{C}$ from any of the validators, $V_l$: \begin{enumerate} \item Start a counter for $\Delta$ units of time. \item Send ($\texttt{blockReceived}$) to $\mathcal{E}$, for it to sequentially give the turn to make an operation to clients (deposits, withdraws or challenges) and validators (only challenges), and start the pending term. \end{enumerate} \begin{center} (II) \underline{\textbf{Pending}} \end{center} A. Upon receiving $(\texttt{depositRequest}, \text{id}_{C_i}, x)$ from a client $C_i$ and if the timer $\Delta$ has not expired: \begin{enumerate} \item Request to $\mathcal{L}$ to transfer $x$ from $C_i$ (in the mainchain), by sending the message $(\texttt{depositRequested},\text{id}_{C_i},x)$ to $\mathcal{L}$. \item If $(\texttt{cannotDeposit},\text{id}_{C_i},x)$ is received, send $(\texttt{depositNotReceived},x)$ to $C_i$ and terminate the operation. \item If $(\texttt{depositConfirmed},\text{id}_{C_i},x)$ is received, send $(\texttt{depositReceived},x)$ to $C_i$ and to all the validators, for them to update the balance, and terminate the operation. \end{enumerate} B. Upon receiving $(\texttt{depositRequest}, \text{id}_{C_i}, x)$ from $\mathcal{E}$ and if the timer $\Delta$ has not expired: \begin{enumerate} \item If $\text{id}_{C_i} \in \mathcal{C}^*$, send $(\texttt{existingClient})$ to $\mathcal{E}$ and terminate the operation. \item If $\text{id}_{C_i} \notin \mathcal{C}^*$, request to $\mathcal{L}$ to transfer $x$ from $C_i$ (in the mainchain), by sending the message $(\texttt{depositRequested},\text{id}_{C_i},x)$ to $\mathcal{L}$. \item If $(\texttt{cannotDeposit},\text{id}_{C_i},x)$ is received, send $(\texttt{depositNotReceived},x)$ to $\mathcal{E}$ and terminate the operation. \item If $(\texttt{depositConfirmed},\text{id}_{C_i},x)$ is received, send $(\texttt{depositReceived},x)$ to $C_i$ and to a randomly selected validator. \end{enumerate} C. Upon receiving $(\texttt{withdraw},b,b_{i,e},h_{B_{e-1},MP_{txn}})$ from a client $C_i$ and if the timer $\Delta$ has not expired: \begin{enumerate} \item Verify if the provided elements for the proof of possesion are valid. If the verification is valid, send $(\texttt{withdrawNotOK},b)$ to the client, and to a randomly selected validator. Else, send $(\texttt{withdrawOK},C_i,b)$ to $\mathcal{L}$ and to a randomly selected validator. \item Update the total balance $b_t(e):=b_t(e)-b$, and terminate the operation. \end{enumerate} D. Upon receiving $(\texttt{exit},b_{i,e},h_{B_{e-1},MP_{txn}})$ from a client $C_i$ and if the timer $\Delta$ has not expired: \begin{enumerate} \item Verify if the provided elements for the proof of possesion are valid. If the verification fails, send $(\texttt{cannotExit,b})$ to the client. Else, update the total balance $b_t(e):=b_t(e)-b$, send $(\texttt{clientExit},C_i)$ to $\mathcal{L}$ and a randomly selected validator. \end{enumerate} E. Upon receiving $(\texttt{noClients})$ from a validator $V_k$: \begin{enumerate} \item If the remaining balance $b=0$, send $(\texttt{executionEnd},1)$ to $\mathcal{E}$ and halt. \item If the remaining balance $b\neq 0$, send $(\texttt{executionEnd},0)$ to $\mathcal{E}$ and halt. \end{enumerate} F. Upon receiving $(\texttt{challenge},B_{k,e-1},w)$ from $V_k$ and if the timer $\Delta$ has not expired: \begin{enumerate} \item Send $(\texttt{getWager},w,V_k)$ to $\mathcal{L}$, to transfer the wager amount $w$ to $\mathbb{C}$, then use $B_{k,e-1}$ to verify if the claim is valid. \item If the claim is valid, invoke a new machine $V_l'$ and update the validators set $\mathcal{V}:=\mathcal{V} \setminus \{V_l\} \cup \{V_l'\}$, send the message $(\texttt{challengeValid}, V_l,V_l')$ to all the validators and $\mathcal{L}$, keep the epoch equal to $e$, stop the timer and proceed to the collect term. \item If the claim fails, update the epoch $e:=e+1$, stop the timer and terminate the operation. \end{enumerate} G. Upon receiving $(\texttt{challenge},PP,w)$ from $C_i$ and if the timer $\Delta$ has not expired: \begin{enumerate} \item Send $(\texttt{getWager},w,C_i)$ to $\mathcal{L}$, to transfer the wager amount $w$ to $\mathbb{C}$, then use $PP$ to verify if the claim is valid. \item If the claim is valid, invoke a new machine $V_l'$ and update the validators set $\mathcal{V}:=\mathcal{V} \setminus \{V_l\} \cup \{V_l'\}$, send the message $(\texttt{challengeValid}, V_l,V_l')$ to all the validators and $\mathcal{L}$, keep the epoch equal to $e$, stop the timer and proceed to the collect term. \item If the claim fails, update the epoch $e:=e+1$, stop the timer and terminate the operation. \end{enumerate} H. Upon receiving ANY message and if the timer $\Delta$ has expired: \begin{enumerate} \item Update the epoch $e:=e+1$, and send $(\texttt{epochChanged})$ to a randomly selected validator. \end{enumerate} \end{myFrame} \caption{The smart contract functionality $\mathbb{C}$}. \label{fig:smart-contract-functionality} \end{figure*} This section presents the ideal functionality for the protocol. The UCS framework requires that, for the ideal protocol, the functionality of the whole system to be performed by a single entity. To keep protocol transparent to any environment or adversary, the system must still have computing entities representing all the elements that are part of the protocol, but just as "dumb machines" that forward incoming messages to the functionality to perform what was requested, and forward output to the environment $\mathcal{E}$. A deposit on $\mathbb{SC}$ triggers the deployment of the protocol. We assume that the order of validators passing the leader is following their indexes, e.g., $V_0,V_1,...,V_n$ and starts over. Lets denote with $\mathcal{F}^{\mathcal{L}(\Delta)}_{sc}(\mathcal{V},\mathbb{C})$ the ideal functionality of the $\mathbb{SC}$, where $\mathcal{V}$ is a set with a prefixed number of validators, $\mathbb{C}$ is a set of contracts deployed on the $\mathbb{MC}$ and $\mathcal{L}(\Delta)$ is the mainchain with delay $\Delta$. The ideal functionality communicates with parties from both $\mathcal{C}$ and $\mathcal{V}$. To keep the model as simple as possible, we exclude transaction fees in our modeling. The Sidechain functionality is shown in Fig. \ref{fig:ideal-functionality}. We will explain how the interactions happen in four phases: (I) \textbf{Deposit.} Parties can join $\mathbb{SC}$ or increase their balance by depositing an amount $x$ via the message \texttt{depositRequest}. (II) \textbf{Withdraw/Exit} Parties from $\mathcal{C}$ can withdraw certain amount of funds or exit the $\mathbb{SC}$ by sending a \texttt{withdraw} or \texttt{exit} message to the functionality during the pending term of current epoch. After the verification, the functionality will restore to the party's mainchain account the requested amount (or the total balance). In case of an exit message, the requesting party machine will halt. (III) \textbf{Transaction.} The procedure for updating the state of $\mathbb{SC}$ proceeds in epochs which have four distinct terms. We describe three of them in this phase and the other one in other phases. (A) During the \textit{collect term}, parties from $\mathcal{C}$ request transaction trough the \texttt{depositRequest} message to the functionality. After the correctness is verified, the states of related parties will be updated accordingly. The functionality keeps $n$ distinct registries, to emulate the fact that there are actually $n$ different validators. Considering the security assumptions, at most $\frac{n}{2} - 1$ of these distinct registries can be corrupted by te adversary. (B) During the propose term, the leader of the current epoch proposes the block via a \texttt{proposedBlock} message. In the functionality, this is accomplished by selecting the j-th registry, that corresponds to the leader of the epoch. Then it validates it against the rest of the registries, and if more than half have consistent information, then the block is compiled. (C) The functionality then computes the checkpoint $cp$ to start the commit term, upon which it sends the \texttt{blockReceived} message to $\mathcal{E}$, for it to start giving turns sequentially to the clients and validators to make deposits, withdraws or challenges. (IV) \textbf{Pending.} Every party can issue a \texttt{challenge} message during this term. There two situations where a party should complain. (i) The current block is not committed within a fixed amount of time. (ii) The pending checkpoint is wrong. Specifically, the message of the aggregate signature does not match the hash of the block header, or the aggregate signature is not aggregated by sufficient validators. After receiving at least one challenge message, the functionality will verify with the proof provided by the client or the validator. If the challenge is successful, then the leader will be removed from the committee. Otherwise, the challenger looses its wager. Now, let us explain how the ideal functionality $\mathcal{F}^{\mathcal{L}(\Delta)}_{sc}(\mathcal{V},\mathbb{C})$ ensures the security and efficiency properties from Sec. \ref{sec:security-property}. \textit{Consensus on sidechain update.} Each update in $\mathbb{SC}$ corresponds to a new block produced and confirmed in $\mathbb{MC}$ in the form of a checkpoint. To reach consensus among honest validators, the leader has to propose the block and gather enough votes to commit the block. If the leader does not receive sufficient votes (i.e., less than $f$ votes), it will give up this round and start a new one from the collecting term. After the commitment is confirmed, every party can view the content of the checkpoint by querying $\mathbb{C}$, which means every party can run the verification locally. We assume at least one honest party (including validators and clients) will request a challenge if the checkpoint is faulty. On receiving at least one \underline{challenge} message, the functionality will run the verification algorithm itself. If the pending checkpoint is detected faulty, the functionality will clear it, remove the leader from the committee, and start a new epoch. Therefore, we can see that this \textit{lazy-challenge} mechanism ensures that every update is agreed among honest parties as long as our assumption (i.e., $n\geq 2f+1$) holds. Given that each interaction with $\mathbb{C}$ is completed in $O(\Delta)$ units of time and the consensus is achieved in $O(\tau)$ related to the size of $\mathcal{V}$, an update in $\mathbb{SC}$ takes $O(\Delta+\tau)$ units. \textit{Guaranteed withdrawal/exit.} A withdrawal or exit can happen only during the \textit{pending term} of each epoch and it will only be handled until the pending checkpoint survives the pending term. If the pending checkpoint is obliterated after the pending term, the end-user has to wait for next round. A withdrawal/exit request can only be handled in the latest checkpoint (the pending one). After the request is approved by $\mathbb{C}$, the requested number of coins will be added to the requester's account within $\Delta$ units of time. The correctness of the withdrawal/exit is ensured by the former property since each checkpoint is agreed among honest validators. \subsection{The \textsf{Sidechain} Protocol} \begin{figure*}[h!] \begin{myFrame}{} \begin{center} (I) \underline{\textbf{Collect}} \end{center} A. Upon receiving $(\texttt{transferFunds}, (C_i,C_j,b),s_{i,j,b})$ from any client $C_i$, \begin{enumerate} \item If $C_i = C_j$, discard and send $(\texttt{ready})$ to $\mathcal{E}$. \item If $C_i \neq C_j$, verify if $V((C_i,C_j,b),s_{i,j,b},k_i)=1$ and $B(\text{id}_{C_i},e)>b$. If so, set $b_i^s:=b_i^s+b$, $b_j^r:=b_j^r+b$, $Q_{txn}(e) := Q_{txn}(e) \cup \{tx_l\}$ and $n_{txn}:=n_{txn}+1$. Otherwise, send $(\texttt{txNotValid})$ to the client $C_i$ and send $(\texttt{ready})$ to $\mathcal{E}$. \item Send $(\texttt{txRequest},(C_i,C_j,b),s_{i,j,b})$ sequentially to all the other validators. \item Upon receiving the last $(\texttt{txAck})$ or $(\texttt{txNotAck})$, evaluate if $n_{txn}\geq n_{max}$ or $t_{txn}\geq t_{max}$. If true, send $(\texttt{compile})$ to the leader. Otherwise $(\texttt{ready})$ to $\mathcal{E}$. \end{enumerate} B. Upon receiving $(\texttt{txRequest},(C_i,C_j,b),s_{i,j,b})$ from other validator, \begin{enumerate} \item If $V((C_i,C_j,b),s_{i,j,b},k_i)=1$ and $B(\text{id}_{C_i},e)>b$, update $b_i^s:=b_i^s+b$, $b_j^r:=b_j^r+b$, $Q_{txn}(e) := Q_{txn}(e) \cup \{tx_l\}$ and $n_{txn}:=n_{txn}+1$, and send $(\texttt{txAck})$ to the sender. Otherwise send $(\texttt{txNotAck})$ to the sender. \end{enumerate} \begin{center} (II) \underline{\textbf{Propose}} \end{center} A. Upon receiving $(\texttt{compile})$: \begin{enumerate} \item Compute $h_{B_{e-1}}$, $MT_{txn}$ and $MT_{\mathcal{P}}$, the tuple $B_e$ (the block), and $s_{B_e,l}$ (the signature). \item Send $(\texttt{proposedBlock},B_e,s_{B_e,l})$ to the rest of the validators, sequentially. \item After the last validator reply (or if the response timed out), proceed to the commit term. \end{enumerate} B: Upon receiving $(\texttt{proposedBlock},B_e,s_{B_e,l})$ from validator $V_l$ \begin{enumerate} \item Use $B_e$ and $s_{B_e,l}$ to verify the validity of the block. If the check is positive, send $(\texttt{blockApproved},s_{B_Q},l')$ to $V_l$. Otherwise send $(\texttt{blockNotApproved})$. \end{enumerate} \begin{center} (III) \underline{\textbf{Commit}} \end{center} A. Upon receiving the reply from the last validator for the block proposal (or if the last reply wait timed out): \begin{enumerate} \item If approval replies are more than $\frac{n}{2}$ compute $H(B_e)$, $QA(H(B_i))$ and \textit{index} and send $(\texttt{commit},cp_e,\textit{index})$ to the rest of the validators and $\mathbb{C}$. \item If approval replies are less than $\frac{n}{2}$, set $n_{txn}:=0$, restart the timer $t_{txn}=0$ and reset the internal parameters for collecting transactions, $b_i^s:=0$, $b_j^r:=0$ and $Q_{txn}(e)=\emptyset$, send $(\texttt{epochRestart})$ to the rest of the validators and $\mathcal{E}$ and send $(\texttt{ready})$ to $\mathcal{E}$. \end{enumerate} B. Upon receiving $(\texttt{epochRestart})$, \begin{enumerate} \item set $n_{txn}:=0$, $b_i^s:=0$, $b_j^r:=0$ and $Q_{txn}(e)=\emptyset$, restart the timer $t_{txn}=0$ and send $(\texttt{restartAck})$. \end{enumerate} \begin{center} (IV) \underline{\textbf{Pending}} \end{center} A. Upon receiving $(\texttt{depositReceived},\text{id}_{C_i},x)$: \begin{enumerate} \item If sender is $\mathcal{E}$, if $\text{id}_{C_i} \notin \mathcal{C}^*$, then invoke a machine for that client, update $\mathcal{C}^*:=\mathcal{C}^* \cup \{\text{id}_{\mathcal{C_i}}\}$ and $B(\text{id}_{C_i},e)=0$, else send $(\texttt{existingClient})$ to $\mathcal{E}$. \item If sender is any client $C_i$, update the balances $B(\text{id}_{C_i},e):=B(\text{id}_{C_i},e)+x$, and send $(\texttt{endOfTurn})$ to $\mathcal{E}$. \end{enumerate} B. Upon receiving $(\texttt{withdrawOK}, C_i, x)$ (or $(\texttt{withdrawNotOK}, C_i, x)$) from $\mathbb{C}$: \begin{enumerate} \item If \texttt{withdrawOK}, update $B(\text{id}_{C_i},e):=B(\text{id}_{C_i},e)-x$, and inform the validators, then send $(\texttt{endOfTurn})$ to $\mathcal{E}$, else send only $(\texttt{endOfTurn})$ to $\mathcal{E}$. \end{enumerate} C. Upon receiving $(\texttt{clientExit}, C_i, x)$ from $\mathbb{C}$: \begin{enumerate} \item Update clients set $\mathcal{C}:=\mathcal{C} \setminus \{\text{id}_{C_i}\}$. \item If $\mathcal{C} = \emptyset$, verify if $\mathcal{V} \neq \emptyset$, if so send $(\texttt{clientExit}, C_i, x)$ to a another randomly selected validator and halt, else send $(\texttt{clientExit}, C_i, x)$ to all the validators and then $(\texttt{endOfTurn})$ to $\mathcal{E}$. \item If $\mathcal{C} = \emptyset$ and $\mathcal{V} = \emptyset$, send $(\texttt{noClients})$ to $\mathbb{C}$ and halt. \end{enumerate} D. Upon receiving $(\texttt{turnToTalk})$ from $\mathcal{E}$: \begin{enumerate} \item If $cp_e$ is invalid, send $(\texttt{challengeCP}, B_{k,e-1},w)$ to $\mathbb{C}$, otherwise send $(\texttt{endOfTurn})$ to $\mathcal{E}$. \end{enumerate} E. Upon receiving $(\texttt{challengeValid}, V_l,V_l')$ from $\mathbb{C}$: \begin{enumerate} \item Reset the transaction registry, $b_i^s=0$, $b_j^r=0$, $Q_{txn}(e)=\emptyset$ to restart the epoch and send $(\texttt{ready})$ to $\mathcal{E}$. \item If the ID of $V_l$ corresponds to its own ID, send $(\texttt{ready})$ to $\mathcal{E}$ and halt. \end{enumerate} E. Upon receiving $(\texttt{epochChanged})$ from $\mathbb{C}$ or a validator: \begin{enumerate} \item Update the transactions registry $B(\text{id}_{C_i},e+1):=B(\text{id}_{C_i},e)+b_i^r-b_i^s$ for all $i \in \{1 \ldots m\}$. \item If the sender is $\mathbb{C}$, send $(\texttt{epochChanged})$ to the rest of the validators and then send $(\texttt{ready})$ to $\mathcal{E}$. \end{enumerate} \end{myFrame} \caption{Functionality for the Validators $V_1, \ldots, V_n$.} \label{fig:validator-functionality} \end{figure*} The functionalities of the machines that perform the main functions in the protocol, are presented in Fig. \ref{fig:smart-contract-functionality} and Fig. \ref{fig:validator-functionality}, for the Smart Contract $\mathbb{C}$ and the validators $V_1, \ldots, V_n$, respectively. A brief summary of the protocol is presented now. The reader can refer to Appendix \ref{UCSmodel}, for a detailed description of the UCS model of the protcol. The protocol starts when the environment machine $\mathcal{E}$ requests a deposit when there is no protocol running yet. Upon this, the smart contract $\mathbb{C}$, the validators $V_1, \ldots, V_n$ and the first client $V_1$ machines are invoked. After this, more clients can join by requesting deposits to $\mathbb{C}$, which transfers money from the mainchain to the sidechain, for the client to use for internal transactions. The protocol is divided in epochs as described in section \ref{sec:epoch}, and that division is mirrored in model. After a client joining the network, it can request to transfer money to other clients, to pay for goods or services in a quick manner. This is made through a request to any $V_l \in \mathcal{V}$. In the collecting term, validators receive all the transactions that the clients request, and store them. Once a certain period has passed, or a certain number or transactions have been accumulated, the propose term begins. In this term one validator takes the lead to compile all the transactions into a block, and propose it. When all the validators have replied to the request for approval (or a fixed timeout has passed), then the commit term begins. In this term, if more than half of the validators approved the block, then the leader generates a QC of the block and submits it to $\mathbb{C}$, after which the pending term begins. If the block fails gaining enough approvals, the protocol returns to the collecting term, and all transactions are discarded. In the pending term, the smart contract is open to receive challenges to the received checkpoint. Also during the pending term, clients can ask for making deposits or withdraws, or to exit. The validators and clients are sequentially queried by $\mathcal{E}$ if they need to request any those operations. Finally, the protocol execution ends when there are no more clients in the sidechain. When the last client is in the network, and it request to exit, if the withdraw operation for the rest of its balance is successful, the protocol ends and all the machines halt. The details of the security proof is given in Appendix \ref{security_proof}. \section{Implementation and Evaluation} \label{sec:implementation} In order to evaluate the feasibility and performance of the protocol and the underlying smart contracts, we constructed a simple proof of concept implementation of Vulcan. The smart contract is written in Solidity (around 800 LoC) and deployed in Ethereum Kovan testnet. We also implemented the code of the validator side using Golang (around 1900 LoC) and the client side using Python (around 800 LoC). An important criteria to evaluate smart contracts running over the Ethereum is the cost of \textit{gas}, which is the fundamental unit of computation in the Ethereum. The fees of any given fragment of programmable computation are universally agreed in terms of gas. Thus we can use the amount of gas to fairly measure the cost of each transaction. Note that we only give run-time cost of our protocol without considering the deployment cost because it is easy to optimize gas costs by extracting all functionality of the smart contract into an external library. \subsection{Constant Gas Cost} There are two types of transactions, \textit{deposit} and \textit{checkpoint}, having constant gas cost, which means no matter how the number of validators and clients increases, the gas cost of these transactions remains unchanged because they send constant size of data. The exchange rate of gas to ether is determined by GasPrice, which is freely chosen by the sender of the transaction. Higher GasPrice means more incentive for miners to mine that transactions, which leads to shorter latency. In our experiment, we choose an average rate, GasPrice$=4$ gwei (1 gwei $=10^{-9}$ Ether), under which the mean time to confirm a transaction is approximately 20 minutes. We use the exchange rate of 267 between Ether and US dollar\footnote{According to the exchange rate as of 31 May, 2019}. \begin{table}[!h] \centering \caption{Constant costs of deposit and checkpoint.} \begin{tabular}{||c | c | c | c | c ||} \hline Type of transactions & Bytes & Gas & ETH (gwei) & USD \\ [0.5ex] \hline\hline deposit & 4 & 21,912 & 87,600 & 0.023 \\ [1ex] \hline checkpoint & 98 & 272,324 & 1,089,300 & 0.289 \\ [1ex] \hline \end{tabular} \label{table:gascost} \end{table} Constant costs of deposit and checkpoint are list in Table \ref{table:gascost}. We observe that it only takes 0.023 USD to issue a deposit and the gas cost 21,912 is slightly more than that of a basic transaction (the gas cost of a basic value-transfer transaction is fixed to 21,000 gas). A checkpoint consists of the hash of the block header (32 bytes), an aggregate signature (65 bytes) and an index number (1 byte). And it takes 272,324 gas (approx. 0.289 USD) for a leader to submit a checkpoint. The duration of an epoch can be adjusted according to the actual use case. For example, a sidechain updates its state hourly (approx. 1 checkpoint for one hour, excluding epoch fails). Then it takes about 7 USD a day, and 2540 USD a year to maintain this sidechain. \subsection{Scalability} \subsubsection{Withdrawal/exit cost} As the size of clients scales up, the cost of a withdrawal/exit increases because the client needs to submit a longer merkle path as the proof of possession (Merkle proof) of the withdrawal/exit. Each withdrawal/exit consists of a key (the address of the requester, 20 bytes), a value (the balance, 4 bytes), a root hash (the hash of the merkle trie, 32 bytes), a branch mask (a ``roadmap'' to the root node, 1 byte), and an array of siblings (adjacent nodes along the merkle path, 32 bytes). The number of siblings grows with $m$ clients in $O(\log m)$, which is the major cost when the size of the clients becomes large. We measured the withdrawal/exit cost as the size of clients grow in incremental steps (cf. Fig. \ref{fig:withdraw}). During each step, we randomly instructed one client to issue a withdrawal/exit transaction to $\mathbb{C}$, recorded the number of siblings included in the transactions and the gas cost. \begin{figure}[h!] \begin{center} \includegraphics[width=1.0\linewidth]{images/withdraw.pdf} \caption{Gas cost as the number of clients increases.} \label{fig:withdraw} \end{center} \end{figure} We can observe that the gas cost grows in the same pattern as the number of siblings grows. During the first 2,000 steps, the gas cost surges to around 80,000 (approx. 17 siblings) and then, for the rest of steps, the speed of growth slows down. When the size of clients came to 10,000, the gas cost only increased to around 90,000 (approx. 20 siblings). Using the same GasPrice and the exchange rate, we can calculate that it only costs about 0.1 USD for a user to withdraw/exit in a sidechain network with 10,000 clients. Based on the above observation, we can easily estimate the cost of withdrawal/exit when the size of clients scales up to one million. For example, if one million clients joined the sidechain, a client would include 20 siblings in a withdrawal/exit transaction, which would cost 140,000 gas approximately (approx. 0.15 USD). \subsubsection{Aggregate verification cost} Our protocol applies a ``lazy-challenge'' scheme where $\mathbb{C}$ will not run the verification of the pending checkpoint until some party submits a ``challenge'' request. There are two types of challenges: (i) a challenge named \textit{challenge-ncp} complaining the leader for not committing the checkpoint, (ii) and a challenge named \textit{challenge-cp} complaining the pending checkpoint (faulty aggregate signature). The former requires parameters including an aggregate signature assembled by the challenger and an index number, while the latter requires no parameters. Both two types of challenges will trigger $\mathbb{C}$ running the verification of aggregate signature. We implemented BGLS aggregate signature \cite{boneh} in Solidity based on an existing codebase\footnote{https://github.com/Project-Arda/bgls-on-evm}. \begin{figure}[h!] \begin{center} \includegraphics[width=1.0\linewidth]{images/verification.pdf} \caption{Gas cost as the number of validators increases.} \label{fig:verification} \end{center} \end{figure} Fig. \ref{fig:verification} showed the gas cost of the aggregate verification as the number of validators increases. We can see that the gas cost (triggered by \textit{challenge-cp}) grows linearly with the validator number from $334,659$ with $10$ validators to $7,723,091$, approx. $0.327$ USD to $7.546$ USD (gas cost triggered by \textit{challenge-ncp} from $338,953$ with $10$ validators to $7,727,248$, approx. $0.331$ USD to $7.542$ USD because of additional parameters). This is because when the number of validators grows, the complexity of the verification increases linearly. Note that the validator number is limited even though we ignore the monetary cost, because there is a \textit{gas limit} which defines all the transactions inside a block allowed to consume in Ethereum. However, the \textit{gas limit} can be adjusted by the miner due to the congestion, which is about $8,000,000$ on average. \section{Related Work} \label{sec:related-work} The idea of off-chain scaling originated from \textit{Lightening Network} \cite{poon2016bitcoin}, which has emerged as the most promising PCN practice for Bitcoin, followed by \textit{Sprites} and \textit{Raiden} for Ethereum. There exist extensive literature proposing constructions to improve PCN. Revive \cite{revive2017}, Spider \cite{Sivaraman_2018} , and Flash \cite{wang2019flash} propose dynamic routing algorithms to maximize the throughput and success volume of PCN, while Perun \cite{perun2019} introduces \textit{virtual payment channels} to avoid the involvement of the intermediary for each individual payment, thereby, significantly reducing communication complexity. In contrast to channels between two parties, sidechain-based approaches allow parties in a sidechain network to freely perform transactions without a prebuilt channel. A first sidechain-based scheme that enables off-chain transactions is Plasma \cite{poon2017plasma}, which allows arbitrary consensus algorithms in the sidechain. The consensus mechanism enforces the rules encoded in the smart contract, through which disputes can are resolved fairly. Therefore, as long as the mainchain remains secure, the safety is ensured in the sidechain even if the consensus mechanism is compromised. Two main challenges of current plasma constructions \cite{plasmamvp}\cite{plasmacash} are the size of proofs and cumbersome withdrawal/exit procedure. A very interesting construction similar to ours is called NOCUST \cite{rami2018nocust}, which is an account-based \textit{commit-chain}, where a single operator maintains users' account and commits checkpoints at regular intervals. NOCUST is a challenge-response protocol, where users can issue different types of challenges directly to the smart contract to mediate. As such, it requires users to be online at least once within a block time, or a malicious operator might manipulate users' balances. NOCUST also utilize zkSNARK \cite{zkSNARK} in its smart contract which enables efficient verification of the complete correctness of checkpoints. A major difference between NOCUST and Vulcan is that our protocol features a PoA-based consensus which ensures safety and liveness without online requirement under appropriate security assumption. We argue that by introducing a consensus mechanism over a small-sized committee in the sidechain can mitigate single-point-failure and improve user experience. Recent literature finds that UCS framework has been widely used to prove the security of off-chain solutions \cite{miller2017sprites}\cite{perun2019}\cite{general-state-channel}\cite{fair-swap}\cite{multyparty}\cite{malavolta2019anonymous}. Given the serious monetary loss when off-chain protocols are massively applied, we suggest that the security of each off-chain protocol should be formally proved. \section{Conclusions} \label{sec:conclusion} In this paper we introduced Vulcan, a sidechain-based off-chain protocol for public blockchains achieve scale-out throughput without sacrificing security. We developed mPoA for validators to achieve consensus in the sidechain which ensures liveness and safety with a maximum of $f<\frac{n}{2}$ validators being Byzantine. We utilized aggregate signature to generate each checkpoint whose validity will only be verified by the smart contract when some party some party. One advantage of Vulcan is that as long as the security assumption holds, clients can always remain offline without worrying assets loss. We defined the security of our protocol in the UC framework and provided formal proofs. The performance evaluation shows that Vulcan is practical and scalable in terms of monetary cost: around $0.289$ USD for each checkpoint and $0.15$ USD for each withdrawal in the order of million users. For future work, we plan to extend our off-chain model to support executing smart contracts. \bibliographystyle{IEEEtranS}
{'timestamp': '2019-06-18T02:06:02', 'yymm': '1906', 'arxiv_id': '1906.06490', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06490'}
arxiv
\section{Introduction} With the rapid development of the Internet and camera, the number of videos is increasing at a very high speed. There are millions of video submissions on video-sharing websites like YouTube every day. Besides, the video surveillance system plays an important role in maintaining security \cite{8253857}\cite{8733112}\cite{wang2018generative}. These video files contain a lot of information for human, such as time duration and action classify\cite{8709763}\cite{wang2019aed}. How to make full use of videos is an indispensable step for building a smart city. It is vital for the development of information age to extract information from a large number of videos by automatically. Action is the most important information for videos because the essence of the video is recording varieties of motion. So a significant branch of video task is action recognition, which aims to recognize the class of action from a trimmed video. But the task is limited because its research object is videos that have been manually trimmed and only contain single action. The majority of videos in the real world are untrimmed videos and contains multiple action instances in a single video. The problem requires another challenging task: temporal action detection, which aims to recognize the temporal boundaries and classes of action instance from untrimmed videos. Temporal action detection usually includes two steps: proposal and classification. Proposal stage focuses on detecting action boundary and generating action instance with untrimmed video. Classification is aim to recognize the class of action instance produced in the previous step. For the task of temporal action detection, classification has achieved high accuracy. And the speed and precision of proposals is the main factor limiting temporal action detection \cite{caba2015activitynet}\cite{jiang2014thumos}. High-quality proposals should meet two requirements \cite{lin2018bsn}: (1) high recall; (2) high overlap with ground truth. And a good algorithm of generating proposal should not only generate excellent proposals, but its speed should be as fast as possible. Because videos occupy a large amount of memory, we must improve the speed of method so for being applied to practice. \begin{figure*}[ht] \centering \includegraphics[width=0.9\textwidth]{figure/network.png} \caption{The framework of our approach. (a) Two-stream network is used to encode visual features in snippet-level. (b) The architecture of Boundary Sensitive Network} \label{network} \end{figure*} Most proposal generation methods generate proposals by using sliding windows \cite{buch2017sst}\cite{caba2016fast}\cite{escorcia2016daps}\cite{shou2016temporal}. But the pre-defined durations and intervals of sliding windows cannot generate proposals with flexible length, which greatly reduced the precision of proposals. Boundary Sensitive Network (BSN) \cite{lin2018bsn} used a temporal network with 3 convolution layers to deal with video feature sequences and could generate proposals with flexible duration. Though BSN has a good performance, its multiple steps and networks make the speed not optimistic. Recently, lots of high performance computing methods are introduced into the field of compute vision for acceleration. Distributed computing is one of the more common methods. It is committed to increasing the number of devices in exchange for speeded-up. Parameter Server is a famous acceleration method for training deep learning network. On this framework, Multiple workers compute different input data and central server integrates the outputs from workers, which is very simple and effective. But when the number of workers has continuous growth, which leads to a significant increase in communication volume, acceleration will get worse. To address these problems and improve the speed of producing proposals, we designed a new parallel computing framework. Because BSN is the state-of-art method for temporal action proposal generation, so our new framework was tested on BSN and had a higher efficiency compared to the popular Parameter-Server Framework\cite{dean2012large}. In summary, the main contribution of our work is two-fold: \begin{enumerate} \renewcommand{\labelenumi}{(\theenumi)} \item We build a new parallel computing framework to speed up temporal convolution network on temporal action recognition with high efficiency. \item A metric is put forward to evaluate the time consumption in the distributed deep learning field. \end{enumerate} \section{Related work} Temporal action detection aims to detect action instances from the untrimmed video. The task could be divided into two steps: proposal and classification. Though some methods do the two steps at the same time, the majority of methods take the task as a serial process and finish proposal and classification separately. \textbf{Temporal action proposal generation.} Proposal generation is the distinct characteristic of Temporal action recognition. Proposal generation aims to detect the start and end boundary of action instance in the untrimmed video. Earlier methods used sliding windows to generate proposals \cite{karaman2014fast}\cite{wang2014action}. Then some algorithms \cite{buch2017sst}\cite{gao2017turn}\cite{caba2016fast}\cite{escorcia2016daps} began to pre-define temporal duration and intervals of proposals, and evaluated them with multiple methods like recurrent neural network (RNN) and dictionary learning. Another popular method for proposal generation is TAG \cite{zhao2017temporal}, which utilized watershed algorithm to do the project. Though TAG can generate proposals with flexible boundaries and durations, it is lack of evaluation to these proposals. BSN \cite{lin2018bsn} has a good performance of generating proposals, which is benefit from its temporal convolution network. By generating a possibilities sequences and selecting candidate proposals, it can achieve a high recall. But a series of CNNs slow down the speed and speed make it difficult to be applied to practice. \textbf{Distributed deep learning} Because deep learning has a wide range of application, acceleration is significant to let it more widely to be used. Distributed deep learning, which is based on parallel computing, belongs to high performance computing and accelerate CNN by using more machines like GPUs. MapReduce\cite{dean2008mapreduce} was proposed by Google and dissemble compute into map and reduce, which divided compute into tow steps of Map and Reduce. But it has a strict requirement of consistency. To address the problem, Graphlab\cite{low2012distributed} used an abstract way like the image to communicate, which also lead to low scalability. Jeff Dean proposed Parameter-Server Framework (PS) \cite{dean2012large}, which uses a parameter server to store the newest weight parameters of CNN. When the number of GPUs increases, the efficient of PS will have a great decline because of the big communication. Video task is closed to real life and Applied in practice is its final goal. So besides accuracy, speed of methods is also an important indicator. Based on these, our method is superior to others in acceleration for temporal action proposal generation. \section{parallel computing acceleration} \subsection{classes of parallel computing} For training of the neural network, GPU is a much faster platform than CPU because of its architectural advantage on matrix computation. So we used GPU as the computing platform for our temporal network. Further, we applied parallel computing based on GPU to accelerate our network for more powerful capabilities of processing video. The hard architecture of GPU is shown as Fig. \ref{gpu-architecture}. Stream Processor (SP) is the basic computing unit of GPU and Stream Multiprocessor (SM) is composed of a certain number of SM, register, share memory and L1/L2 cache. From the picture, we can see that one SM contains multiple SP but only one instruction unit. So for single SM, it only supports single instruction multiple data (SIMD) but not multiple instruction multiple data (MIMD). When GPUs are used to train CNN models, parameters of models are stored at device memory, which decided that the form of parallel computing of GPU in deep learning field is SIMD. After determining SIMD, the parallel architecture of GPU can be divided into two classes of model parallelism and data parallelism. \begin{figure}[ht] \centering \includegraphics[width=0.45\textwidth]{figure/gpu-architecture.png} \caption{Hard architecture of GPU} \label{gpu-architecture} \end{figure} \subsection{model parallelism} Model parallelism means different machines (GPU or CPU) in a distributed system are responsible for different parts of a network model. For example, different layers in a neural network model or different parameters in the same layer are assigned to different machines. The structure of model parallelism is shown as Fig. \ref{model_parallelism}. In general, the reason for applying model parallelism is oversized for the neural network so that single GPU cannot load the whole model. \begin{figure}[ht] \centering \includegraphics[width=0.2\textwidth]{figure/model_parallelism.png} \caption{Model parallelism} \label{model_parallelism} \end{figure} \subsection{data parallelism} Data parallelism means the input data are divided into several parts and delivered to different machines. There is a complete model in each machine and these machines run the same program to deal with allocated data. Training CNN is a serial process, i.e., only after computing the gradients for current data and upgrading parameter weights, the next data can be put into the machine. The key of model parallelism is that all of GPUs have the same CNN model, which we called them model replicas. But the data for each GPU is different. We integrate different weight gradients $\nabla w$ calculated by all of GPUs and upgrade parameters of the model. With its simple and understandable structure, Parameter Server (PS) becomes the main data parallelism framework and got support from some mainstream deep learning framework like TensorFlow \cite{abadi2016tensorflow}. The architecture of PS is shown as Fig. \ref{data-parallelism}, where $\Delta w$ is the weight gradients computed by model replicas like GPUs and $w'$ is the newest weight parameters. PS stores the parameters of the model. Model replicas compute different parameter weights and then upgrade the parameters in the parameter server. \begin{figure}[ht] \centering \includegraphics[width=0.45\textwidth]{figure/data-parallelism.png} \caption{Parameter Server framework} \label{data-parallelism} \end{figure} \subsection{ring parallel architecture} From Fig. \ref{data-parallelism} we can see that the communications volumes increase linearly with the increasing number of GPUs. We suppose the size of CNN model is $M$ and $N$ GPUs are used in our distributed system, so the communications volume is $N\cdot M$. If the number of GPUs achieved a high level, the large communications volume will greatly limit the training speed of CNN model. To address the problem of large communication volume in distributed deep learning system, we proposed ring parallel architecture. By building communication between GPUs with Message Passing Interface (MPI), our ring parallel architecture can reduce the pressure of communication. The ring parallel architecture is shown as Fig. \ref{Ring-architecture}. We changed the parallel topology to ring and averaged the communications volumes. The ring architecture upgrades weights through two steps including scatter and gather. \begin{figure}[ht] \centering \includegraphics[width=0.28\textwidth]{figure/Ring-architecture.png} \caption{Ring parallel architecture. Multiple colors denote the weight gradient computed by each GPU is different.} \label{Ring-architecture} \end{figure} \subsubsection{scatter} We divide weights in every GPU into $N$ parts, where $N$ is the number of GPU utilized in the architecture. After all of GPUs got different weight gradients by computing different input data, like there are different colors in Fig. \ref{Ring-architecture} and a row of colored blocks denotes a part. The $n$-th GPU passes its own $(n-i)\%N$-th block of weight gradients to its right neighbor and receives $(n-i-1)\%N$-th block of weight gradients from its left neighbor, where $i$ is the round of scatter. Fig. \ref{ring-process} shows the detail after one round of scatter. \begin{figure}[ht] \centering \includegraphics[width=0.28\textwidth]{figure/ring_process.png} \caption{Scatter. In the scatter step, the GPU passes a row of weight gradient (all of the colors in this row) to the same position in its next GPU.} \label{ring-process} \end{figure} After $N-1$ rounds of scatter, $n$-th GPU has collected $(n+1)\%N$-th block of weight gradients from all GPUs, which is shown as Fig. \ref{scatter-reduce}. After scatter, each GPU has a block of gradients which is from all GPUs. \begin{figure}[ht] \centering \includegraphics[width=0.28\textwidth]{figure/scatter-reduce.png} \caption{Distribution of weight gradients after scatter. There is a row in every GPU that has collected weight gradients from all of GPUs (all of the colors).} \label{scatter-reduce} \end{figure} \subsubsection{gather} Like scatter, GPUs also pass a block of weight gradients to the next GPU in the process of gather. Through $N-1$ rounds of gather, the $(n+1)\%N$-th block of weight gradients in the $n$-th GPU is passed to all of other GPUs. In the $i$-th round of gather, the $n$-th GPU passes its own $(n-i-1)\%N$-th blocks of weight gradients to its right neighbor and receives the $(n-i-2)\%N$-th blocks of weight gradients from its left neighbor. Different from scatter, GPUs don't need to add but replace its own block by the block received. After gather, we can see that all of GPUs have obtained all weight gradients computed by every GPU, which is shown as Fig. \ref{all-gather}. \begin{figure}[ht] \centering \includegraphics[width=0.28\textwidth]{figure/all-gather.png} \caption{Distribution of weight gradients after gather. All of the weight gradients are merged in each GPU.} \label{all-gather} \end{figure} \subsection{training time metrics} To explore the relationship between the number of GPUs and training time and evaluate parallel architecture, we defined training time metrics $T(n)$, where $n$ is the number of GPU used. Training time in distributed deep learning system could consist of three parts:(1) $t_1$ for forward propagation and backward propagation of single GPU; (2) $t_2$ for communication of weight gradients between GPUs or between GPU and CPU; (3) $t_3$ for preparation before training process and finishing work after training. For Parameter Server framework, $t_1$ is inversely proportional to the number $n$ of GPUs used. $t_2$ is proportional to the number $n$ of GPUs and $t_3$ has nothing to do with $n$. So the training time metrics for PS framework $T_{PS}(n)$ is shown as below: \begin{equation} t=\frac{T}{n}+C \cdot n+P, \ n=2,3,\dots \label{ps-time} \end{equation} Where $T$ is the training time with using single GPU, $C$ is the communication time and $P$ is the preparation time for opening and closing deep learning platform. For our ring parallel architecture, $t_1$ is also inversely proportional to the number of $n$ of GPUs used. Let the size of $\Delta w$ in each GPU is $K$, single GPU send $\frac{K}{n}$ to his right neighbor each round. Every GPU do $n-1$ rounds of scatter and $n-1$ rounds of gather, so the total communication volume is $2K\cdot \frac{n-1}{n}$. Then we can get that $t_2$ is proportional to $\frac{n-1}{n}$. And $t_3$ is also a constant. So the training time metrics for ring parallel framework $T_{Ring}(n)$ is shown as below: \begin{equation} t=\frac{T}{n}+C\cdot \frac{n}{n-1}+P, \ n=2,3,\dots \label{ring-time} \end{equation} For a distribute deep learning system, especially a large system, total time consumption $t$ depends largely on the csommunication time $t_2$. The most difference between these two training time metrics is $t_2$. As the number of GPUs $n$ increases, $t_2$ in ring parallel architecture will be smaller than PS framework. \section{experiments} \textbf{Dataset. ActivityNet-1.3} \cite{caba2015activitynet} is a normal video dataset for the temporal action proposal generation task. It contains 19994 untrimmed videos containing 200 classes of action instance and corresponding annotations. each untrimmed video includes one or more action instances. ActivityNet-1.3 is divided into training set, test set and validation set in a ratio of approximately 2:1:1. In this part, we will compare the performance of various commonly used methods for temporal action detection on ActivityNet-1.3. \textbf{Temporal action proposal generation.} For lots of tasks in video analysis, they do not handle video directly but deal with video feature sequence. Video feature sequence is usually encoded by neural network with special structure. In this paper, we used two-stream network \cite{simonyan2014two} as an encoder to transfer video into a set of vectors. \textbf{Implementation details.} Two-stream network \cite{simonyan2014two} whose temporal network is BN-Inception \cite{ioffe2015batch} and spacial network is ResNet \cite{he2016deep} is used to encode videos and generate video feature sequences. Then Boundary Sensitive Network (BSN) shown in Fig. \ref{network}(b) deals with these video sequences and produces final action proposals. We used both Parameter Server and Ring Architecture to run temporal action proposal generation task and compare their time consumption. We implement our distributed neural network with TensorFlow \cite{abadi2016tensorflow}. Our parallel computing platform are equipped with 8 TITAN V-100 GPUs. Because of occupying huge memory and a large number of video files, distributed deep learning is indispensable for applying temporal action detection algorithm to the actual. Based on that the inefficient of the traditional PS framework on distributed deep learning, we applied parallel ring architecture to our temporal convolution network and received a good result. The speed ratio with these two parallel frameworks is shown as Fig. \ref{parallel_architecture_compare}. In the figure, $Speed ratio = t_0/t$, where $t_0$ is the time cost with single GPU. As the number of GPU increases, the performance of parallel ring architecture is getting better and better than PS architecture. \begin{figure}[ht] \centering \includegraphics[width=0.45\textwidth]{figure/parallel_architecture_compare.png} \caption{Comparison of speed ratio between PS and parallel ring architecture} \label{parallel_architecture_compare} \end{figure} The reason for efficiency improve of Ring Architecture is the decrease of communication volume, which is obvious. To further explore the relationship between the number of GPUs and training time, we defined training time function $T(n)$, where $n$ is the number of GPU used. In order to test the validation of our training time metrics, we use the number of GPUs used, $n$, as the independent variable and the training time as the dependent variable to fit the Eq. \ref{ps-time}. The fitting curve is shown in Fig. \ref{ps-curve-fit} and we can get that $T=4223.8, C=12.1, P=290.8$. \begin{figure}[htpb] \centering \subfigure[Parameter Server architecture] { \label{ps-curve-fit} \includegraphics[width=0.8\columnwidth]{figure/ps-curve-fit.png} } \subfigure[Parallel ring architecture] { \label{ring-curve-fit} \includegraphics[width=0.8\columnwidth]{figure/ring-curve-fit.png} } \caption{Fitting curve of training time function} \label{curve_fit} \end{figure} If we use the same training time metrics \ref{ps-time} to fit the training time with using parallel ring architecture, we would get the result of $C=-3.8<0$, which is obviously unreasonable. The fitting curve for ring parallel architecture with using Eq. \ref{ring-time} is shown in Fig. \ref{ring-curve-fit} and we can get that $T=4400.1, C=59.6, P=363.5$. The parameter $C$ is much bigger in parallel ring architecture than it in PS, which indicates that parallel ring architecture is lower than PS in transfer speed. But if the number of GPUs increases to a obvious level, especially in large scale deep learning like some video task, parallel ring architecture will be a better choice than Parameter Server framework. \section{conclusion} In this paper, we applied a new parallel architecture, ring parallel architecture, to accelerate our network by reducing the pressure of communication. Our method have a higher acceleration efficiency compared with other state-of-art proposal generation methods, which is significant for dealing with large-scale video database in industrial filed. And we also proposed metrics to evaluate the time consumption of an distributed deep learning system and proved its effectiveness. \bibliographystyle{IEEEtran} \section{Introduction} With the rapid development of the Internet and camera, the number of videos is increasing at a very high speed. There are millions of video submissions on video-sharing websites like YouTube every day. Besides, the video surveillance system plays an important role in maintaining security \cite{8253857}\cite{8733112}\cite{wang2018generative}. These video files contain a lot of information for human, such as time duration and action classify\cite{8709763}\cite{wang2019aed}. How to make full use of videos is an indispensable step for building a smart city. It is vital for the development of information age to extract information from a large number of videos by automatically. Action is the most important information for videos because the essence of the video is recording varieties of motion. So a significant branch of video task is action recognition, which aims to recognize the class of action from a trimmed video. But the task is limited because its research object is videos that have been manually trimmed and only contain single action. The majority of videos in the real world are untrimmed videos and contains multiple action instances in a single video. The problem requires another challenging task: temporal action detection, which aims to recognize the temporal boundaries and classes of action instance from untrimmed videos. Temporal action detection usually includes two steps: proposal and classification. Proposal stage focuses on detecting action boundary and generating action instance with untrimmed video. Classification is aim to recognize the class of action instance produced in the previous step. For the task of temporal action detection, classification has achieved high accuracy. And the speed and precision of proposals is the main factor limiting temporal action detection \cite{caba2015activitynet}\cite{jiang2014thumos}. High-quality proposals should meet two requirements \cite{lin2018bsn}: (1) high recall; (2) high overlap with ground truth. And a good algorithm of generating proposal should not only generate excellent proposals, but its speed should be as fast as possible. Because videos occupy a large amount of memory, we must improve the speed of method so for being applied to practice. \begin{figure*}[ht] \centering \includegraphics[width=0.9\textwidth]{figure/network.png} \caption{The framework of our approach. (a) Two-stream network is used to encode visual features in snippet-level. (b) The architecture of Boundary Sensitive Network} \label{network} \end{figure*} Most proposal generation methods generate proposals by using sliding windows \cite{buch2017sst}\cite{caba2016fast}\cite{escorcia2016daps}\cite{shou2016temporal}. But the pre-defined durations and intervals of sliding windows cannot generate proposals with flexible length, which greatly reduced the precision of proposals. Boundary Sensitive Network (BSN) \cite{lin2018bsn} used a temporal network with 3 convolution layers to deal with video feature sequences and could generate proposals with flexible duration. Though BSN has a good performance, its multiple steps and networks make the speed not optimistic. Recently, lots of high performance computing methods are introduced into the field of compute vision for acceleration. Distributed computing is one of the more common methods. It is committed to increasing the number of devices in exchange for speeded-up. Parameter Server is a famous acceleration method for training deep learning network. On this framework, Multiple workers compute different input data and central server integrates the outputs from workers, which is very simple and effective. But when the number of workers has continuous growth, which leads to a significant increase in communication volume, acceleration will get worse. To address these problems and improve the speed of producing proposals, we designed a new parallel computing framework. Because BSN is the state-of-art method for temporal action proposal generation, so our new framework was tested on BSN and had a higher efficiency compared to the popular Parameter-Server Framework\cite{dean2012large}. In summary, the main contribution of our work is two-fold: \begin{enumerate} \renewcommand{\labelenumi}{(\theenumi)} \item We build a new parallel computing framework to speed up temporal convolution network on temporal action recognition with high efficiency. \item A metric is put forward to evaluate the time consumption in the distributed deep learning field. \end{enumerate} \section{Related work} Temporal action detection aims to detect action instances from the untrimmed video. The task could be divided into two steps: proposal and classification. Though some methods do the two steps at the same time, the majority of methods take the task as a serial process and finish proposal and classification separately. \textbf{Temporal action proposal generation.} Proposal generation is the distinct characteristic of Temporal action recognition. Proposal generation aims to detect the start and end boundary of action instance in the untrimmed video. Earlier methods used sliding windows to generate proposals \cite{karaman2014fast}\cite{wang2014action}. Then some algorithms \cite{buch2017sst}\cite{gao2017turn}\cite{caba2016fast}\cite{escorcia2016daps} began to pre-define temporal duration and intervals of proposals, and evaluated them with multiple methods like recurrent neural network (RNN) and dictionary learning. Another popular method for proposal generation is TAG \cite{zhao2017temporal}, which utilized watershed algorithm to do the project. Though TAG can generate proposals with flexible boundaries and durations, it is lack of evaluation to these proposals. BSN \cite{lin2018bsn} has a good performance of generating proposals, which is benefit from its temporal convolution network. By generating a possibilities sequences and selecting candidate proposals, it can achieve a high recall. But a series of CNNs slow down the speed and speed make it difficult to be applied to practice. \textbf{Distributed deep learning} Because deep learning has a wide range of application, acceleration is significant to let it more widely to be used. Distributed deep learning, which is based on parallel computing, belongs to high performance computing and accelerate CNN by using more machines like GPUs. MapReduce\cite{dean2008mapreduce} was proposed by Google and dissemble compute into map and reduce, which divided compute into tow steps of Map and Reduce. But it has a strict requirement of consistency. To address the problem, Graphlab\cite{low2012distributed} used an abstract way like the image to communicate, which also lead to low scalability. Jeff Dean proposed Parameter-Server Framework (PS) \cite{dean2012large}, which uses a parameter server to store the newest weight parameters of CNN. When the number of GPUs increases, the efficient of PS will have a great decline because of the big communication. Video task is closed to real life and Applied in practice is its final goal. So besides accuracy, speed of methods is also an important indicator. Based on these, our method is superior to others in acceleration for temporal action proposal generation. \section{parallel computing acceleration} \subsection{classes of parallel computing} For training of the neural network, GPU is a much faster platform than CPU because of its architectural advantage on matrix computation. So we used GPU as the computing platform for our temporal network. Further, we applied parallel computing based on GPU to accelerate our network for more powerful capabilities of processing video. The hard architecture of GPU is shown as Fig. \ref{gpu-architecture}. Stream Processor (SP) is the basic computing unit of GPU and Stream Multiprocessor (SM) is composed of a certain number of SM, register, share memory and L1/L2 cache. From the picture, we can see that one SM contains multiple SP but only one instruction unit. So for single SM, it only supports single instruction multiple data (SIMD) but not multiple instruction multiple data (MIMD). When GPUs are used to train CNN models, parameters of models are stored at device memory, which decided that the form of parallel computing of GPU in deep learning field is SIMD. After determining SIMD, the parallel architecture of GPU can be divided into two classes of model parallelism and data parallelism. \begin{figure}[ht] \centering \includegraphics[width=0.45\textwidth]{figure/gpu-architecture.png} \caption{Hard architecture of GPU} \label{gpu-architecture} \end{figure} \subsection{model parallelism} Model parallelism means different machines (GPU or CPU) in a distributed system are responsible for different parts of a network model. For example, different layers in a neural network model or different parameters in the same layer are assigned to different machines. The structure of model parallelism is shown as Fig. \ref{model_parallelism}. In general, the reason for applying model parallelism is oversized for the neural network so that single GPU cannot load the whole model. \begin{figure}[ht] \centering \includegraphics[width=0.2\textwidth]{figure/model_parallelism.png} \caption{Model parallelism} \label{model_parallelism} \end{figure} \subsection{data parallelism} Data parallelism means the input data are divided into several parts and delivered to different machines. There is a complete model in each machine and these machines run the same program to deal with allocated data. Training CNN is a serial process, i.e., only after computing the gradients for current data and upgrading parameter weights, the next data can be put into the machine. The key of model parallelism is that all of GPUs have the same CNN model, which we called them model replicas. But the data for each GPU is different. We integrate different weight gradients $\nabla w$ calculated by all of GPUs and upgrade parameters of the model. With its simple and understandable structure, Parameter Server (PS) becomes the main data parallelism framework and got support from some mainstream deep learning framework like TensorFlow \cite{abadi2016tensorflow}. The architecture of PS is shown as Fig. \ref{data-parallelism}, where $\Delta w$ is the weight gradients computed by model replicas like GPUs and $w'$ is the newest weight parameters. PS stores the parameters of the model. Model replicas compute different parameter weights and then upgrade the parameters in the parameter server. \begin{figure}[ht] \centering \includegraphics[width=0.45\textwidth]{figure/data-parallelism.png} \caption{Parameter Server framework} \label{data-parallelism} \end{figure} \subsection{ring parallel architecture} From Fig. \ref{data-parallelism} we can see that the communications volumes increase linearly with the increasing number of GPUs. We suppose the size of CNN model is $M$ and $N$ GPUs are used in our distributed system, so the communications volume is $N\cdot M$. If the number of GPUs achieved a high level, the large communications volume will greatly limit the training speed of CNN model. To address the problem of large communication volume in distributed deep learning system, we proposed ring parallel architecture. By building communication between GPUs with Message Passing Interface (MPI), our ring parallel architecture can reduce the pressure of communication. The ring parallel architecture is shown as Fig. \ref{Ring-architecture}. We changed the parallel topology to ring and averaged the communications volumes. The ring architecture upgrades weights through two steps including scatter and gather. \begin{figure}[ht] \centering \includegraphics[width=0.28\textwidth]{figure/Ring-architecture.png} \caption{Ring parallel architecture. Multiple colors denote the weight gradient computed by each GPU is different.} \label{Ring-architecture} \end{figure} \subsubsection{scatter} We divide weights in every GPU into $N$ parts, where $N$ is the number of GPU utilized in the architecture. After all of GPUs got different weight gradients by computing different input data, like there are different colors in Fig. \ref{Ring-architecture} and a row of colored blocks denotes a part. The $n$-th GPU passes its own $(n-i)\%N$-th block of weight gradients to its right neighbor and receives $(n-i-1)\%N$-th block of weight gradients from its left neighbor, where $i$ is the round of scatter. Fig. \ref{ring-process} shows the detail after one round of scatter. \begin{figure}[ht] \centering \includegraphics[width=0.28\textwidth]{figure/ring_process.png} \caption{Scatter. In the scatter step, the GPU passes a row of weight gradient (all of the colors in this row) to the same position in its next GPU.} \label{ring-process} \end{figure} After $N-1$ rounds of scatter, $n$-th GPU has collected $(n+1)\%N$-th block of weight gradients from all GPUs, which is shown as Fig. \ref{scatter-reduce}. After scatter, each GPU has a block of gradients which is from all GPUs. \begin{figure}[ht] \centering \includegraphics[width=0.28\textwidth]{figure/scatter-reduce.png} \caption{Distribution of weight gradients after scatter. There is a row in every GPU that has collected weight gradients from all of GPUs (all of the colors).} \label{scatter-reduce} \end{figure} \subsubsection{gather} Like scatter, GPUs also pass a block of weight gradients to the next GPU in the process of gather. Through $N-1$ rounds of gather, the $(n+1)\%N$-th block of weight gradients in the $n$-th GPU is passed to all of other GPUs. In the $i$-th round of gather, the $n$-th GPU passes its own $(n-i-1)\%N$-th blocks of weight gradients to its right neighbor and receives the $(n-i-2)\%N$-th blocks of weight gradients from its left neighbor. Different from scatter, GPUs don't need to add but replace its own block by the block received. After gather, we can see that all of GPUs have obtained all weight gradients computed by every GPU, which is shown as Fig. \ref{all-gather}. \begin{figure}[ht] \centering \includegraphics[width=0.28\textwidth]{figure/all-gather.png} \caption{Distribution of weight gradients after gather. All of the weight gradients are merged in each GPU.} \label{all-gather} \end{figure} \subsection{training time metrics} To explore the relationship between the number of GPUs and training time and evaluate parallel architecture, we defined training time metrics $T(n)$, where $n$ is the number of GPU used. Training time in distributed deep learning system could consist of three parts:(1) $t_1$ for forward propagation and backward propagation of single GPU; (2) $t_2$ for communication of weight gradients between GPUs or between GPU and CPU; (3) $t_3$ for preparation before training process and finishing work after training. For Parameter Server framework, $t_1$ is inversely proportional to the number $n$ of GPUs used. $t_2$ is proportional to the number $n$ of GPUs and $t_3$ has nothing to do with $n$. So the training time metrics for PS framework $T_{PS}(n)$ is shown as below: \begin{equation} t=\frac{T}{n}+C \cdot n+P, \ n=2,3,\dots \label{ps-time} \end{equation} Where $T$ is the training time with using single GPU, $C$ is the communication time and $P$ is the preparation time for opening and closing deep learning platform. For our ring parallel architecture, $t_1$ is also inversely proportional to the number of $n$ of GPUs used. Let the size of $\Delta w$ in each GPU is $K$, single GPU send $\frac{K}{n}$ to his right neighbor each round. Every GPU do $n-1$ rounds of scatter and $n-1$ rounds of gather, so the total communication volume is $2K\cdot \frac{n-1}{n}$. Then we can get that $t_2$ is proportional to $\frac{n-1}{n}$. And $t_3$ is also a constant. So the training time metrics for ring parallel framework $T_{Ring}(n)$ is shown as below: \begin{equation} t=\frac{T}{n}+C\cdot \frac{n}{n-1}+P, \ n=2,3,\dots \label{ring-time} \end{equation} For a distribute deep learning system, especially a large system, total time consumption $t$ depends largely on the csommunication time $t_2$. The most difference between these two training time metrics is $t_2$. As the number of GPUs $n$ increases, $t_2$ in ring parallel architecture will be smaller than PS framework. \section{experiments} \textbf{Dataset. ActivityNet-1.3} \cite{caba2015activitynet} is a normal video dataset for the temporal action proposal generation task. It contains 19994 untrimmed videos containing 200 classes of action instance and corresponding annotations. each untrimmed video includes one or more action instances. ActivityNet-1.3 is divided into training set, test set and validation set in a ratio of approximately 2:1:1. In this part, we will compare the performance of various commonly used methods for temporal action detection on ActivityNet-1.3. \textbf{Temporal action proposal generation.} For lots of tasks in video analysis, they do not handle video directly but deal with video feature sequence. Video feature sequence is usually encoded by neural network with special structure. In this paper, we used two-stream network \cite{simonyan2014two} as an encoder to transfer video into a set of vectors. \textbf{Implementation details.} Two-stream network \cite{simonyan2014two} whose temporal network is BN-Inception \cite{ioffe2015batch} and spacial network is ResNet \cite{he2016deep} is used to encode videos and generate video feature sequences. Then Boundary Sensitive Network (BSN) shown in Fig. \ref{network}(b) deals with these video sequences and produces final action proposals. We used both Parameter Server and Ring Architecture to run temporal action proposal generation task and compare their time consumption. We implement our distributed neural network with TensorFlow \cite{abadi2016tensorflow}. Our parallel computing platform are equipped with 8 TITAN V-100 GPUs. Because of occupying huge memory and a large number of video files, distributed deep learning is indispensable for applying temporal action detection algorithm to the actual. Based on that the inefficient of the traditional PS framework on distributed deep learning, we applied parallel ring architecture to our temporal convolution network and received a good result. The speed ratio with these two parallel frameworks is shown as Fig. \ref{parallel_architecture_compare}. In the figure, $Speed ratio = t_0/t$, where $t_0$ is the time cost with single GPU. As the number of GPU increases, the performance of parallel ring architecture is getting better and better than PS architecture. \begin{figure}[ht] \centering \includegraphics[width=0.45\textwidth]{figure/parallel_architecture_compare.png} \caption{Comparison of speed ratio between PS and parallel ring architecture} \label{parallel_architecture_compare} \end{figure} The reason for efficiency improve of Ring Architecture is the decrease of communication volume, which is obvious. To further explore the relationship between the number of GPUs and training time, we defined training time function $T(n)$, where $n$ is the number of GPU used. In order to test the validation of our training time metrics, we use the number of GPUs used, $n$, as the independent variable and the training time as the dependent variable to fit the Eq. \ref{ps-time}. The fitting curve is shown in Fig. \ref{ps-curve-fit} and we can get that $T=4223.8, C=12.1, P=290.8$. \begin{figure}[htpb] \centering \subfigure[Parameter Server architecture] { \label{ps-curve-fit} \includegraphics[width=0.8\columnwidth]{figure/ps-curve-fit.png} } \subfigure[Parallel ring architecture] { \label{ring-curve-fit} \includegraphics[width=0.8\columnwidth]{figure/ring-curve-fit.png} } \caption{Fitting curve of training time function} \label{curve_fit} \end{figure} If we use the same training time metrics \ref{ps-time} to fit the training time with using parallel ring architecture, we would get the result of $C=-3.8<0$, which is obviously unreasonable. The fitting curve for ring parallel architecture with using Eq. \ref{ring-time} is shown in Fig. \ref{ring-curve-fit} and we can get that $T=4400.1, C=59.6, P=363.5$. The parameter $C$ is much bigger in parallel ring architecture than it in PS, which indicates that parallel ring architecture is lower than PS in transfer speed. But if the number of GPUs increases to a obvious level, especially in large scale deep learning like some video task, parallel ring architecture will be a better choice than Parameter Server framework. \section{conclusion} In this paper, we applied a new parallel architecture, ring parallel architecture, to accelerate our network by reducing the pressure of communication. Our method have a higher acceleration efficiency compared with other state-of-art proposal generation methods, which is significant for dealing with large-scale video database in industrial filed. And we also proposed metrics to evaluate the time consumption of an distributed deep learning system and proved its effectiveness. \bibliographystyle{IEEEtran}
{'timestamp': '2019-08-05T02:06:06', 'yymm': '1906', 'arxiv_id': '1906.06496', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06496'}
arxiv
\section*{Introduction} According to the statistical studies from Brazil's ministry for external commerce, between January and April 2019, Brazilian exports for the hides and skins reached US \$430 million ~\cite{brazil}. The Brazilian leather industry produced about 15 million ft$^2$ leather in the first four months of 2019, making it the second largest leather production country after China. On the other hand, India is one of the biggest global exporters of leather especially for footwear and garment products~\cite{india}. Figure~\ref{fig:leather_india} shows the statistical report for India's exported leather products (in US\$ million), for 2015-2018. It involves a complex series of treatments to turn hides into leather, which include soaking, pressing, shaving, trimming, dyeing, drying, finishing and selecting. To produce world-class, quality leather products, it must be ensured that the leather used is defect free. However, most leather pieces bear the marks of their natural origin, like insect bites, cuts, stains and wrinkles. The example of the defective images is shown in Figure~\ref{fig:defect}. These defects should be detected and removed during the filtering process. To date, the defect detection on leather still relies highly on trained human inspectors. It is not reliable and inconsistent as it is highly dependent on the experience of the individual. Furthermore, this kind task is repetitive, tedious and physically laborious. One could probably spend more time on tasks that require creativity and innovation. Therefore, an automated quality inspection on leather pieces with digital image processing is essential to assist the defect inspection procedure. However, in the literature, there are relatively few researchers from the computer vision field investigating this topic. \begin{figure}[t!] \centering \includegraphics[width=1\linewidth]{leather_india.eps} \caption{India's exports leather products (in US\$ million), for 2015-2018}\label{fig:leather_india} \end{figure} \begin{figure}[t!] \centering \includegraphics[width=1\linewidth]{defect.eps} \caption{Example of leather images: (a) no defect; and with the defects of (b) black line; (c) wrinkle; (d) cuts and (e) stain}\label{fig:defect} \end{figure} One of the approaches to implement the automation task is by using machine learning. Neural network technique allows a computer to behave like a human, particularly in learning and understanding the same way as humans do. Neural network is gaining a lot of attention in the recent years due to its superior performance. For example, this technology has been utilized in driverless cars, allowing the cars to automatically recognize a stop sign, or to determine the obstacles on the road. Concretely, neural network architectures can achieve state-of-the-art accuracy in many classification tasks and sometimes even exceed human-level performance, such as in speech recognition~\cite{xiong2018microsoft} and object recognition~\cite{he2016deep}. The neural network model is a set of algorithms and is usually trained by a large set of labeled data. It requires high-performance GPUs with parallel architecture to increase the computational speed. \begin{figure*}[t!] \centering \includegraphics[width=1\linewidth]{flow.eps} \caption{Flowchart of the leather defect classification using neural network}\label{fig:flow} \end{figure*} This paper attempts to propose an image processing technique for leather classification by employing the neural network method. The leather images are pre-processed using edge detection and block partition, before performing the feature extraction and classification with neural network. The overview of the proposed method is shown in Figure~\ref{fig:flow}. The rest of this paper is organized as follows: Section~\ref{sec:literature} discusses a brief review of related literature, followed by Section~\ref{sec:method} which describes the proposed method in detail. Next, Section~\ref{sec:results} summarizes the experimental results while the conclusion is drawn in Section~\ref{sec:conclusion}. \section{Literature Review} \label{sec:literature} One of the recent research about leather classification is presented by Bong et al.~\cite{bong2018vision}. They employed several image processing algorithms to extract the image features and identify the defect's position on the leather surface. The extracted features (i.e., color moments, color correlograms, Zernike moments, and texture) are evaluated on an SVM classifier. Total number of image samples collected are 2500, where 2000 are used as training data and 500 samples are used as the testing data. The testing accuracy in distinguishing the three types of defects (scars, scratches, pinholes) as well as also no defect is 98.8\%. However, such method requires camera environment to be setup and static for consistent leather images, and might be time consuming for finding best parameters for model training. Jawahar et al.~\cite{jawahar2014leather} proposed a wavelet transform to classify the leather images. They adopt the Wavelet Statistical Features (WSF) and Wavelet Co-occurrence Features (WCF)~\cite{jobanputra2004texture} as feature descriptors. There are a total of 700 leather images involved, including 500 defective and 200 non-defective samples. The dataset is partitioned into 2 parts, where 70\% is the train set and 30\% is the test set. A binary SVM with Gaussian kernel is exploited to differentiate the defective and non defective leather sample. The classification accuracy of WSF, WCF and WSF+WCF are 95.76\%, 96.12\% and 98.56\%, respectively. However, the description of the defect types is unknown as an obvious visualization of the defect is easier for analysis and classification. On the other hand, Pistori et al.~\cite{pistori2018defect} presented Gray-scale Coocurrence Matrix (GLCM)~\cite{jobanputra2004texture} to extract the features of the images. The dataset is elicited from 258 different pieces of raw hide and wet blue leather, and they contain 17 different defect types. For the experiment, four types of defects are chosen, namely, tick marks, brand marks made from hot iron, cuts and scabies. Ridge estimators and logistic regression are adopted to learn the normalized Gaussian radial basis functions. They are then clustered by SVM, Radial Basis Functions networks (RBF) and Nearest Neighbours (KNN) as classifiers. Among them, SVM achieved the best results: beyond 94\% by using 10$\times$10 window image size and 100\% when 40$\times$40 window size is considered. Another leather detection work is carried out by Pereira et al.~\cite{pereiraclassification}. A Pixel Intensity Analyzer (PIA) is employed as the feature descriptor with Extreme Learning Machines (ELM) as the classifier. It describes the entire process going from image acquisition to image pre-processing, features extraction and finally machine learning classification. However the paper did not describe the machine setup it used to run the experiment. The performance comparison might be different on different machines. Winiarti et al.~\cite{winiarti2018pre} aims to realise an automatic leather grading system. At this stage, it classifies the type of leather on tanning leather images. It uses the first seven layers of AlexNet to extract features from the images and then classifies the images using linear SVM. The proposed method performs better than using a hand-crafted feature extractor (colour moments + GLCM) combining with SVM classifier in term of its average accuracy, specificity, sensitivity, precision, and performance time. Our previous work~\cite{liong2019automatic} discusses the elicitation of the dataset in detail and locates the fly bite defect with a segmentation accuracy of 91\%. The experiment is examined on a relatively small dataset that only contains 584 images. In~\cite{liong2019integrated}, ANN is employed to extract features and classify the image. The input images are resized to 40$\times$40 and edge detection methods such as Canny, Prewitt, Sobel, Roberts, LoG and ApproxCanny are performed. The classification result is 82.5\% when the number of hidden neurons is set to 50. Note that there is a single hidden layer in their implementation. \section{Method Proposed}\label{sec:method} For the feature extractors, there exists handcrafted methods (i.e., statistical features) and neural network approaches (i.e., AlexNet architecture). We propose a method using both the Convolutional Neural Network (CNN) and ANN as the feature extractors and classifiers to differentiate the defective/ non-defective leather images. The details are described in the subsections: Section~\ref{sec:ANN} to explain about ANN approach, and Section~\ref{sec:CNN} to elaborate CNN method. \subsection{Dataset} A new dataset is created by collecting the leather images using a six-axis articulated robot DRV70L Delta. To avoid the flicker caused by the fluorescent lights, a professional lighting source is used, when capturing the images using a DSLR camera. The amount of the data collected is 1897 images, where each of them are 400$\times$400 pixels. There are 370 images containing the fly bite defect and the rest are non-defective. The sample images are shown in Figure~\ref{fig:sample}. More information about the elicitation of the dataset can be found in~\cite{liong2019automatic, liong2019integrated}. \begin{figure}[t!] \centering \includegraphics[width=1\linewidth]{sample.eps} \caption{The sample of leather images, that has (a) defect and (b) no defect}\label{fig:sample} \end{figure} \subsection{Artificial Neural Network}\label{sec:ANN} A few image pre-processing techniques are applied on the leather images prior to passing them into the ANN for feature extraction. \subsubsection{Data Pre-processing} All the images are put through four pre-processing steps, namely, RGB to grayscale, re-sizing, edge detection and block partition. These steps are to enhance the visibility of defective regions in the images. Succinctly, the original images have a resolution of 400 $\times$ 400 $\times$ 3. They are first converted to grayscale, therefore becoming 400 $\times$ 400 $\times$ 1. Next, the images are re-sized to 50 $\times$ 50 pixels. There are several options for edge detection methods, such as Sobel, Prewitt, Roberts and Canny. The edge detector that can display the leather defect most clearly is the Canny operator. By adjusting the threshold values of the operator, different effects are obtained, as illustrated in Figure~\ref{fig:canny}. Finally, each image is divided into 5$\times$5 blocks, as shown in Figure~\ref{fig:block}. Since the pixel intensity of each image is either 0 or 255, the frequency of occurrence of pixel values are calculated. Thus, each block of the image will form 2 values and each image has 50 feature vectors. \begin{figure}[t!] \centering \includegraphics[width=1\linewidth]{canny.eps} \caption{After processing the leather image of Canny edge detection with the threshold range of (a) [0, 1], (b) [0.2, 0.9] and (c) [0.5, 0.9] }\label{fig:canny} \end{figure} \begin{figure}[t!] \centering \includegraphics[width=0.8\linewidth]{block.eps} \caption{The image is partitioned into 5$\times$5 blocks}\label{fig:block} \end{figure} \subsubsection{Feature Extraction using ANN} ANN consists of an interconnected group of nodes that link the three basic layers of neurons. Classically, the layers include input, hidden and output. Each ANN has one input layer, one output layer and may include more than one hidden layer. The neurons derive a unique pattern from the image and make decisions based on the extracted features. The number of neurons in the input layer in this study is fixed to 50 and there is one neuron in the output layer (i.e., either 0/1, which is defect/ no defect). \subsubsection{Experiment Configuration for ANN} The data is split to three sets: training, validation and testing. This is to ensure that there is no overlapping of the images. The training samples are fed into the architecture to adjust the parameters (i.e, weights and biases) to best describe the features of the input data. Validation samples give clues regarding the network generalization to prevent the architecture from overfitting or underfitting. The testing samples are to evaluate the classification performance of the unseen input data to examine the robustness of the trained architecture. Concisely, among the 1897 images, 60\% of them (1138 samples) are allocated for training, 5\% (95 samples) is the validation set and 35\% (664) is the testing set. The example of the ANN is shown in Figure~\ref{fig:ann}. \begin{figure}[t!] \centering \includegraphics[width=0.7\linewidth]{ann.eps} \caption{Example of Artificial Neural Network with one input, hidden and output layer, respectively.}\label{fig:ann} \end{figure} \subsection{Convolutional Neural Network}\label{sec:CNN} As CNN is capable to extract low-level features (i.e., lines, edges, curves), mid-level features (i.e., circles, squares) and high-level features (shapes and objects). The images are pre-processed by simply performing a resize operation. \subsubsection{Data Pre-processing} To reduce the computational speed while maintaining the image quality, we attempt to decrease the spatial resolution of the original image. Concretely, the images are resize to 50$\times$50$\times$3, 100$\times$100$\times$3, 150$\times$150$\times$3 and 200$\times$200$\times$3, from the original size of 400$\times$400$\times$3. Due to the distribution of the image dataset is imbalance, we build three sub-datasets by randomly selecting the images from the image collected. Concisely, there will be 1:1, 1:2 and 1:3 ratios for the defective:non-defective images, respectively. We further remove the images that are irrelevant to the fly bites defect, such as the images with wrinkles, stains and some blur images. As a result, the remaining amount of defective images left is 233. Next, the images are categorized to ``bright" and ``dark" groups. They are distinguished by the sum of the pixel intensity values in the image. For instance, if more than 70\% of the pixels in an image are greater than the intensity value of 125, it is defined as ``bright" image; otherwise it is the ``dark" image. Consequently, there are 92 and 141 defective images that are bright and dark, respectively. \subsubsection{Feature Extraction using CNN} A pre-trained neural network (i.e., AlexNet) is utilized with slight modification. The details structure of the modified AlexNet architecture is tabulated in Table~\ref{table:alex}, for the input image of 150$\times$150$\times$3. Basically, the architecture comprised of five types of operation: convolution, ReLU, pooling, fully connected and dropout: \begin{enumerate} \item Convolution: The image performs a dot product between a kernel/ weight and the local regions of the image. This step can achieve blurring, sharpening, edge detection, noise reduction effect. \item ReLU: An element-wise activation function is applied as thresholding a technique, such as $max(0,x)$. This is to eliminate the neurons that are playing vital role in in discriminating the input and is essentially meaningless. \item Pooling: To downsample the image along the spatial dimensions (i.e., width and height). This allows dimension reduction and enables the computation process to be less intensive. \item Fully connected: All the previous layer and next layer of neurons are linked. It acts like a classifier based on the features from previous layer. \item Dropout: The neurons are randomly dropped out during the training phase. This can avoid the overfitting phenomena and enhance the the generalization of the neural network trained. \end{enumerate} Specifically, the parameters of the input and output layers are changed, while the other layers remain the same. \subsubsection{Experiment Configuration for CNN} Since the dataset to be evaluated in this section is lesser compared to ANN. A conventional machine learning approach is employed, viz., k-fold cross-validation (CV). The general procedure of implementing the k-fold CV is: (1) The dataset is shuffled randomly; (2) The dataset is then split into k subsets; (3) A subset is selected as the test set, whereas the rest are the training sets; (4) The model is trained on the training set and evaluate om the test set; (5) The evaluation score is recorded and the model trained is discarded; (6) Steps 3 to 5 is repeated; (7) All the k sets of evaluation scores are summarized to form the final classification accuracy. Particularly, we fix the value of k to 10 in the experiment. \begin{table*}[tb] \begin{center} \caption{Modified AlexNet architecture for leather defect classification} \label{table:alex} \begin{tabular}{lccccccc} \noalign{\smallskip} \hline \noalign{\smallskip} Layer & Filter/ pool size & \# filter & Stride & Padding & Channel/ element & \% & Output size \\ \hline \noalign{\smallskip} Input image & - & - & - & - & - & - & 150 $\times$ 150 $\times$ 3 \\ \noalign{\smallskip} Convolution 1 & 11 $\times$ 11$\times$ 3 & 96 & [4, 4] & [0, 0, 0, 0] & - & - & 35 $\times$ 35 $\times$ 96 \\ \noalign{\smallskip} ReLU 1 & - & - & - & - & - & - & 35 $\times$ 35 $\times$ 96 \\ \noalign{\smallskip} Normalization 1 & - & - & - & - & 5 & - & 35 $\times$ 35 $\times$ 96 \\ \noalign{\smallskip} Pooling 1 & 3 $\times$ 3 & - & [2, 2] & [0, 0, 0, 0] & - & - & 17 $\times$ 17 $\times$ 96 \\ \noalign{\smallskip} Convolution 2 & 5 $\times$ 5$\times$ 48 & 256 & [1, 1] & [2, 2, 2, 2] & - & - & 17 $\times$ 17 $\times$ 256 \\ \noalign{\smallskip} ReLU 2 & - & - & - & - & - & - & 17 $\times$ 17 $\times$ 256 \\ \noalign{\smallskip} Normalization 2 & - & - & - & - & 5 & - & 17 $\times$ 17 $\times$ 256 \\ \noalign{\smallskip} Pooling 2 & 3 $\times$ 3 & - & [2, 2] & [0, 0, 0, 0] & - & - & 8 $\times$ 8 $\times$ 256 \\ \noalign{\smallskip} Convolution 3 & 3 $\times$ 3 $\times$ 256 & 384 & [1, 1] & [1, 1, 1, 1] & - & - & 8 $\times$ 8 $\times$ 384 \\ \noalign{\smallskip} ReLU 3 & - & - & - & - & - & - & 8 $\times$ 8 $\times$ 384 \\ \noalign{\smallskip} Convolution 4 & 3 $\times$ 3 $\times$ 192 & 384 & [1, 1] & [1, 1, 1, 1] & - & - & 8 $\times$ 8 $\times$ 384 \\ \noalign{\smallskip} ReLU 4 & - & - & - & - & - & - & 8 $\times$ 8 $\times$ 384 \\ \noalign{\smallskip} Convolution 5 & 3 $\times$ 3 $\times$ 192 & 256 & [1, 1] & [1, 1, 1, 1] & - & - & 8 $\times$ 8 $\times$ 256 \\ \noalign{\smallskip} ReLU 5 & - & - & - & - & - & - & 8 $\times$ 8 $\times$ 256 \\ \noalign{\smallskip} Pooling 5 & 3 $\times$ 3 & - & [2, 2] & [2, 2, 2, 2] & - & - & 5 $\times$ 5 $\times$ 256 \\ \noalign{\smallskip} Fully Connected 6 & 4096 $\times$ 6400 & - & - & - & - & - & 4096 $\times$ 1 \\ \noalign{\smallskip} ReLU 6 & - & - & - & - & - & - & 4096 $\times$ 1 \\ \noalign{\smallskip} Dropout 6 & - & - & - & - & - & 50 & 4096 $\times$ 1 \\ \noalign{\smallskip} Fully Connected 7 & 4096 $\times$ 4096 & - & - & - & - & - & 4096 $\times$ 1 \\ \noalign{\smallskip} ReLU 7 & - & - & - & - & - & - & 4096 $\times$ 1 \\ \noalign{\smallskip} Dropout 7 & - & - & - & - & - & 50 & 4096 $\times$ 1 \\ \noalign{\smallskip} Fully Connected 8 & 2 $\times$ 4096 & - & - & - & - & - & 2 $\times$ 1 \\ \noalign{\smallskip} Output & - & - & - & - & - & - & 2 $\times$ 1 \\ \hline \end{tabular} \end{center} \end{table*} \section{Results and Discussion} \label{sec:results} Since there are two methods evaluated on the dataset: ANN and CNN. We report and discuss both the classification performances in Section~\ref{sec:res_ANN} and Section~\ref{sec:res_CNN}. \subsection{Results for ANN} \label{sec:res_ANN} Several numbers of hidden neurons are tested (i.e., 10, 20, 50 and 100). The experimental results for the effectiveness of the pre-processing steps are presented in Table~\ref{table:result}. It can be observed that the performance after performing the edge detection and block division is higher. The edge detection employed here is Canny and the threshold is set to [0.5, 0.9]; this is because the defect in the image can be more obvious by using this range. The best classification result is 80.3\%, where the number of neurons in the hidden layer is 50. Within the range tested, good accuracy is consistently achieved when the number of hidden neurons is set to 50. The confusion matrix of the highest result is shown in Table~\ref{table:confusion}. It is noticed that there are imbalance issues in the test set, as the total number of defective samples is 9, where about one-third of them can be classified correctly. In contrast, there are 655 samples of non-defective images and most of them (more than 80\%) are distinguishable by the trained architecture. In addition, its ROC is reported in Figure~\ref{fig:roc}, which further indicates the severe imbalanced class distribution problem. \begin{table}[!tb] \caption{Classification results when varying neurons of hidden layer} \label{table:result} \centering \begin{tabular}{ccccc} \noalign{\smallskip} \cline{2-5} \noalign{\smallskip} & \multicolumn{4}{c}{Number of neuron} \\ \noalign{\smallskip} \cline{1-5} \noalign{\smallskip} Proposed Method & 10 & 20 & 50 & 100 \\ \noalign{\smallskip} \hline \noalign{\smallskip} W/o both edge detection \& block division & 78.0 & 79.2 & 80.2 & 79.5 \\ With edge detection \& w/o block division &79.2 & 78.5 & 80.0 & 78.8 \\ With both edge detection \& block division &78.6 & 78.8 & \bf 80.3 & 79.3 \\ \hline \end{tabular} \end{table} \begin{table}[!tb] \caption{Confusion matrix by adopting the ANN approach for the test set} \label{table:confusion} \centering \begin{tabular}{lcc} \noalign{\smallskip} \cline{1-3} \noalign{\smallskip} & Non-defective & Defective \\ \noalign{\smallskip} \hline \noalign{\smallskip} Non-defective & 530 & 125 \\ Defective & 6 & 3 \\ \hline \end{tabular} \end{table} \begin{figure}[t!] \centering \includegraphics[width=1\linewidth]{roc.eps} \caption{Receiver Operating Characteristic for the performance in training, validation and testing sets}\label{fig:roc} \end{figure} \subsection{Results for CNN}\label{sec:res_CNN} The images are carefully selected from the dataset collected before performing the evaluation using the modified AlexNet. The distribution of the data subsets is tabulated in Table~\ref{table:datadistribution}. For example, there will be a total of 932 ``bright+dark" images involved during the 10-fold CV for 1:3/ defective:non-defective case. In brief, 233 of them are defective images and 699 images have no defect. Among them, 10\% (i.e., 47) of the images are treated as the test set and 90\% (i.e., 419) are the training set. On the other hand, the minimum number of images for one of the cases is 184, which is when considering only the dark images for 1:1 case. The classification results are reported in Tables~\ref{table:cnn_11},~\ref{table:cnn_12} and ~\ref{table:cnn_13}, for the 1:1, 1:2 and 1:3 data subsets, respectively. The highest result obtained is 76.2\% in the bright images when epoch = 180 and resolution = 150$\times$150, in the 1:3 case. The lowest result attained is 50\%, which is as good as a chance, as there are only two target classes. It is in the 1:2 case, when epoch = 100 and resolution = 50$\times$50. It is observed that 50$\times$50 are always underperformed in most of the cases, compared to other input resolutions. There is a trend indicates that the classification accuracy is higher when the dataset is larger. For instance, the results in Table~\ref{table:cnn_11} (i.e., 1:1) is lower compared to Table~\ref{table:cnn_13} (i.e., 1:3). The epoch number set here is in the range of [100, 200], which is considered relatively small compared to general classification task. It implies that, with a slight fine-tuning on the architecture parameters (i.e., weights and biases) are sufficient to encode important features of the leather images. The confusion matrices for the highest results achieved in the 1:3 case for the ``bright+dark", ``bright" and ``dark" cases are reported in Tables~\ref{table:confusion_13_brightdark},~\ref{table:confusion_13_bright} and~\ref{table:confusion_13_dark}. It can be seen that the although the classification accuracy of Table~\ref{table:confusion_13_dark} reaches 74\%, the are $\sim$75\% (i.e., 69 out of 92 images) of the defective images are being predicted wrongly, whereas $\sim$90\% (i.e., 250 out of 276 images) non-defective images are correctly classified. \begin{table}[!tb] \caption{Data distribution for evaluation using modified AlexNet} \label{table:datadistribution} \centering \begin{tabular}{lccc} \noalign{\smallskip} \cline{2-4} \noalign{\smallskip} & \multicolumn{3}{c}{Defective: Non-defective} \\ \noalign{\smallskip} \hline \noalign{\smallskip} & 1:1 & 1:2 & 1:3 \\ \hline Bright + Dark & 233 : 233 & 233 : 466 & 233 : 699 \\ Bright & 141 : 141 & 141 : 282 & 141 : 423 \\ Dark & 92 : 92 & 92 : 184 & 92 : 276 \\ \hline \end{tabular} \end{table} \begin{table}[!tb] \caption{Classification results for 1:1 data subset when varying the epoch value using modified AlexNet} \label{table:cnn_11} \centering \begin{tabular}{cccccccc} \noalign{\smallskip} \cline{3-8} \noalign{\smallskip} & & \multicolumn{6}{c}{Epoch}\\ \noalign{\smallskip} \cline{2-8} \noalign{\smallskip} & Resolution & 100 & 120 & 140 & 160 & 180 & 200 \\ \noalign{\smallskip} \hline \noalign{\smallskip} \multirow{4}{*}{Bright + Dark} & 50$\times$50 & 58.1 & 58.5 & 59.2 & 58.3 & 58.7 & 58.3\\ & 100$\times$100 & 62.4 & 58.5 & 61.3 & 60.5 & 64.5 & 61.8 \\ & 150$\times$150 & 62.4 & 60.5 & 63.7 & 65.0 & 65.4 & \textbf{66.5}\\ & 200$\times$200 & 58.7 & 55.7 & 62.8 & 55.5 & 60.5 & 60.0\\ \noalign{\smallskip} \hline \noalign{\smallskip} \multirow{4}{*}{Bright} & 50$\times$50 & 53.1 & 53.5 & 53.1 & 53.9 & 57.8 & 59.5 \\ & 100$\times$100 & 65.6 & 66.3 & 64.1 & \textbf{67.0} & 66.3 & 65.6 \\ & 150$\times$150 & 61.3 & 62.4 & 64.1 & 63.1 & 65.9 & 63.4 \\ & 200$\times$200 & 59.9 & 59.2 & 62.4 & 59.5 & 58.5 & 59.2 \\ \noalign{\smallskip} \hline \noalign{\smallskip} \multirow{4}{*}{Dark} & 50$\times$50 & 53.8 & 50.5 & 57.6 & 54.3 & 51.6 & 54.3 \\ & 100$\times$100 & 61.4 & \textbf{64.1} & 58.6 & 59.2 & 61.9 & 63.5 \\ & 150$\times$150 & 56.5 & 61.9 & 61.4 & 60.8 & 61.4 & 63.5 \\ & 200$\times$200 & 54.8 & 54.8 & 57.0 & 57.0 & 53.8 & 53.8 \\ \noalign{\smallskip} \hline \end{tabular} \end{table} \begin{table}[!tb] \caption{Classification results for 1:2 data subset when varying the epoch value using modified AlexNet} \label{table:cnn_12} \centering \begin{tabular}{cccccccc} \noalign{\smallskip} \cline{3-8} \noalign{\smallskip} & & \multicolumn{6}{c}{Epoch}\\ \noalign{\smallskip} \cline{2-8} \noalign{\smallskip} & Resolution & 100 & 120 & 140 & 160 & 180 & 200 \\ \noalign{\smallskip} \hline \noalign{\smallskip} \multirow{4}{*}{Bright + Dark} & 50$\times$50 & 63.8 & 62.2 & 58.7 & 62.9 & 57.7 & 60.6 \\ & 100$\times$100 & 62.5 & 63.3 & 66.3 & 66.6 & 66.3 & 63.6 \\ & 150$\times$150 & 63.9 & 66.8 & 67.3 & 65.9 & \textbf{67.6} & 67.5 \\ & 200$\times$200 & 62.2 & 61.2 & 60.9 & 62.2 & 61.3 & 61.9 \\ \noalign{\smallskip} \hline \noalign{\smallskip} \multirow{4}{*}{Bright} & 50$\times$50 & 50.0 & 65.2 & 64.3 & 62.6 & 62.4 & 58.6 \\ & 100$\times$100 & 64.0 & 69.7 & 69.0 & 66.9 & 68.5 & 67.3 \\ & 150$\times$150 & 65.9 & 61.2 & 63.3 & 65.0 & 65.0 & 62.6 \\ & 200$\times$200 & \textbf{69.9} & 66.4 & 60.9 & 63.3 & 64.7 & 66.6 \\ \noalign{\smallskip} \hline \noalign{\smallskip} \multirow{4}{*}{Dark} & 50$\times$50 & 65.9 & 64.1 & 64.4 & 63.7 & 62.6 & 63.4 \\ & 100$\times$100 & 64.8 & 67.0 & 67.7 & 68.4 & \textbf{69.9} & 67.7 \\ & 150$\times$150 & 62.3 & 60.8 & 61.9 & 63.7 & 63.4 & 60.1 \\ & 200$\times$200 & 59.0 & 61.5 & 63.0 & 61.5 & 59.4 & 63.0 \\ \noalign{\smallskip} \hline \end{tabular} \end{table} \begin{table}[!tb] \caption{Classification results for 1:3 data subset when varying the epoch value using modified AlexNet} \label{table:cnn_13} \centering \begin{tabular}{cccccccc} \noalign{\smallskip} \cline{3-8} \noalign{\smallskip} & & \multicolumn{6}{c}{Epoch}\\ \noalign{\smallskip} \cline{2-8} \noalign{\smallskip} & Resolution & 100 & 120 & 140 & 160 & 180 & 200 \\ \noalign{\smallskip} \hline \noalign{\smallskip} \multirow{4}{*}{Bright + Dark} & 50$\times$50 & 72.6 & 68.6 & 68.7 & 65.3 & 66.6 & 68.0 \\ & 100$\times$100 & 67.7 & 71.6 & 72.3 & 72.2 & 71.8 & 73.4 \\ & 150$\times$150 & \textbf{74.0} & 72.0 & \textbf{74.0} & 71.6 & 71.1 & 73.1 \\ & 200$\times$200 & 68.4 & 70.2 & 70.1 & 70.1 & 71.2 & 70.6 \\ \noalign{\smallskip} \hline \noalign{\smallskip} \multirow{4}{*}{Bright} & 50$\times$50 & 75.0 & 74.1 & 71.4 & 70.0 & 64.3 & 63.4 \\ & 100$\times$100 & 74.8 & 74.2 & 72.5 & 67.0 & 68.2 & 65.6 \\ & 150$\times$150 & 71.4 & 72.8 & 73.7 & 74.4 & \textbf{76.2} & 75.1 \\ & 200$\times$200 & 73.4 & 73.5 & 73.5 & 74.6 & 73.4 & 75.1 \\ \noalign{\smallskip} \hline \noalign{\smallskip} \multirow{4}{*}{Dark} & 50$\times$50 & 75.0 & 72.2 & 69.5 & 67.9 & 67.3 & 67.6 \\ & 100$\times$100 & 67.6 & 69.8 & 72.5 & 73.6 & 72.2 & 70.9 \\ & 150$\times$150 & 72.5 & 66.8 & 69.8 & 70.9 & 70.6 & 69.5 \\ & 200$\times$200 & 73.3 & 68.2 & 70.9 & 72.8 & 73.3 & \textbf{74.1} \\ \noalign{\smallskip} \hline \end{tabular} \end{table} \begin{table}[!tb] \caption{Confusion matrix by adopting modified AlexNet for 1:3 ``bright+dark" data subset, when epoch=140 and resolution=150$\times$150}\label{table:confusion_13_brightdark} \centering \begin{tabular}{lcc} \noalign{\smallskip} \cline{1-3} \noalign{\smallskip} & Non-defective & Defective \\ \noalign{\smallskip} \hline \noalign{\smallskip} Non-defective & 616 & 83 \\ Defective & 159 & 74 \\ \hline \end{tabular} \end{table} \begin{table}[!tb] \caption{Confusion matrix by adopting modified AlexNet for 1:3 ``bright" data subset, when epoch=180 and resolution=150$\times$150}\label{table:confusion_13_bright} \centering \begin{tabular}{lcc} \noalign{\smallskip} \cline{1-3} \noalign{\smallskip} & Non-defective & Defective \\ \noalign{\smallskip} \hline \noalign{\smallskip} Non-defective & 381 & 42 \\ Defective & 92 & 49 \\ \hline \end{tabular} \end{table} \begin{table}[!tb] \caption{Confusion matrix by adopting modified AlexNet for 1:3 ``dark" data subset, when epoch=200 and resolution=200$\times$200}\label{table:confusion_13_dark} \centering \begin{tabular}{lcc} \noalign{\smallskip} \cline{1-3} \noalign{\smallskip} & Non-defective & Defective \\ \noalign{\smallskip} \hline \noalign{\smallskip} Non-defective & 250 & 26 \\ Defective & 69 & 23 \\ \hline \end{tabular} \end{table} \section{Conclusion}\label{sec:conclusion} This paper presents two neural network approaches to distinguish the defective and non-defective leather images: Artificial Neural Network (ANN) and Convolutional Neural Network (CNN). For ANN, there are four pre-processing steps involved before extracting the features from the images. They include RGB to grayscale, re-sizing, edge detection and block partitioning. All the images are put through these steps to improve their quality and to eliminate noise. Then, the images are passed to ANN to further select effective features to represent the image. Experimental results show that the proposed method achieves a promising classification accuracy of 80\%. On the other hand, for CNN, only good samples are selected for evaluation. To reduce the impact of data class imbalance issue, the dataset is reconstructed to form 1:1, 1:2, 1:3 data distributions for defective:non-defective images. As a result, the highest classification accuracy obtained is 76\% when the images is resized to more than half of the original size. The features are extracted using modified AlexNet with relatively few training epoch to fine-tune the weights and biases in the architecture. As future work, more defective leather samples can be added to the testing dataset in the experiment to avoid the feature extractor learns the features of one particular class. Moreover, the number of hidden neurons and the number of feature vectors in ANN can be increased to obtain more accurate results. Besides, popular pre-trained CNN models such as GoogLeNet, SqueezeNet, VGG-16, ResNet-101 can be employed to extract the important features of the image and hence generating higher classification results. \section*{Acknowledgments} This work was funded by Ministry of Science and Technology (MOST) (Grant Number: MOST 107-2218-E-035-016-), National Natural Science Foundation of China (No. 61772023) and Natural Science Foundation of Fujian Province (No. 2016J01320). \bibliographystyle{natlib}
{'timestamp': '2019-06-18T02:03:50', 'yymm': '1906', 'arxiv_id': '1906.06446', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06446'}
arxiv
\section{Introduction} Dependent types support the development of extremely reliable software. With the full power of higher-order logic, programmers can write expressive specifications as types, and be confident that if a program typechecks, then it meets its specification. Dependent types are at the core of proof assistants like Coq~\citep{coqart} and Agda~\citep{agdaPaper}. While these pure systems can be used for certified programming~\citep{cpdt}, their focus is on the construction of proofs, rather than practical or efficient code. \added{Dependently-typed extensions of practical programming languages maintain a clear phase distinction between compile-time typechecking and runtime execution, and have to embrace some compromise regarding impurity.} \rev{One possibility is to forbid potentially impure expressions from occurring in types, either by considering a separate pure sub-language of type-level computation as in Dependent ML~\citep{Xi1999}, by using an effect system and termination checker to prevent impurity to leak in type dependencies as in F$\star$~\cite{mumon} and Idris~\citep{idrisPaper}, or by explicitly separating the language into two fragments with controlled interactions between them, as in Zombie~\citep{EPTCS76.9, Casinghino:2014:CPP:2535838.2535883}. A radical alternative is to give up on decidable typechecking and logical consistency altogether and give all responsibility to the programmer, as in Dependent Haskell~\citep{eisenberg2016dependent}. The design space is wide, and practical dependently-typed programming is a fertile area of research. } As with any static type system, the reliability brought by dependent types comes at a cost. Dependently-typed languages impose a rigid discipline, sometimes requiring programmers to explicitly construct proofs in their programs. Because of this rigidity, dependent types can interfere with rapid prototyping, and migrating code from languages with simpler type systems can be difficult. Several approaches have been proposed to relax dependent typing in order to ease programming, for instance by supporting some form of interoperability between (possibly polymorphic) non-dependently-typed and dependently-typed programs and structures~\citep{10.1007/1-4020-8141-3_34,Osera:2012:DI:2103776.2103779, dagand_tabareau_tanter_2018,Tanter:2015:GCP:2816707.2816710}. These approaches require programmers to explicitly trigger runtime checks through casts, liftings, or block boundaries. Such explicit interventions hamper evolution. In contrast, gradual typing~\citep{gradualTypeInitial} exploits {\em type imprecision} to drive the interaction between static and dynamic checking in a smooth, continuous manner~\citep{refinedCriteria}. A gradual language introduces an unknown type $ {\qm } $, and admits imprecise types such as $ \ottkw{Nat} \to {\qm } $. The gradual type system optimistically handles imprecision, deferring to runtime checks where needed. Therefore, runtime checking is an {\em implicit} consequence of type imprecision, and is seamlessly adjusted as programmers evolve the declared types of components, be they modules, functions, or expressions. This paper extends gradual typing to provide a flexible incremental path to adopting dependent types. Gradual typing has been adapted to many other type disciplines, including ownership types~\citep{sergeyClarke:esop2012}, effects~\cite{banadosAl:jfp2016}, refinement types~\citep{lehmannTanter:popl2017}, security types~\citep{fennellThiemann:csf2013,toroAl:toplas2018}, and session types~\citep{igarashiAl:icfp2017b}. But it has not yet reached dependent types. Even as the idea holds much promise, it also poses significant challenges. The greatest barrier to gradual dependent types is that a dependent type checker must evaluate some program terms as part of type checking, and gradual types complicate this in two ways. First, if a gradual language fully embeds an untyped language, then some programs will diverge: indeed, self application $(\lambda \mathit{x} : {\qm } .x\; x)$ is typeable in such a language. Second, gradual languages introduce the possibility of type errors \added{that are uncovered as a term is evaluated}: applying the function $(\lambda \mathit{x} : {\qm } \ldotp \mathit{x} + 1 )$ may fail, depending on whether its argument \added{can actually be used as a} number. So a gradual dependently-typed language must account for the potential of non-termination and failure \textit{during typechecking}. \paragraph{{\bf A gradual dependently-typed language}} This work presents \lang, a gradual dependently-typed core language that supports the whole spectrum between an untyped functional language and a dependently-typed one. As such, \lang adopts a unified term and type language, meaning that the unknown type $ {\qm } $ is also a valid term. This allows programmers to specify types with imprecise indices, and to replace proof terms with $ {\qm } $ (\autoref{sec:motivation}). \lang is a gradual version of the predicative fragment of the Calculus of Constructions with a cumulative universe hierarchy ($\mathsf{CC}_\omega$) (\autoref{sec:staticlang}), similar to the core language of Idris~\citep{idrisPaper}. We gradualize this language following the Abstracting Gradual Typing (AGT) methodology~\citep{agt} (\autoref{sec:graduallang}). Because \lang is a {\em conservative extension} of this dependently-typed calculus, it is both strongly normalizing and logically consistent for fully static code. \rev{These strong properties are however lost as soon as imprecise types and/or terms are introduced.} On the dynamic side, \lang can fully embed the untyped lambda calculus. When writing purely untyped code, static type errors are never encountered. In between, \lang satisfies the {\em gradual guarantees} of \citet{refinedCriteria}, meaning that typing and evaluation are monotone with respect to type imprecision. These guarantees ensure that programmers can move code between imprecise and precise types in small, incremental steps, with the program typechecking and \added{behaving identically (modulo dynamic type errors)} at each step. \added{If a program fails to typecheck, the programmer knows the problem is not too few type annotations, but rather incompatible types.} \lang is a call-by-value language with a sharp two-phase distinction. The key technical insight on which \lang is built is to exploit two distinct notions of evaluation: one for {\em normalization} during typechecking, and one for {\em execution} at runtime. Specifically, we present a novel {\em approximate} normalization technique that guarantees decidable typechecking (\autoref{sec:gradualhsub}): applying a function of unknown type, which may trigger non-termination, normalizes to the {\em unknown value} $ {\qm} $. Consequently, some terms that would be distinct at runtime become indistinguishable as type indices. Approximation is also used to ensure that compile-time normalization (i.e. during typechecking) always terminates and never signals a ``dynamic error''. \added{In this sense, \lang is closer to Idris than Dependent Haskell, which does admit reduction errors and non-termination during typechecking.} At runtime, \lang uses the standard, precise runtime execution strategy of gradual languages, which may fail due to dynamic type errors, and may diverge as well (\autoref{sec:gradual-semantics}). \added{In that respect, \lang is closer to Dependent Haskell and Zombie than to Idris, which features a termination checker and a static effect system.} We prove that \lang has decidable typechecking and satisfies all the expected properties of gradual languages \citep{refinedCriteria}: type safety, conservative extension of the static language, embedding of the untyped language, and the gradual guarantees (\autoref{sec:lang-properties}). We then show how inductive types with eliminators can be added to \lang without significant changes (\autoref{sec:inductive}). \autoref{sec:related} discusses related work, and \autoref{sec:conclusion} discusses limitations and perspectives for future work. \paragraph{{\bf Disclaimer}} \rev{ This work does not aim to develop a full-fledged dependent gradual type theory, a fascinating objective that would raise many metatheoretic challenges. Rather, it proposes a novel technique, {\em approximate normalization}, applicable to \added{full-spectrum} dependently-typed programming languages. This technique reflects specific design choices that affect the pragmatics of programming and reasoning in \lang: we review these design decisions, after the informal presentation of the language, in \autoref{sec:choices}. Also, being a core calculus, \lang currently lacks several features expected of a practical dependently-typed language (\autoref{sec:conclusion}); nevertheless, this work provides a foundation on which practical gradual dependently-typed languages can be built. } {\bf \added{Implementation}.} \rev{ We provide a prototype implementation of \lang in Racket, based on a Redex model. The code for the implementation is open source~\citep{GDTL-github}. The implementation also supports our extension of natural numbers, vectors, and equality as built-in inductive types. } {\bf \added{Technical report}.} \rev{ Complete definitions and proofs can be found in \citep{eremondi2019approximate} }. \section{Goals and Challenges} \label{sec:motivation} We begin by motivating our goals for \lang, and describe the challenges and design choices that accompany them. \subsection{The Pain and Promise of Dependent Types} \label{subsec:vector} To introduce dependent types, we start with a classic example: length-indexed vectors. In a dependently-typed language, the type $ \ottkw{Vec} \ \mathtt{A} \ \mathtt{n} $ describes any vector that contains $\mathtt{n}$ elements of type $\mathtt{A}$. We say that $ \ottkw{Vec} $ is \textit{indexed} by the value $\mathtt{n}$. This type has two constructors, ${ \ottkw{Nil} : \ottsym{(} \mathtt{A} \ottsym{:} \rev{\ottkw{Type} } _{ \ottsym{1} } \ottsym{)} \rightarrow \ottkw{Vec} \ \mathtt{A} \ 0 }$ and ${\ottkw{Cons}: \ottsym{(} \mathtt{A} \ottsym{:} \rev{\ottkw{Type} } _{ \ottsym{1} } \ottsym{)} \rightarrow \ottsym{(} \mathtt{n} \ottsym{:} \ottkw{Nat} \ottsym{)} \rightarrow \mathtt{A} \to \ottkw{Vec} \ \mathtt{A} \ \mathtt{n} \to \ottkw{Vec} \ \mathtt{A} \ \ottsym{(} \mathtt{n} + 1 \ottsym{)} }$. By making length part of the type, we ensure that operations that are typically partial can only receive values for which they produce results. One can type a function that yields the first element of a vector as follows: $$ \ottkw{head}\ :\ \ottsym{(} \mathtt{A} \ottsym{:} \rev{\ottkw{Type} } _{ \ottsym{1} } \ottsym{)} \rightarrow \ottsym{(} \mathtt{n} \ottsym{:} \ottkw{Nat} \ottsym{)} \rightarrow \ottkw{Vec} \ \mathtt{A} \ \ottsym{(} \mathtt{n} + 1 \ottsym{)} \to \mathtt{A} $$ Since $\mathtt{head}$ takes a vector of non-zero length, \rev{it can never receive} an empty vector. The downside of this strong guarantee is that we can only use vectors in contexts where their length is known. This makes it difficult to migrate code from languages with weaker types, or for newcomers to prototype algorithms. For example, a programmer may wish to migrate the following quicksort algorithm into a dependently-typed language: \begin{align*} & \mathtt{sort} \ \mathtt{vec} \ =&&&& \ottkw{if}\ \mathtt{vec} == \ottkw{Nil}\ \ottkw{then}\ \ottkw{Nil}\ \ottkw{else} \\ &&&&& \qquad (\text{\texttt{sort (filter ($\leq$ (head vec)) (tail vec)))}}) \ \mathtt{++}\ \mathtt{head} \ \mathtt{vec} \\ &&&&& \qquad \ \mathtt{++}\ (\text{\texttt{sort (filter ($>$ (head vec)) (tail vec)))}}) \end{align*} \noindent Migrating this definition to a dependently-typed language poses some difficulties. The recursive calls are not direct deconstructions of $\mathtt{vec}$, so it takes work to convince the type system that the code will terminate, and is thus safe to run at compile time. Moreover, if we try to use this definition with $ \ottkw{Vec} $, we must account for how the length of each filtered list is unknown, and while we can prove that the length of the resulting list is the same as the input, this must be done manually. Alternately, we could use simply-typed lists in the dependently-typed language, but we do not wish to duplicate every vector function for lists. \subsection{Gradual Types to the Rescue?} Even at first glance, gradual typing seems like it can provide the desired flexibility. In a gradually-typed language, a programmer can use the unknown type, written $ {\qm } $, to soften the static typing discipline. Terms with type $ {\qm } $ can appear in any context. Runtime type checks ensure that dynamically-typed code does not violate invariants expressed with static types. Since $ {\qm } $ allows us to embed untyped code in a typed language, we can write a gradually-typed fixed-point combinator ${\mathsf{Z} : \ottsym{(} \mathtt{A} \ottsym{:} \rev{\ottkw{Type} } _{ \ottsym{1} } \ottsym{)} \rightarrow \ottsym{(} \mathtt{B} \ottsym{:} \rev{\ottkw{Type} } _{ \ottsym{1} } \ottsym{)} \rightarrow \ottsym{(} \ottsym{(} \mathtt{A} \to \mathtt{B} \ottsym{)} \to \mathtt{A} \to \mathtt{B} \ottsym{)} \to \mathtt{A} \to \mathtt{B} }$. \added{We define this in the same way as the usual $\mathsf{Z}$ combinator, but the input function is ascribed the type $\qm$, allowing for self-application.} Using this combinator, the programmer can write $\mathtt{sort}$ using general recursion. Furthermore, the programmer can give $\mathtt{sort}$ the type $ {\qm } \to {\qm } $, causing the length of the results of $\mathtt{filter}$ to be ignored in typechecking. Annotating the vector with $ {\qm } $ inserts runtime checks that ensure that the program will \rev{fail (rather than behave in an undefined manner)} if it is given an argument that is not a vector. However, introducing the dynamic type $ {\qm } $ in a dependently-typed language brings challenges. \paragraph{{\bf The unknown type is not enough}}If we assign $\mathtt{sort}$ the type $ {\qm } \to {\qm } $, then we can pass it any argument, whether it is a vector or not. This seems like overkill: we want to restrict $\mathtt{sort}$ to vectors and statically rule out nonsensical calls like $ \mathtt{sort} \ \mathtt{false} $. Unfortunately the usual notion of type imprecision is too coarse-grained to support this. We want to introduce imprecision more judiciously, as in $ \ottkw{Vec} \ \mathtt{A} \ {\qm } $: the type of vectors with \textit{unknown length}. But the length is a natural number, not a type. How can we express imprecision in type indices? \paragraph{{\bf Dependent types require proofs}} To seamlessly blend untyped and dependently-typed code, we want to let programs omit proof terms, yet still allow code to typecheck and run. But this goes further than imprecision in type indices, since imprecision also manifests in program terms. What should the dynamic semantics of imprecise programs be? \paragraph{{\bf Gradual typing introduces effects}} Adding $ {\qm } $ to types introduces two effects. The ability to type self-applications means programs may diverge, and the ability to write imprecise types introduces the possibility of type errors uncovered while evaluating terms. These effects are troubling because dependent typechecking must often evaluate code, sometimes under binders, to compare dependent types. We must normalize terms at compile time to compute the type of dependent function applications. This means that both effects can manifest \textit{during typechecking}. How should compile-time evaluation errors be handled? Can we make typechecking decidable in the presence of possible non-termination? \paragraph{{\bf Dependent types rely on equality}} The key reason for normalizing at compile time is that we must compare types, and since types can be indexed by terms, we need a method of comparing arbitrary terms. If we have $A : (\ottkw{Nat} \to \ottkw{Nat}) \to \rev{\ottkw{Type} } _1$, then $A\ (\lambda \mathit{x} \ldotp 1 + 1) $ and $A\ (\lambda \mathit{x} \ldotp 2) $ should be seen as the same type. In intensional type theories, like that of Coq, Agda and Idris, this is done using \textit{definitional equality}, which fully evaluates terms (even under binders) to determine whether their normal forms are \textit{syntactically} equal. Of course, this is a weaker notion than {\em propositional equality}, but typechecking with propositional equality (as found in {\em extensional} theories) is undecidable. In intensional theories, explicit rewriting must be used to exploit propositional equalities. In a gradual language, types are also compared \textit{at runtime} to compensate for imprecise static type information. With gradual dependent types, how should types (and the terms they contain) be compared at runtime? The simplest solution is to use the same notion of definitional equality as used for static typechecking. This has some unfortunate consequences, such as $A\ (\lambda \mathit{x} \ldotp x + x - x) $ and $A\ (\lambda \mathit{x} \ldotp x) $ being deemed inconsistent, even though they are clearly propositionally equal. However, mirroring compile-time typechecking at runtime simplifies reasoning about the language behavior. \subsection{GDTL in Action} \label{subsec:gdtl-action} To propagate imprecision to type indices, and soundly allow omission of proof terms, \lang admits $ {\qm } $ {\em both as a type and a term}. To manage effects due to gradual typing, we use separate notions of evaluation for compile-time and runtime. Introducing {\em imprecision in the compile-time normalization of types} avoids both non-termination and failures during typechecking. \paragraph{{\bf The unknown as a type index}} Since full-spectrum dependently-typed languages conflate types and terms, \lang allows $ {\qm } $ to be used as either a term or a type. Just as any term can have type $ {\qm } $, the term $ {\qm } $ can have any type. This lets dependent type checks be deferred to runtime. For example, we can define vectors $\mathtt{staticNil}$, $\mathtt{dynNil}$ and $\mathtt{dynCons}$ as follows: \begin{align*} &\mathtt{staticNil} : \ottkw{Vec} \ \ottkw{Nat} \ 0 && \mathtt{dynNil} : \ottkw{Vec} \ \ottkw{Nat} \ {\qm } \quad &&\mathtt{dynCons} : \ottkw{Vec} \ \ottkw{Nat} \ {\qm } \\ &\mathtt{staticNil} = \ottkw{Nil} \ \ottkw{Nat} && \mathtt{dynNil} = \ottkw{Nil} \ \ottkw{Nat} && \mathtt{dynCons} = \ottkw{Cons} \ \ottkw{Nat} \ 0 \ 0 \ \ottsym{(} \ottkw{Nil} \ \ottkw{Nat} \ottsym{)} \end{align*} \noindent Then, $\ottsym{(} \mathtt{head} \ \ottkw{Nat} \ 1 \ \mathtt{staticNil} \ottsym{)}$ does not typecheck, $\ottsym{(} \mathtt{head} \ \ottkw{Nat} \ 1 \ \mathtt{dynNil} \ottsym{)}$ typechecks but fails at runtime, and $\ottsym{(} \mathtt{head} \ \ottkw{Nat} \ 1 \ \mathtt{dynCons} \ottsym{)}$ typechecks and succeeds at runtime. The programmer can choose between compile-time or runtime checks, but \replaced{safety}{soundness} is maintained either way, and in the fully-static case, the unsafe code is still rejected. \paragraph{{\bf The unknown as a term at runtime}} Having $ {\qm } $ as a term means that programmers can use it to optimistically omit \textit{proof terms}. Indeed, terms can be used not only as type indices, but also as proofs of propositions. For example, consider \added{the equality type} $ \ottkw{Eq} : \ottsym{(} \mathtt{A} \ottsym{:} \rev{\ottkw{Type} } _{ \ottnt{i} } \ottsym{)} \rightarrow \mathtt{A} \to \mathtt{A} \to \rev{\ottkw{Type} } _{ \ottnt{i} } $, along with its lone constructor $ \ottkw{Refl} : \ottsym{(} \mathtt{A} \ottsym{:} \rev{\ottkw{Type} } _{ \ottnt{i} } \ottsym{)} \rightarrow \ottsym{(} \mathit{x} \ottsym{:} \mathtt{A} \ottsym{)} \rightarrow \ottkw{Eq} \ \mathtt{A} \ \mathit{x} \ \mathit{x} $. We can use these to write a (slightly contrived) formulation of the $\mathtt{head}$ function: $$ \mathtt{head}'\ :\ \ottsym{(} \mathtt{A} \ottsym{:} \rev{\ottkw{Type} } _{ \ottnt{i} } \ottsym{)} \rightarrow \ottsym{(} \mathtt{n} \ottsym{:} \ottkw{Nat} \ottsym{)} \rightarrow \ottsym{(} \mathtt{m} \ottsym{:} \ottkw{Nat} \ottsym{)} \rightarrow \ottkw{Eq} \ \ottkw{Nat} \ \mathtt{n} \ \ottsym{(} \mathtt{m} + 1 \ottsym{)} \to \ottkw{Vec} \ \mathtt{A} \ \mathtt{n} \to \mathtt{A} $$ This variant accepts vectors of any length, provided the user also supplies a proof that its length $\mathtt{n}$ is not zero (by providing the predecessor $\mathtt{m}$ and the equality proof $ \ottkw{Eq} \ \mathtt{n} \ \ottsym{(} \mathtt{m} + 1 \ottsym{)} $). \lang allows $ {\qm } $ to be used in place of a proof, while still ensuring that a runtime error is thrown if $\mathtt{head}'$ is ever given an empty list. For instance, suppose we define a singleton vector and a proof that $0=0$: \begin{align*} &\mathtt{staticCons} : \ottkw{Vec} \ \ottkw{Nat} \ 1 \qquad\qquad\qquad && \mathtt{staticProof} : \ottkw{Eq} \ \ottkw{Nat} \ 0 \ 0 \\ &\mathtt{staticCons} = \ottkw{Cons} \ \ottkw{Nat} \ 0 \ \ottsym{(} \ottkw{Nil} \ \ottkw{Nat} \ottsym{)} && \mathtt{staticProof} = \ottkw{Refl} \ \ottkw{Nat} \ 0 \end{align*} Then ${\ottsym{(} \mathtt{head'} \ \ottkw{Nat} \ 0 \ 0 \ \mathtt{staticProof} \ \mathtt{staticNil} \ottsym{)}}$ does not typecheck, ${\ottsym{(} \mathtt{head'} \ \ottkw{Nat} \ 0 \ {\qm } \ {\qm } \ \mathtt{staticNil} \ottsym{)}}$ typechecks but fails at runtime, and ${\ottsym{(} \mathtt{head'} \ \ottkw{Nat} \ 1 \ {\qm } \ {\qm } \ \mathtt{staticCons} \ottsym{)}}$ typechecks and succeeds at runtime. To see why we get a runtime failure for $\mathtt{staticNil}$, we note that internally, $\mathtt{head'}$ uses an explicit \textit{rewriting} of the equality, i.e. if $\mathit{x}$ and $\mathit{y}$ are equal, then any property $\mathtt{P}$ that holds for $\mathit{x}$ must also hold for $\mathit{y}$: $$ \mathtt{rewrite}\ :\ \ottsym{(} \mathtt{A} \ottsym{:} \rev{\ottkw{Type} } _{ \ottsym{1} } \ottsym{)} \rightarrow \ottsym{(} \mathit{x} \ottsym{:} \mathtt{A} \ottsym{)} \rightarrow \ottsym{(} \mathit{y} \ottsym{:} \mathtt{A} \ottsym{)} \rightarrow \ottsym{(} \mathtt{P} \ottsym{:} \mathtt{A} \to \rev{\ottkw{Type} } _{ \ottsym{1} } \ottsym{)} \rightarrow \ottkw{Eq} \ \mathtt{A} \ \mathit{x} \ \mathit{y} \to \mathtt{P} \ \mathit{x} \to \mathtt{P} \ \mathit{y} $$ \rev{ In \lang, when $ {\qm } $ is treated as an equality proof, it behaves as $ \ottkw{Refl} \ {\qm } \ {\qm } $.\footnote{ This follows directly from the understanding of the unknown type $ {\qm } $ as denoting all possible static types~\citep{agt}. Analogously, {\em the gradual term $ {\qm } $ denotes all possible static terms}. Thus applying the term $ {\qm } $ as a function represents applying all possible functions, producing all possible results, which can be abstracted as the gradual term $ {\qm } $. This means that $ {\qm } $, when applied as a function, behaves as $\lambda \mathit{x} \ldotp {\qm }$. Similarly, $ {\qm } $ treated as an equality proof behaves as $ \ottkw{Refl} \ {\qm } \ {\qm } $. } Therefore, in the latter two cases of our example, $\mathtt{rewrite}$ gives a result of type $ \mathtt{P} \ {\qm } $, which is checked against type $ \mathtt{P} \ \mathit{y} $, \textit{at runtime}. If $ \mathtt{P} \ \mathit{x} $ and $ \mathtt{P} \ \mathit{y} $ are not \added{definitionally equal}, then this check fails with a runtime error. } \paragraph{{\bf Managing effects from gradual typing}} \label{subsec:factorial} To illustrate how the effects of gradual typing can show up in typechecking, suppose a programmer uses the aforementioned $\mathtt{Z}$ combinator to accidentally write a non-terminating function $\mathtt{badFact}$. $$ \mathtt{badFact} = \lambda\ m\ \ldotp Z\ (\lambda\ f\ \ldotp \mathtt{ifzero}\ m\ (f\ 1) (m * f\ (m)) \quad \textit{ \texttt{--} never terminates} $$ As explained before, from a practical point of view, it is desirable for \lang to fully support dynamically-typed terms, because it allows the programmer to opt out of both the type discipline and the termination discipline of a dependently-typed language. However, this means that computing the return type of a function application may diverge, for instance: \begin{align*} &\mathsf{repeat} : \ottsym{(} \mathtt{A} \ottsym{:} \rev{\ottkw{Type} } _{ \ottsym{1} } \ottsym{)} \rightarrow \ottsym{(} \mathtt{n} \ottsym{:} \ottkw{Nat} \ottsym{)} \rightarrow \mathtt{A} \to \ottsym{(} \ottkw{Vec} \ \mathtt{A} \ \mathtt{n} \ottsym{)} \\ &\mathsf{factList} = \mathtt{repeat} \ \ottkw{Nat} \ \ottsym{(} \mathtt{badFact} \ 1 \ottsym{)} \ 0 \quad \textit{ \texttt{--} has type } \mathit{ \ottkw{Vec} \ \ottkw{Nat} \ \ottsym{(} \mathtt{badFact} \ 1 \ottsym{)} } \end{align*} \noindent To isolate the non-termination from imprecise code, we observe that any diverging code will necessarily apply a function of type $ {\qm } $. \added{While $\mathtt{badFact}$ does not have type $\qm$, its definition uses $Z$, which contains ascriptions of type $\qm$. } Similarly, a na\"ive approach to gradual dependent types will encounter failures when normalizing some terms. Returning to our $\mathtt{head}$ function, how should we typecheck the following term? $$\mathtt{failList} = { \mathtt{head} \ \ottkw{Nat} \ \ottsym{(} \mathtt{false} \dblcolon {\qm } \ottsym{)} \ \mathtt{staticCons} }$$ \noindent We need to check $\mathtt{staticCons}$ against ${ \ottkw{Vec} \ \ottkw{Nat} \ \ottsym{(} \ottsym{(} \mathtt{false} \dblcolon {\qm } \ottsym{)} + 1 \ottsym{)} }$, but what does ${ \ottsym{(} \mathtt{false} \dblcolon {\qm } \ottsym{)} + 1 }$ mean as a vector length? The difficulty here is that if a term contains type ascriptions that may produce a runtime failure, then it will \textit{always} trigger an error when normalizing, since normalization evaluates under binders. This means that typechecking will fail any time we apply a function to a possibly-failing term. This is highly undesirable, and goes against the spirit of gradual typing: writing programs in the large would be very difficult if applying a function to an argument that does match its domain type caused a type error, or caused typechecking to diverge! \added{Whereas Dependent Haskell places the burden on the programmer to ensure termination and freedom from failure during typechecking, doing so in a gradual language would make it difficult for programmers because of the possibly indirect interactions with untyped code.} \lang avoids both problems by using different notions of running programs for the compile-time and runtime phases. We distinguish compile-time \textit{normalization}, which is {\em approximate but total}, from runtime \textit{execution}, which is {\em exact but partial}. When non-termination or failures are possible, compile-time normalization uses $ {\qm } $ as an approximate but pure result. So both $\mathtt{factList}$ and $\mathtt{failList}$ can be defined and used in runtime code, but they are assigned type $ \ottkw{Vec} \ \ottkw{Nat} \ {\qm } $. To avoid non-termination and dynamic failures, we want our language to be strongly normalizing during typechecking. Approximate normalization gives us this. \lang normalization is focused around \textit{hereditary substitution}~\citep{hereditary}, which is a total operation from canonical forms to canonical forms. Because hereditary substitution is structurally decreasing in the \textit{type} of the value being substituted, a static termination proof is easily adapted to \lang. This allows us to pinpoint exactly where gradual types \rev{introduce} effects, approximate in those cases, and easily adapt the proof of termination of a static language to the gradual language \lang. Similarly, our use of bidirectional typing means that a single check needs to be added to prevent failures in normalization. \subsection{Gradual Guarantees for \lang} \label{subsec:gg-intro} To ensure a smooth transition between precise and imprecise typing, \lang satisfies the \textit{gradual guarantee}, which comes in two parts~\citep{refinedCriteria}. The \textit{static gradual guarantee} says that reducing the precision of a program preserves its well-typedness. The \textit{dynamic gradual guarantee} states that reducing the precision of a program also preserves its behavior, though the resulting value may be less precise. One novel insight of \lang's design is that the interplay between dependent typechecking and program evaluation carries over to the gradual guarantees. Specifically, the static gradual guarantee fundamentally depends on a restricted variant of the dynamic gradual guarantee. We show that approximate normalization maps terms related by precision to canonical forms related by precision, thereby ensuring that reducing a term's precision always preserves well-typedness. By satisfying the gradual typing criteria, \added{and embedding both a fully static and a fully dynamic fragment}, \lang gives programmers freedom to move within the entire spectrum of typedness, from the safety of higher-order logic to the flexibility of dynamic languages. Furthermore, admitting $ {\qm } $ as a term means that we can easily combine \added{code with dependent and non-dependent types}, the midpoint between dynamic and dependent types. For example, the simple list type could be written as $ \ottkw{List} \ \mathtt{A} = \ottkw{Vec} \ \mathtt{A} \ {\qm } $, so lists could be given to vector-expecting code and vice-versa. The programmer knows that as long as vectors are used in vector-expecting code, no crashes can happen, and \replaced{safety}{soundness} ensures that using a list in a vector operation will always fail gracefully or run successfully. This is significantly different from work on casts to subset types~\cite{Tanter:2015:GCP:2816707.2816710} and dependent interoperability~\citep{dagand_tabareau_tanter_2018}, where the user must explicitly provide decidable properties or (partial) equivalences. \subsection{Summary of Design Decisions} \label{sec:choices} \rev{\lang embodies several important design decisions, each with tradeoffs related to ease of reasoning and usability of the language. By embracing full-spectrum dependent types, \lang allows types to be first-class citizens: arbitrary terms can appear in types and expressions can produce types as a result. Therefore the programmer does not need to learn a separate index language, and there is no need to recreate term-level operations at the type level. Sticking to clearly separated phases allows us to adopt different reduction strategies for typechecking and for execution. Crucially, by using \textit{approximate normalization}, we ensure that typechecking in \lang always terminates: compile-time normalization is a total (though imprecise) operation. This means that some type information is statically lost, with checks deferred to runtime. \lang features an unknown term $\qm$, which resembles term holes in Agda and Idris, and existential variables in Coq; the notable difference is that programs containing $\qm$ can be run without evaluation getting stuck. Every type in \lang is therefore inhabited at least by the unknown term $\qm$, which means that the language is inconsistent as a logic, except for fully-precise programs. In a gradual language that can embed arbitrary untyped terms, programs may not terminate at runtime. Every type in \lang contains expressions that can fail or diverge at runtime, due to imprecision. Fully-precise programs are guaranteed to terminate. Finally, like Coq, Agda, and Idris, \lang is based on an intensional type theory, meaning that it automatically decides {\em definitional equality}---i.e. syntactic equality up to normalization---and not propositional equality; explicit rewriting is necessary to exploit propositional equalities. Consequently, runtime checks in \lang also rely on definitional equality. This makes equality decidable, but means that a runtime error can be triggered even though two (syntactically different) terms are propositionally equal. } \section{\slang: A Static Dependently-Typed Language} \label{sec:staticlang} We now present \slang, a static dependently-typed language which is essentially a bidirectional, call-by-value, cumulative variant of the predicative fragment of $\mathsf{CC}_\omega$ (i.e. the calculus of constructions with a universe hierarchy~\citep{COQUAND198895}). \slang is the starting point of our gradualization effort, following the Abstracting Gradual Typing (AGT) methodology~\cite{agt}, refined to accommodate dependent types. \subsection{Syntax and Dynamic Semantics} \begin{figure} \begin{minipage}[t]{0.3\linewidth} \nonterms{t} \end{minipage} \begin{minipage}[t]{0.3\linewidth} \nonterms{simpleValue} \end{minipage} \begin{minipage}[t]{0.3\linewidth} \nonterms{simpleContext} \end{minipage} \ottdefnSimpleStep{} \caption{\slang: Syntax and Semantics} \label{fig:syntax-static} \end{figure} The syntax of \slang is shown in \autoref{fig:syntax-static}. Metavariables for the static variants of terms, values, etc. are written in $\staticstyle{red,\ sans\text{-}serif\ font}{}{}$. Types and terms share a syntactic category. Functions and applications are in their usual form. Function types are \textit{dependent}: a variable name is given to the argument, and the codomain may refer to this variable. We have a \textit{universe hierarchy}: the lowest types have the type $ \rev{\ottkw{Type} } _{ \ottsym{1} } $, and each $ \rev{\ottkw{Type} } _{ \ottnt{i} } $ has type $ \rev{\ottkw{Type} } _{ \ottnt{i} \ottsym{+} \ottsym{1} } $. This hierarchy is \textit{cumulative}: any value in $ \rev{\ottkw{Type} } _{ \ottnt{i} } $ is also in $ \rev{\ottkw{Type} } _{ \ottnt{i} + 1} $. Finally, we have a form for explicit type ascriptions. We use metavariables $\static{v},\static{V}$ to range over values, which are the subset of terms consisting only of functions, function types and universes. For evaluation, we use a call-by-value reduction semantics (\autoref{fig:syntax-static}). Ascriptions are dropped when evaluating, and function applications result in (syntactic) substitution. We refer to the values and semantics as \textit{simple} rather than \textit{static}, since they apply equally well to an untyped calculus, albeit without the same soundness guarantees. \subsection{Comparing Types: Canonical Forms} \label{subsec:static-canonical} Since dependent types can contain expressions, it is possible that types may contain redexes. Most dependent type systems have a \textit{conversion} rule that assigns an expression type $\static{T}_{{\mathrm{1}}}$ if it has type $\static{T}_{{\mathrm{2}}}$, and $\static{T}_{{\mathrm{2}}}$ is convertible to $\static{T}_{{\mathrm{1}}}$ through some sequence of $\beta$-conversions, $\eta$-conversions, and $\alpha$-renamings. Instead, we treat types as ${\alpha\beta\eta}$-equivalence classes. To compare equivalence classes, we represent them using \textit{canonical forms}~\citep{hereditary}, denoted with metavariables $\static{u}$ and $\static{U}$. These are $\beta$-reduced, $\eta$-long canonical members of an equivalence class. We compare terms for ${\alpha\beta\eta}$-equivalence by normalizing and syntactically comparing their canonical forms. The syntax for canonical forms is given in \autoref{fig:static-types}. We omit well-formedness rules for terms and environments, since the only difference from the typing rules is the $\eta$-longness check. By representing function applications in \textit{spine form}~\citep{linearSpineCalc}, we can ensure that all heads are variables, and thus no redexes are present, even under binders. The well-formedness of canonical terms is ensured using bidirectional typing~\citep{localTypeInference}. An \textit{atomic form} can be a universe $ \rev{\ottkw{Type} } _{ \ottnt{i} } $, or a variable $x$ applied to 0 or more arguments, which we refer to as its \textit{spine}. Our well-formedness rules ensure the types of atomic forms are themselves atomic. This ensures that canonical forms are $\eta$-long, since they cannot have type $\ottsym{(} \mathit{y} \ottsym{:} \static{U}_{{\mathrm{1}}} \ottsym{)} \rightarrow \static{U}_{{\mathrm{2}}}$. \setbool{ShowArrowIndex}{false} \begin{figure} $\static{u},\static{U} \in \oblset{SCanonical}$ \setbool{ShowEmptyDot}{true} \begin{minipage}[t]{0.38\textwidth} \nonterms{u} \end{minipage} \begin{minipage}[t]{0.3\textwidth} \nonterms{rr} \end{minipage} \begin{minipage}[t]{0.3\textwidth} \nonterms{e} \end{minipage} \setbool{ShowEmptyDot}{false} \setbool{ShowArrowIndex}{true} \drules{$\static{Gamma} \vdash \static{t} \Rightarrow \static{U} \quad\mid\quad \static{Gamma} \vdash \static{t} \Leftarrow \static{U}$}{\ottcom{Static Typing: Synthesis and Checking}} {SSynthAnn,SSynthApp, SSynthVar, SSynthType, SCheckSynth, SCheckLevel, SCheckLam, SCheckPi} \caption{\slang: Canonical Forms and Typing Rules} \label{fig:static-types} \end{figure} \subsection{Typechecking and Normalization} Using the concept of canonical forms, we can now express the type rules for \slang in \autoref{fig:static-types}. To ensure syntax-directedness, we again use bidirectional typing. The \textit{type synthesis} judgement $\static{Gamma} \vdash \static{t} \Rightarrow \static{U}$ says that $\static{t}$ has type $\static{U}$ under context $\static{Gamma}$, where the type is treated as an output of the judgement. That is, from examining the term, we can determine its type. Conversely, the \textit{checking} judgment $\static{Gamma} \vdash \static{t} \Leftarrow \static{U}$ says that, given a type $\static{U}$, we can confirm that $\static{t}$ has that type. These rules allow us to propagate the information from ascriptions inwards, so that only top-level terms and redexes need ascriptions. Most rules in the system are standard. To support dependent types, \rrule{SSynthApp} computes the result of applying a particular value. We switch between checking and synthesis using \rrule{SSynthAnn} and \rrule{SCheckSynth}. The predicativity of our system is distilled in the \rrule{SSynthType} rule: $ \rev{\ottkw{Type} } _{ \ottnt{i} } $ always has type $ \rev{\ottkw{Type} } _{ \ottnt{i} + 1} $. The rule \rrule{SCheckLevel} encodes \textit{cumulativity}: we can always treat types as if they were \added{at} a higher \added{level}, though the converse does not hold. This allows us to check function types against any $ \rev{\ottkw{Type} } _{ \ottnt{i} } $ in \rrule{SCheckPi}, provided the domain and codomain check against that $ \rev{\ottkw{Type} } _{ \ottnt{i} } $. We distinguish \textit{hereditary substitution} on canonical forms $ {[ \static{u}_{{\mathrm{1}}} / { \mathit{x} } ]}^{ \static{U} } \static{u}_{{\mathrm{2}}} = \static{u}_{{\mathrm{3}}} $, from \textit{syntactic substitution} $ [ \mathit{x} \Mapsto \static{t}_{{\mathrm{1}}} ] \static{t}_{{\mathrm{2}}} = \static{t}_{{\mathrm{3}}}$ on terms. Notably, the former takes the type of its variable as input, and has canonical forms as both inputs and as output. In \rrule{SSynthApp} and \rrule{SCheckPi}, we use the \textit{normalization} judgement $\static{Gamma} \vdash \static{u} \leadsfrom\ \static{t} \Leftarrow \static{U}$, which computes the canonical form of $\static{t}$ while checking it against $\static{U}$. Similarly, \rrule{SSynthAnn} uses the judgement $ \static{Gamma} \vdash \static{U} \leadsfrom \static{T} : \rev{\ottkw{Type} } $, which uses hereditary substitution to compute the canonical form of $\static{T}$ while ensuring it checks against some $ \rev{\ottkw{Type} } _{ \ottnt{i} } $. The rules for normalization (\autoref{fig:static-hsub}) directly mirror those for well-typed terms, building up the canonical forms from sub-derivations. In particular, the rule \rrule{SNormSynthVar} $\eta$-expands any variables with function types, which allows us to assume that the function in an application will always normalize to a $\lambda$-term. (The rules for the eta expansion function $ \mathit{x} \leadsto_\eta \static{u} : \static{U} $ are standard, so we omit them). We utilize this assumption in \rrule{SNormSynthApp}, where the canonical form of an application is computed using hereditary substitution. \subsection{Hereditary Substitution} \label{subsec:static-hsub} \begin{figure} \drules{$ \static{Gamma} \vdash \static{U} \leadsfrom \static{T} : \rev{\ottkw{Type} } $}{\ottcom{Type Normalization with Unknown Level (rules omitted)}}{} \drules{$\static{Gamma} \vdash \static{t} \leadsto \static{u} \Rightarrow \static{U} \quad\mid\quad \static{Gamma} \vdash \static{u} \leadsfrom\ \mathit{y} \Leftarrow \static{U}$}{\ottcom{Static Normalization}}{SNormSynthAnn, SNormSynthVar, SNormSynthApp} \ottdefnSHsub \\ \ottdefnSHsubR \caption{\slang: Normalization (select rules) and Hereditary Substitution} \label{fig:static-hsub} \end{figure} Hereditary substitution is defined in \autoref{fig:static-hsub}. At first glance, many of the rules look like a traditional substitution definition. They traverse the expression looking for variables, and replace them with the corresponding term. However, there are some key differences. Hereditary substitution has canonical forms as both inputs and outputs. The key work takes place in the rule \rrule{SHsubRSpine}. When replacing $\mathit{x}$ with $\static{u}_{{\mathrm{1}}}$ in $ \mathit{x} \static{e} \ \static{u}_{{\mathrm{2}}} $, find the substituted forms of $\static{u}_{{\mathrm{2}}}$ and $ \mathit{x} \static{e} $, which we call $\static{u}_{{\mathrm{3}}}$ and $\lambda \mathit{y} \ldotp \static{u}'_{{\mathrm{1}}}$ respectively. If the inputs are well-typed and $\eta$-long, the substitution of the spine will always return a $\lambda$-term, meaning that its application to $\static{u}_{{\mathrm{3}}}$ is not a canonical form. To produce a canonical form in such a case, we continue substituting, recursively replacing $\mathit{y}$ with $\static{u}_{{\mathrm{3}}}$ in $\static{u}'_{{\mathrm{1}}}$\added{.} A similar substitution in the codomain of $\static{U}$ gives our result type. Thus, if this process terminates, it will always produce a canonical form. To ensure that the process does, in fact, terminate for well-typed inputs, we define hereditary substitution in terms of the type of the variable being replaced. Since we are replacing a different variable in the premise \rrule{SHsubRSpine}, we must keep track of the type of the resultant expression when substituting in spines, which is why substitution on atomic forms is a separate relation. We order types by the multiset of universes of all arrow types that are subterms of the type, similar to techniques used for Predicative System F~\citep{predSysF, eades2010hereditary}. We can use the well-founded multiset ordering given by \citet{multisetOrder}: if a type $\static{U}$ has maximum arrow type universe $\ottnt{i}$, we say that it is greater than all other types containing fewer arrows at universe $\ottnt{i}$ whose maximum is not greater than $\ottnt{i}$. Predicativity ensures that, relative to this ordering, the return type of a function application is always less than the type of the function itself. In all premises but the last two of \rrule{SHsubRSpine}, we recursively invoke substitution on strict subterms, while keeping the type of the variable the same. In the remaining cases, we perform substitution at a type that is smaller by our multiset order. \subsection{Properties of \slang} Since \slang is mostly standard, it enjoys the standard properties of dependently-typed languages. Hereditary substitution can be used to show that the language is strongly normalizing, and thus consistent as a logic. Since the type rules, hereditary substitution, and normalization are syntax directed and terminating, typechecking is decidable. Finally, because all well-typed terms have canonical forms, \slang is type \replaced{safe}{sound}. \section{\lang: Abstracting the Static Language} \label{sec:graduallang} We now present \lang, a gradual counterpart to \slang derived following the Abstracting Gradual Typing (AGT) methodology~\cite{agt}, extended to the setting of dependent types. \added{The key idea behind AGT is that gradual type systems can be designed by first specifying the \textit{meaning} of gradual types in terms of sets of static types. This meaning is given as a concretization function $\gamma$ that maps a gradual type to the set of static types that it represents, and an abstraction function $\alpha$ that recovers the {\em most precise} gradual type that represents a given set of static types. In other words, $\gamma$ and $\alpha$ form a {\em Galois connection}. Once the meaning of gradual types is clear, the typing rules and dynamic semantics for the gradual language can be derived systematically.} \rev{ First, $\gamma$ and $\alpha$ allow us to lift the type predicates and type functions used in the static type system (such as equality, subtyping, join, etc.) to obtain their gradual counterparts. From these definitions, algorithmic characterizations can then be validated and implemented. Second, the gradual type system is obtained from the static type system by using these lifted type predicates and functions. Finally, the runtime semantics follow by proof reduction of the typing derivation, mirroring the type safety argument at runtime. In particular, typing derivations are augmented with pieces of {\em evidence} for consistent judgments, whose combination during reduction may be undefined, hence resulting in a runtime type error. } \added{In this work we follow the AGT methodology, specifying $\gamma$ and $\alpha$, then describing how the typing rules are lifted to gradual types. In doing so, we uncover several points for which the standard AGT approach lacks the flexibility to accommodate full-spectrum dependent types with $\qm$ as a term. We describe our extensions to (and deviations from) the AGT methodology, and how they allow us to fully support gradual dependent types. } Throughout this section, we assume that we have gradual versions of hereditary substitution and normalization. We leave the detailed development of these notions to \autoref{sec:gradualhsub}, as they are non-trivial if one wants to preserve both decidable typechecking and the gradual guarantee (\autoref{subsec:gg-intro}). The dynamic semantics of \lang are presented in \autoref{sec:gradual-semantics}, and its metatheory in \autoref{sec:lang-properties}. \subsection{Terms and Canonical Forms} \subsubsection*{Syntax} \setbool{ShowArrowIndex}{true} \begin{figure} $\gradual{u},\gradual{U} \in \oblset{GCanonical}$\\ \setbool{ShowEmptyDot}{true} \begin{minipage}[t]{0.33\textwidth} \nonterms{gt} \end{minipage} \rev{ \begin{minipage}[t]{0.33\textwidth} \nonterms{canonical} \end{minipage} } \begin{minipage}[t]{0.3\textwidth} \nonterms{atomic,spine} \end{minipage} \setbool{ShowEmptyDot}{false} \caption{\lang: Terms and Canonical Forms} \label{fig:syntax-gradual} \end{figure} The syntax of \lang (\autoref{fig:syntax-gradual}) is a simple extension of \slang's syntax. We use $\gradualstyle{\text{blue, serif font}}{}{}$ to for metavariables denoting gradual terms, contexts, etc. In addition to constructs from \slang, \lang's syntax includes $ {\qm } $, the unknown term/type. This represents a type or term that is unknown to the programmer: by annotating a type with $ {\qm } $ or leaving a term as $ {\qm } $, they can allow their program to typecheck with only partial typing information or an incomplete proof. Similarly, $ {\qm } $ is added to the syntax of canonical values. \added{Additionally, arrow-types are annotated with a level $i$.} \rev{ The type $(x : \gradual{U}_1) \xrightarrow{i} \gradual{U}_2$ is well formed at type $\rev{\ottkw{Type} } _i$, and we have a special top level $\omega$ where $(x : \gradual{U}_1) \xrightarrow{\omega} \gradual{U}_2$ is well formed at type $?$. These annotations are necessary for ensuring the termination of hereditary substitution, but are inferred during normalization, and are never present in source programs. We often omit these annotations, as they clutter the presentation. } Canonical forms do not contain ascriptions. While statically-typed languages use ascriptions only for guiding typechecking, the potential for dynamic type failure means that ascriptions have computational content in gradual typing. Notably, only variables \added{or neutral applications} can synthesize $ {\qm } $ as a type, though any typed expression can be checked against $ {\qm } $. This allows us to reason about canonical forms at a given type: while we can layer ascriptions on terms, such as $ \ottsym{(} \mathtt{true} \dblcolon {\qm } \ottsym{)} \dblcolon {\qm } \to {\qm } $, the only canonical forms with function types are lambdas and $ {\qm } $. \subsection{Concretization and Predicates} \label{subsec:concretization} \begin{figure} $\gamma : \oblset{GCanonical} \to \mathcal{P}(\oblset{SCanonical}) \setminus \emptyset$ \\ \begin{minipage}{0.33\textwidth} \begin{align*} &\gamma( {\qm } ) & = & \oblset{SCanonical}\\ &\gamma( \rev{\ottkw{Type} } _{ \ottnt{i} } ) & = & \set{ \rev{\ottkw{Type} } _{ \ottnt{i} } } \\ &\gamma(\mathit{x}) & = & \set{x} \end{align*} \end{minipage} \begin{minipage}{0.6\textwidth} \begin{align*} &\gamma(\lambda \mathit{x} \ldotp \gradual{u}) & = & \set{\lambda \mathit{x} \ldotp \static{u}' \mid \static{u}' \in \gamma(\gradual{u})}\\ &\gamma( \mathit{x} \gradual{e} \ \gradual{u} ) & = & \set{ \mathit{x} \static{e}' \ \static{u}' \mid \mathit{x} \static{e}' \in \gamma( \mathit{x} \gradual{e} ), \static{u}' \in \gamma(\gradual{u})}\\ &\gamma(\ottsym{(} \mathit{x} \ottsym{:} \gradual{U}_{{\mathrm{1}}} \ottsym{)} \rightarrow \gradual{U}_{{\mathrm{2}}}) &=& \set{\ottsym{(} \mathit{x} \ottsym{:} \static{U}'_{{\mathrm{1}}} \ottsym{)} \rightarrow \static{U}'_{{\mathrm{2}}} \mid \static{U}'_{{\mathrm{1}}} \in \gamma(\gradual{U}_{{\mathrm{1}}}), \static{U}'_{{\mathrm{2}}} \in \gamma(\gradual{U}_{{\mathrm{2}}})} \end{align*} \end{minipage} \ottdefnConsistent \caption{\lang: Concretization and Consistency} \label{fig:concretization} \end{figure} The main idea of AGT is that gradual types abstract sets of static types, and that each gradual type can be made \textit{concrete} as a set of static types. For our system, we simply extend this to say that gradual terms represent sets of static terms. In a simply typed language, a static type embedded in the gradual language concretizes to the singleton set containing itself. However, for terms, we wish to consider the entire ${\alpha\beta\eta}$-equivalence class of the static term. As with typechecking, this process is facilitated by considering only canonical forms. The concretization function $\gamma : \oblset{GCanonical} \to \mathcal{P}(\oblset{SCanonical})$, defined in \autoref{fig:concretization}, recurs over sub-terms, with $ {\qm } $ mapping to the set of all terms. Given the concretization, we can \textit{lift} a predicate from the static system to the gradual system. A predicate holds for gradual types if it holds for some types in their concretizations. For equality, this means that $ \gradual{U} \cong \gradual{U}' $ if and only if $\gamma(\gradual{U}) \cap \gamma(\gradual{U}') \neq \emptyset$. We present a syntactic version of this in \autoref{fig:concretization}. Concretization also gives us a notion of \textit{precision} on gradual types. We say that $ \gradual{U} \sqsubseteq \gradual{U}' $ if $\gamma(\gradual{U}) \subseteq \gamma(\gradual{U}')$: that is, $\gradual{U}$ is more precise because there are fewer terms it could plausibly represent. We can similarly define $ \gradual{U} \sqcap \gradual{U}' $ as the most general term that is as precise as both $\gradual{U}$ and $\gradual{U}'$. Note that $ \gradual{U} \sqcap \gradual{U}' $ is defined if and only if $ \gradual{U} \cong \gradual{U}' $ i.e. if $\gamma(\gradual{U})\cap\gamma(\gradual{U}')\neq\emptyset$, \added{and like the consistency relation, it can be computed syntactically.} \subsection{Functions and Abstraction} \label{subsec:abstraction} \begin{figure} $\alpha : \mathcal{P}(\oblset{SCanonical}) \setminus \emptyset \to \oblset{GCanonical}$ \begin{minipage}{0.95\textwidth} \begin{align*} \alpha(\set{ \mathit{x} \static{e} \ \static{u} \mid \mathit{x} \static{e} \in A, \static{u} \in B}) & = && \mathit{x} \gradual{e}' \ \gradual{u}' & \text{ where } \alpha(A) = \mathit{x} \gradual{e}' , \alpha(B) = \gradual{u}'&\\ \alpha(\set{\ottsym{(} \mathit{x} \ottsym{:} \static{U}_{{\mathrm{1}}} \ottsym{)} \rightarrow \static{U}_{{\mathrm{2}}} \mid \static{U}_{{\mathrm{1}}} \in A, \static{U}_{{\mathrm{2}}} \in B }) & = && \ottsym{(} \mathit{x} \ottsym{:} \gradual{U}'_{{\mathrm{1}}} \ottsym{)} \rightarrow \gradual{U}'_{{\mathrm{2}}} & \text{ where } \alpha(A) = \gradual{U}'_{{\mathrm{1}}}, \alpha(B) = \gradual{U}'_{{\mathrm{2}}}&\\ \alpha(\set{\lambda \mathit{x} \ldotp \static{u} \mid \static{u} \in A} ) &= && \lambda \mathit{x} \ldotp \gradual{u}' & \text{ where } \alpha(A) = \gradual{u}'& \end{align*} \end{minipage} $\alpha(\set{ \rev{\ottkw{Type} } _{ \ottnt{i} } })\ =\ \rev{\ottkw{Type} } _{ \ottnt{i} } \qquad\qquad\qquad \alpha(\set{\mathit{x}})\ =\ \mathit{x} \qquad\qquad\qquad \alpha(A)\ =\ {\qm } \text{ otherwise } $ \begin{minipage}{0.95\textwidth} \fbox{$\ottkw{dom} : \oblset{GCanonical} \rightharpoonup \oblset{GCanonical}$}\qquad \fbox{$[\square / \_ ]^\square\ \ottkw{cod} \square : \oblset{GCanonical}^3 \rightharpoonup \oblset{GCanonical} \quad$} \end{minipage} \drules{ $[\square / \_ ]^\square\ \ottkw{body} \square : \oblset{GCanonical}^3 \rightharpoonup \oblset{GCanonical}$ }{\ottcom{Partial Functions}}{DomainPi, CodSubPi, BodySubPi, DomainDyn, CodSubDyn, BodySubDyn} \caption{\lang: Abstraction and Lifted Functions} \label{fig:abstraction} \end{figure} When typechecking a function application, we must handle the case where the function has type $ {\qm } $. Since $ {\qm } $ is not an arrow type, the static version of the rule would fail in all such cases. Instead, we extract the domain and codomain from the type using partial functions. Statically, $ \ottkw{dom}\ \ottsym{(} \mathit{x} \ottsym{:} \static{U} \ottsym{)} \rightarrow \static{U}' = \static{U} $, and is undefined otherwise. But what should the domain of $ {\qm } $ be? AGT gives a recipe for lifting such partial functions. To do so, we need the counterpart to concretization: abstraction. The abstraction function $\alpha$ is defined in \autoref{fig:abstraction}. It takes a set of static terms, and finds the most precise gradual term that is consistent with the entire set. Now, we are able to take gradual terms to sets of static terms, then back to gradual terms. It is easy to see that $\alpha(\gamma(\gradual{U})) = \gradual{U}$: \added{they are normal forms describing the same equivalence classes}. This lets us define our partial functions in terms of their static counterparts: we concretize the inputs, apply the static function element-wise on all values of the concretization for which the function is defined, then abstract the output to obtain a gradual term as a result. For example, the domain of a gradual term $\gradual{U}$ is $\alpha(\set{\ottkw{dom}\ \static{U}' \mid \static{U}'\in\gamma(\gradual{U})})$, which can be expressed algorithmically using the rules in \autoref{fig:abstraction}. We define function-type codomains and lambda-term bodies similarly, though we pair these operations with substitution to avoid creating a ``dummy'' bound variable name for $ {\qm } $. Taken together, $\alpha$ and $\gamma$ form a Galois connection, which ensures that our derived type system is a conservative extension of the static system. \subsection{Typing Rules} \begin{figure} \rev{ \drules{$\gradual{Gamma} \vdash \gradual{t} \Rightarrow \gradual{U} \quad\mid\quad \gradual{Gamma} \vdash \gradual{t} \Leftarrow \gradual{U}$}{Well-Typed Gradual Terms}{GSynthAnn, GSynthType, GSynthVar, GSynthDyn, GSynthApp, GCheckPi, GCheckLamPi, GCheckLamDyn, GCheckSynth, GCheckLevel} \added{} } \caption{\lang: Type Checking and Synthesis} \label{fig:typerules-gradual} \end{figure} Given concretization and abstraction, AGT gives a recipe for converting a static type system into a gradual one, and we follow it closely. \Autoref{fig:typerules-gradual} gives the rules for typing. Equalities implied by repeated metavariables have been replaced by consistency checks, such as in \rrule{GCheckSynth}. Similarly, in \rrule{GCheckPi} we use the judgment $ \gradual{U} \cong \rev{\ottkw{Type} } $ to ensure that the given type is consistent to, rather than equal to, some $ \rev{\ottkw{Type} } _{ \ottnt{i} } $. Rules that matched on the form of a synthesized type instead use partial functions, as we can see in \rrule{GSynthApp}. We split the checking of functions into \rrule{GCheckLamPi} and \rrule{GCCheckLamDyn} for clarity, but the rules are equivalent to a single rule using partial functions. \rev{In \rrule{GSynthAnn}, the judgment $\gradual{Gamma} \vdash \gradual{U} \leadsfrom \gradual{T} : \rev{\ottkw{Type} } _{\Rightarrow \ottnt{i} }$ \added{denotes \textit{level synthesis}}, where we normalize $\gradual{U}$ while inferring at what universe level it resides.} \added{We note that while $\gamma$ and $\alpha$ are crucial for deriving the definitions of gradual operations, the operations can be implemented algorithmically as syntactic checks; an implementation does not need to compute $\gamma$ or $\alpha$.} \rev{ Also, because $\gamma(x)=\{x\}$ for any variable $x$, consistency, precision and meet are all well-defined on open terms. Consistency corresponds to the gradual lifting of \textit{definitional equality}: $\gradual{u}_1 \cong \gradual{u}_2$ if and only if there is some $\static{u}'_1 \in \gamma(\gradual{u}_1)$ and $\static{u}'_2 \in \gamma(\gradual{u}_2)$ where $\static{u}'_1 =_{\alpha\beta\eta} \static{u}'_2 $. This reflects our intensional approach: functions are consistent if their bodies are consistent. } We wish to allow the unknown term $ {\qm } $ to replace any term in a program. But what should its type be? By the AGT philosophy, $ {\qm } $ represents all terms, so it should synthesize the abstraction of all inhabited types, which is $ {\qm } $. We encode this in the rule \rrule{GSynthDyn}. This means that we can use the unknown term in any context. As with the static system, we represent types in canonical form, which makes consistency checking easy. Well-formedness rules (omitted) are derived from the static system in the same way as the gradual type rules. Additionally, the gradual type rules rely on the \textit{gradual normalization} judgments, $\gradual{Gamma} \vdash \gradual{t} \leadsto \gradual{u} \Rightarrow \gradual{U}$ and $\gradual{Gamma} \vdash \gradual{u} \leadsfrom\ \gradual{t} \Leftarrow \gradual{U}$, which we explain in \autoref{subsec:gradualnorm}. \subsection{Example: Typechecking $\mathtt{head}$ of $\mathtt{nil}$} \label{subsec:type-headnil} To illustrate how the \lang type system works, we explain the typechecking of one example from the introduction. Suppose we have types for natural numbers and vectors, and a derivation for \\ $\gradual{Gamma} \vdash \mathtt{head} \ :\ \ottsym{(} \mathtt{A} \ottsym{:} \rev{\ottkw{Type} } _{ \ottsym{1} } \ottsym{)} \rightarrow \ottsym{(} \mathtt{n} \ottsym{:} \ottkw{Nat} \ottsym{)} \rightarrow \ottkw{Vec} \ \mathtt{A} \ \ottsym{(} \mathtt{n} + 1 \ottsym{)} \to \mathtt{A} $. In \autoref{fig:vec-deriv}, we show the (partial) derivation of $\gradual{Gamma} \vdash \mathtt{head} \ \ottkw{Nat} \ 0 \ \ottsym{(} \ottsym{(} \ottkw{Nil} \ \ottkw{Nat} \ottsym{)} \dblcolon \ottkw{Vec} \ \ottkw{Nat} \ {\qm } \ottsym{)} \Rightarrow \ottkw{Nat} $. The key detail here is that the compile-time consistency check lets us compare $ 0 $ to $ {\qm } $, and then $ {\qm } $ to $ 1 $, which allows the example to typecheck. Notice how we only check consistency when we switch from checking to synthesis. While this code typechecks, it fails at runtime. We step through its execution in \autoref{subsec:nilhead-run}. \section{Approximate Normalization} \label{sec:gradualhsub} \begin{figure}[t!] \tiny \begin{mathpar} \inferrule*[Right = \tiny\rrule{GSynthApp}]{ \inferrule*{ \vdots } { \gradual{Gamma} \vdash \mathtt{head} \, \ottkw{Nat} \, 0 \! \Rightarrow \! \ottkw{Vec} \, \ottkw{Nat} \, 1 \! \to \! \ottkw{Nat} } \\ \inferrule*[Right = \tiny\rrule{GCheckSynth}]{ \inferrule*[Left = \tiny\rrule{GSynthAnn}]{ \inferrule*[Left = \tiny\rrule{GCheckSynth}]{ \inferrule*{ \vdots } { \gradual{Gamma} \vdash \ottkw{Nil} \, \ottkw{Nat} \Rightarrow \ottkw{Vec} \, \ottkw{Nat} \, 0 } \\ \inferrule*{\vdots}{ \gbox{ \ottkw{Vec} \, \ottkw{Nat} \, 0 \cong \ottkw{Vec} \, \ottkw{Nat} \, {\qm } } } } { \gradual{Gamma} \vdash \ottkw{Nil} \, \ottkw{Nat} \Leftarrow \ottkw{Vec} \, \ottkw{Nat} \, {\qm } } \\ \vdots } { \gradual{Gamma} \vdash \ottsym{(} \ottkw{Nil} \, \ottkw{Nat} \ottsym{)} \dblcolon \ottkw{Vec} \, \ottkw{Nat} \, {\qm } \! \Rightarrow \! \ottkw{Vec} \, \ottkw{Nat} \, {\qm } } \\ \inferrule*{\vdots}{ \gbox{ \ottkw{Vec} \, \ottkw{Nat} \, {\qm } \! \cong \! \ottkw{Vec} \, \ottkw{Nat} \, 1 } } } { \gradual{Gamma} \vdash \ottsym{(} \ottkw{Nil} \, \ottkw{Nat} \ottsym{)} \dblcolon \ottkw{Vec} \, \ottkw{Nat} \, {\qm } \Leftarrow \ottkw{Vec} \, \ottkw{Nat} \, 1 } } { \gradual{Gamma} \vdash \mathtt{head} \, \ottkw{Nat} \, 0 \, \ottsym{(} \ottsym{(} \ottkw{Nil} \, \ottkw{Nat} \ottsym{)} \dblcolon \ottkw{Vec} \, \ottkw{Nat} \, {\qm } \ottsym{)} \Rightarrow \ottkw{Nat} } \end{mathpar} \caption{Type Derivation for head of nil} \label{fig:vec-deriv} \end{figure} In the previous example, normalization was used to compute the type of $ \mathtt{head} \ \ottkw{Nat} \ 0 $, replacing $\mathtt{n}$ with $ 0 $ in the type of $\mathtt{head}$, normalizing $ 0 + 1 $ to $ 1 $. This computation is trivial, but not all are. As we saw in \autoref{subsec:factorial}, the type-term overlap in \lang means that code that is run during typechecking may fail or diverge. A potential solution would be to disallow imprecisely typed code in type indices. However, this approach breaks the criteria for a gradually-typed language. In particular, it would result in a language that violates the static gradual guarantee (\autoref{subsec:gg-intro}). The static guarantee implies that if a program does not typecheck, the programmer knows that the problem is not the absence of type precision, but that the types present are fundamentally wrong. Increasing precision in multiple places will never cause a program to typecheck if doing so in one place fails. In this section, we present two versions of gradual substitution. First, we provide \textit{ideal substitution}, which is well defined on all terms, but for which equality is undecidable. Second, we describe \textit{approximate hereditary substitution}, which regains decidability while preserving the gradual guarantee, by producing compile-time canonical forms that are potentially less precise than their runtime counterparts. Thus, we trade precision for a termination guarantee. From this, we build \textit{approximate normalization}, which uses hereditary substitution to avoid non-termination, and avoids dynamic failures by normalizing certain imprecise terms to $ {\qm } $. A key insight of this work is that we need separate notions of \textit{compile-time normalization} and \textit{run-time execution}. That is, we use approximate hereditary substitution \textit{only} in our types. Executing our programs at run-time will not lose information, but it may diverge or fail. For typechecking, the effect of this substitution is that non-equal terms of the unknown type may be indistinguishable at compile-time. Returning to the example from \autoref{subsec:factorial}, the user's faulty factorial-length vector will typecheck, but at type $ \ottkw{Vec} \ \ottkw{Nat} \ {\qm } $. Using it will never raise a static error due to its length, but it may raise a runtime error. \subsection{Ideal Substitution} Here, we present a definition of gradual substitution for ${\alpha\beta\eta}$-equivalence classes of terms. While comparing equivalence classes is undecidable, we will use ideal substitution as the theoretical foundation, showing that our approximate substitution produces the same results as ideal substitution, save for some loss of precision. The main difficulty with lifting the definition of hereditary substitution is that the set of terms with a canonical form is only closed under hereditary substitution when we assume a static type discipline. The terms $ \mathit{y} \ \mathit{y} $ and $ \lambda \mathit{x} \ldotp \mathit{x} \ \mathit{x} $ are both syntactically canonical, but if we substitute the second in for $\mathit{y}$, there is no normal form. However, both of these terms can be typed in our gradual system. How can $[ \ottsym{(} \lambda \mathit{x} \ldotp \mathit{x} \ \mathit{x} \ottsym{)}/\mathit{y} ]^{ {\qm } } \mathit{y} \ \mathit{y} $ be defined? If we apply the AGT lifting recipe to hereditary substitution, we get a function that may not have a defined output for all gradually well-typed canonical inputs. Even worse is that determining whether substitution is defined for an input is undecidable. By AGT's formulation, $[ \gradual{u}/\mathit{x} ]^{ {\qm } } \gradual{u}' $ would be $\alpha(\set{ [ \static{u}_{{\mathrm{1}}} / x]^{\static{U}} \static{u}_{{\mathrm{2}}} \mid \static{u}_{{\mathrm{1}}} \in \gamma(\gradual{u}), \static{u}_{{\mathrm{2}}} \in \gamma(\gradual{u}'), \static{U}\in\oblset{SCanonical} })$. To compute $\alpha$, we must know which of the concretized results are defined, i.e. find all pairs in $\gamma(\gradual{u})\times\gamma(\gradual{u}')$ for which there exists some $\static{U}$ on which static hereditary substitution is defined. This means determining if there is any finite number of substitutions under which the substitution on a (possibly dynamically-typed) term is defined, which requires solving the Halting Problem. Recall that we introduced canonical forms in \autoref{subsec:static-canonical} to uniquely represent ${\alpha\beta\eta}$-equivalence classes. While canonical forms are not closed under substitutions, equivalence classes are. Going back to our initial example, what we really want is for $[ \ottsym{(} \lambda \mathit{x} \ldotp \mathit{x} \ \mathit{x} \ottsym{)}/\mathit{y} ]^{ {\qm } } \mathit{y} \ \mathit{y} $ to be $(\ottsym{(} \lambda \mathit{x} \ldotp \mathit{x} \ \mathit{x} \ottsym{)}\ottsym{(} \lambda \mathit{x} \ldotp \mathit{x} \ \mathit{x} \ottsym{)})^{\alpha\beta\eta} $, i.e. the set of all terms ${\alpha\beta\eta}$-equivalent to $\Omega$. Thus we define ideal substitution on ${\alpha\beta\eta}$-equivalence classes themselves. For this, we do not need hereditary substitution: if $s \in s^{\alpha\beta\eta}$ and $t\in t^{\alpha\beta\eta}$ are terms with their respective equivalence classes, the substitution $[x \Mapsto s^{\alpha\beta\eta}]t^{\alpha\beta\eta}$ is simply the equivalence class of $[x \Mapsto s]t$. We now have a total operation from equivalence classes to equivalence classes. These classes may have no canonical representative, but the function is defined regardless. If we extend concretization and abstraction to be defined on equivalence classes, this gives us the definition of ideal substitution: $$ [ \mathit{x} \Mapsto \gradual{t}_{{\mathrm{1}}}^{\alpha\beta\eta} ] \gradual{t}_{{\mathrm{2}}}^{\alpha\beta\eta} = \alpha(\{ [ \mathit{x} \Mapsto \static{t}'_{{\mathrm{1}}} ] \static{t}'_{{\mathrm{2}}} \mid \static{t}'_{{\mathrm{1}}} \in \gamma(\gradual{t}_{{\mathrm{1}}}), \static{t}'_{{\mathrm{2}}} \in \gamma(\gradual{t}_{{\mathrm{2}}}) \} ) $$ That is, we find the concretization of the gradual equivalence classes, which are sets of static equivalence classes. We then substitute in each combination of these by taking the substitution of a representative element, and abstract over this set to obtain a single gradual equivalence class. \subsection{Approximate Substitution} \rev{ \begin{figure} \ottdefnGHsubR \caption{\lang: \rev{Approximate Substitution (select rules)}} \label{fig:gradual-hsub} \end{figure} } With a well-defined but undecidable substitution, we now turn to the problem of how to recover decidable comparison for equivalence classes, without losing the gradual guarantees. We again turn to (gradual) canonical forms as representatives of ${\alpha\beta\eta}$-equivalence classes. What happens when we try to construct a hereditary substitution function syntactically, as in \slang? The problem is in adapting \rrule{SHsubRSpine}. Suppose we are substituting $\gradual{u}$ for $\mathit{x}$ in $ \mathit{x} \gradual{e} \ \gradual{u}_{{\mathrm{2}}} $, and the result of substituting in $ \mathit{x} \gradual{e} $ is $\ottsym{(} \lambda \mathit{y} \ldotp \gradual{u}' \ottsym{)} : {\qm } $. Following the AGT approach, we can use the $\ottkw{dom}$ function to calculate the domain of $ {\qm } $, which is the type at which we substitute $\mathit{y}$. But this violates the well-foundedness condition we imposed in the static case! Since the domain of $ {\qm } $ is $ {\qm } $, eliminating redexes may infinitely apply substitutions without decreasing the size of the type. In all other cases, we have no problem, since the term we are substituting into is structurally decreasing. So, while equivalence classes give us our ideal, theoretical definition, hereditary substitution provides us with the exact cases we must approximate in order to preserve decidability. To guarantee termination, we must not perform recursive substitutions in spines with $ {\qm } $-typed heads. There are two apparent options for how to proceed without making recursive calls: we either fail when we try to apply a $ {\qm } $-typed function, or we return $ {\qm } $. The former will preserve termination, but it will not preserve the static gradual guarantee. Reducing the precision of a well-typed program's ascriptions should never yield ill-typed code. If applying a dynamically-typed function caused failure, then changing an ascription to $ {\qm } $ could cause a previously successful program to crash, violating the guarantee. Our solution is to produce $ {\qm } $ when applying a function of type $ {\qm } $. We highlight the changes to hereditary substitution in \autoref{fig:gradual-hsub}. \rrule{GHsubRDynType} accounts for $ {\qm } $-typed functions, and \rrule{GHsubRDynSpine} accounts for $ {\qm } $ applied as a function. \added{We must add one more check to guarantee termination, because $\qm : \qm$ could be used to circumvent the universe hierarchy. For instance,} \rev{we can assign $(x : \qm) \to (x\ \rev{\ottkw{Type} } _{99})$ the type $\rev{\ottkw{Type} } _1$, and we can even write a version Girard's Paradox~\citep{girard1972interpretation,coquand:inria-00076023} by using $\qm$ in place of $\rev{\ottkw{Type} } $. Because of this, \rrule{GHsubRLamSpine} manually checks our decreasing metric.} \added{Concretely, $i \prec \omega$ for every $i$, and } \rev{ $\gradual{U} \prec \gradual{U}'$ when the multiset of annotations on arrow types in $\gradual{U}$ is less than that of $\gradual{U}'$ by the well-founded multiset ordering given by \citet{multisetOrder}. In the static case, the type of substitution is always decreasing for this metric. In the presence of $\qm$, we must check if the order is violated and return $\qm$ if it is, as seen in the rule \rrule{GHsubRLamSpineOrd}. Unlike applying a function of type $\qm$, we believe that this case is unlikely to arise in practice unless programmers are deliberately using $\qm$ to circumvent the universe hierarchy.} \subsection{Approximate Normalization} \label{subsec:gradualnorm} \begin{figure} \rev{ \drules{$\gradual{Gamma} \vdash \gradual{t} \leadsto \gradual{u} \Rightarrow \gradual{U} \quad\mid\quad \gradual{Gamma} \vdash \gradual{u} \leadsfrom\ \gradual{t} \Leftarrow \gradual{U}$}{\ottcom{Approximate Normalization}}{ GNSynthApp, GNCheckSynth, GNCheckApprox, GNCheckPiType, GNCheckPiDyn } } \caption{\lang: Approximate Normalization (select rules) } \label{fig:typing-norm-gradual} \end{figure} While approximate hereditary substitution eliminates non-termination, we must still account for dynamic failures. We do so with \textit{approximate normalization} (\autoref{fig:typing-norm-gradual}). To see the issue, consider that we can type the term $\ottsym{(} \lambda \mathtt{A} \ldotp \ottsym{(} 0 \dblcolon {\qm } \ottsym{)} \dblcolon \mathtt{A} \ottsym{)}$ against $\ottsym{(} \mathtt{A} \ottsym{:} \rev{\ottkw{Type} } _{ \ottsym{1} } \ottsym{)} \rightarrow \mathtt{A} $. However, there are no ascriptions in canonical form, since ascriptions can induce casts, which are a form of computation. The term $\ottsym{(} \lambda \mathtt{A} \ldotp 0 \ottsym{)}$ certainly does not type against against $\ottsym{(} \mathtt{A} \ottsym{:} \rev{\ottkw{Type} } _{ \ottsym{1} } \ottsym{)} \rightarrow \mathtt{A} $, since $\ottsym{0}$ will not check against the type variable $\mathtt{A}$. However, if we were to raise a type error, we would never be able to apply a function to the above term. In the context $\ottsym{(} \mathtt{A} \ottsym{:} \rev{\ottkw{Type} } _{ \ottsym{1} } \ottsym{)} \cdot$, the only canonical term with type $\mathtt{A}$ is $ {\qm } $. \added{For the term to have a} well-typed normal form, its body must be $ {\qm } $. More broadly, normalization does not preserve \textit{synthesis} of typing, only checking. In the rule \rrule{GNCheckSynth}, if $\gradual{Gamma} \vdash \gradual{t} \leadsto \gradual{u} \Rightarrow \gradual{U}'$, then the normal form of $\gradual{t}$ might check against $\gradual{U}$, but it won't necessarily synthesize $\gradual{U}$ (or any type). We need to construct a canonical form $\gradual{u}$ for $\gradual{t}$ at type $\gradual{U}$, assuming we have some normal form $\gradual{u}'$ for $\gradual{t}$ at type $\gradual{U}'$. If $ \gradual{U} \sqsubseteq \gradual{U}' $, $\gradual{u}'$ will check against $\gradual{U}$. Otherwise, the only value we can be sure will check against $\gradual{U}$ is $ {\qm } $, which checks against any type. We formalize this using a pair of rules: \rrule{GNCheckSynth} normalizes fully when we can do so in a type-safe way, and \rrule{GNCheckApprox} produces $ {\qm } $ as an approximate result in all other cases. Gradual typing must also treat $\eta$-expansion carefully. We $\eta$-expand all variables in \rrule{GNSynthVar} (see appendix), but in \rrule{GNSynthApp}, we may be applying a function of type $ {\qm } $. However, a variable $\mathit{x}$ of type $ {\qm } $ is $\eta$-long. Since we are essentially treating a value of type $ {\qm } $ as type $ {\qm } \to {\qm } $, we must expand $\mathit{x}$ to $\ottsym{(} \lambda \mathit{y} \ldotp \mathit{x} \ \mathit{y} \ottsym{)}$. We do this in \rrule{GNSynthVar} with an extra $\eta$-expansion at type $ {\qm } \to {\qm } $, which expands a $ {\qm } $-typed term one level, and has no effect on a canonical form with a function type. \added{Normalization is also where we generate the annotations necessary for ensuring the decreasing metric of hereditary substitution. As we see in the rules} \rev{ \rrule{GNCheckPiType} and \rrule{GNCheckPiDyn}, we annotate arrows either with the level against which they are checked, or with $\omega$ when checking against $\qm$.} The remaining rules for normalization (omitted) directly mirror the rules from \autoref{fig:typerules-gradual}. $ \rev{\ottkw{Type} } _{ \ottnt{i} } $, $ {\qm } $, and variables all normalize to themselves, and all other rules simply construct normal forms from the normal forms of their subterms. Some of the difficulty with normalization arises because function arguments are normalized before being substituted. One could imagine a language that normalizes after substituting function arguments, and typechecking fails if a dynamic error is encountered during normalization. Here, normalization could fail, but only on terms that had truly ill-formed types, since unused failing values would be discarded. We leave the development of such a language to future work. \subsection{Properties of Approximate Normalization} \subsubsection*{Relationship to the Ideal} If we expand our definition of concretization to apply to equivalence classes of terms, gradual precision gives us a formal relationship between ideal and approximate normalization: \begin{restatable}[Normalization Approximates the Ideal]{theorem}{norm-precision} For any $\gradual{Gamma},\gradual{t},\gradual{U}$, if $\gradual{Gamma} \vdash \gradual{t} \Leftarrow \gradual{U}$, then $\gradual{Gamma} \vdash \gradual{u} \leadsfrom\ \gradual{t} \Leftarrow \gradual{U}$ for some $\gradual{u}$, and $ \gradual{t}^{\alpha\beta\eta} \sqsubseteq \gradual{u} $. \end{restatable} \noindent Intuitively, this holds because approximate normalization for a term either matches the ideal, or produces $ {\qm } $, which is less precise than every other term. \subsubsection*{Preservation of Typing} To prove type \replaced{safety}{soundness} for \lang, a key property of normalization is that it preserves typing. This property relies on the fact that hereditary substitution preserves typing, which can be shown using a technique similar to that of \citet{churchCurry}. \begin{restatable}[Normalization preserves typing]{theorem}{typeNorm} \label{lem:typeSub} If $\gradual{Gamma} \vdash \gradual{u} \leadsfrom\ \gradual{t} \Leftarrow \gradual{U}$, then $\gradual{Gamma} \vdash \gradual{u} \Leftarrow \gradual{U}$. \end{restatable} \subsubsection*{Normalization as a Total Function} Since we have defined substitution and normalization using inference rules, they are technically relations rather than functions. Since the rules are syntax directed in terms of their inputs, it is easy to show that there is at most one result for every set of inputs. As we discussed above, the approximation in \rrule{GNCheckApprox} makes normalization total. \begin{restatable}[Normalization is Total]{theorem}{normTotal} \label{lem:normTotal} If $\gradual{Gamma} \vdash \gradual{t} \Leftarrow \gradual{U}$, then $\gradual{Gamma} \vdash \gradual{u} \leadsfrom\ \gradual{t} \Leftarrow \gradual{U}$ for exactly one $\gradual{u}$. \end{restatable} \section{\lang: Runtime Semantics} \label{sec:gradual-semantics} With the type system for \lang realized, we turn to its dynamic semantics. Following the approaches of \citet{agt} and \citet{parametricityRevisited}, we let the syntactic type-safety proof for the static \slang drive its design. In place of a cast calculus, gradual terms carry \textit{evidence} that they match their type, and computation steps evolve that evidence incrementally. When evidence no longer supports the well-typedness of a term, execution fails with a runtime type error. \subsection{The Runtime Language} \begin{figure} \begin{minipage}[t]{0.32\textwidth} \nonterms{et} \end{minipage} \begin{minipage}[t]{0.32\textwidth} \nonterms{dummyev,rv} \end{minipage} \rev{ \begin{minipage}[t]{0.32\textwidth} \nonterms{evalContext} \nonterms{epsilon} \end{minipage} \drules{$\gradual{Gamma} \vdash \evterm{t} \ottsym{:} \gradual{U}$}{\ottcom{Evidence Term Typing}}{EvTypeApp, EvTypeEv,EvTypeDyn} } \caption{Evidence Term Syntax and Typing (select rules)} \label{fig:evidenceTerms} \end{figure} \Autoref{fig:evidenceTerms} gives the syntax for our runtime language. It mirrors the syntax for gradual terms, with two main changes. In place of type ascriptions, we have a special form for terms augmented with evidence, following \citet{parametricityRevisited}. We also have $\mathsf{err}$, an explicit term for runtime type errors. Translation proceeds by augmenting our bidirectional typing rules to output the translated term. Type ascriptions are dropped in the \rrule{GSynthAnn} rule, and initial evidence of consistency is added in \rrule{GCheckSynth}. \Autoref{subsec:initialEvidence} describes how to derive this initial evidence. In the \rrule{GSynthDyn} rule, we annotate $ {\qm } $ with evidence $ {\qm } $, so $ {\qm } $ is always accompanied by some evidence of its type. \added{Similarly, functions of type $\qm$ are ascribed $\langle \qm \to \qm \rangle$.} In \autoref{fig:evidenceTerms} we also define the class of syntactic values, which determines those terms that are done evaluating. We wish to allow values to be augmented with evidence, but not to have multiple evidence objects stacked on a value. To express this, we separate the class of values from the class of \textit{raw values}, which are never ascribed with evidence at the top level. Values are similar to, but not the same, as canonical forms. In particular, there are no redexes in canonical terms, even beneath a $\lambda$, whereas values may contain redexes within abstractions. \subsection{Typing and Evidence} \label{subsec:initialEvidence} To establish progress and preservation, we need typing rules for evidence terms, whose key rules we highlight in \autoref{fig:evidenceTerms}. These are essentially the same as for gradual terms, with two major changes. First, we no longer use bidirectional typing, since our type system need not be syntax directed to prove \replaced{safety}{soundness}. \added{Second, whereas gradual terms could be given any type that is consistent with their actual type, we only allow this for dynamic terms directly ascribed with evidence, as seen in the} \rev{ rule \rrule{EvTypeEv}. Thus, all applications of consistency are made explicit in the syntax of evidence terms, and for a term $\varepsilon\ \evterm{t}$, the evidence $\varepsilon$ serves as a concrete witness between the actual type of $\evterm{t}$ and the type at which it is used. The normalization relation is extended to evidence terms: it simply erases evidence ascriptions and otherwise behaves like the normalization for gradual terms. We can then define hereditary substitutions of evidence terms into types, which is crucial for updating evidence after function applications}. This raises the question: what is evidence? \added{At a high level, the evidence attached to a term tracks the most precise type information about this term that is dynamically available. As we can see in \autoref{fig:evidenceTerms}, evidence consists of a canonical type: we use brackets $\langle \rangle$ to syntactically distinguish evidence from canonical forms. Ascribing a term with evidence behaves like a cast in a gradual cast calculus; the key difference is that evidence only ever increases in precision. It serves as a witness for the consistency of two types, and by refining evidence at each step (and failing when this is not possible), we ensure that each intermediate expression is (gradually) well-typed.} \rev{ \citet{agt} identify the correspondence between evidence and the middle type in a threesome calculus~\cite{Siek:2009:TWB:1570506.1570511}.} AGT provides a general formulation of evidence, applicable to multi-argument, asymmetric predicates. However, since equality is the only predicate we use, the meet of two terms is sufficient to serve as evidence of their consistency. \rev{We say that $ \varepsilon \vdash \gradual{U}_{{\mathrm{1}}} \cong \gradual{U}_{{\mathrm{2}}} $ whenever $\varepsilon = \langle \gradual{U}' \rangle$ and $ \gradual{U}' \sqsubseteq \gradual{U}_{{\mathrm{1}}} \sqcap \gradual{U}_{{\mathrm{2}}} $.} \added{There are two key operations on evidence. First, we need \textit{initial evidence} for elaborating gradual terms to evidence terms.} \rev{ If a term synthesizes some $\gradual{U}$ and is checked against $\gradual{U}'$, then during elaboration we can ascribe to it the evidence $ \langle \gradual{U} \sqcap \gradual{U}' \rangle $. Secondly, we need a way to combine two pieces of evidence at runtime, an operation referred to as \textit{consistent transitivity} in AGT: if $ \langle \gradual{U} \rangle \vdash \gradual{U}_{{\mathrm{1}}} \cong \gradual{U}_{{\mathrm{2}}} $, and $ \langle \gradual{U}' \rangle \vdash \gradual{U}_{{\mathrm{2}}} \cong \gradual{U}_{{\mathrm{3}}} $, then $ \langle \gradual{U} \sqcap \gradual{U}' \rangle \vdash \gradual{U}_{{\mathrm{1}}} \cong \gradual{U}_{{\mathrm{3}}} $, provided that the meet is defined. So we can also use the precision meet to dynamically combine different pieces of evidence.} \added{Evidence is combined using the meet operation, which is based on definitional (intensional) equality. This means that if we have a type $\mathtt{A} : (\ottkw{Nat} \to \ottkw{Nat}) \to \rev{\ottkw{Type} } _1$, then $\mathtt{A} (\lambda x \ldotp x + x - x)$ and $\mathtt{A} (\lambda x \ldotp x)$ will not be consistent at runtime, despite being extensionally equivalent. Extensional equality is undecidable, so it cannot be used during typechecking. Since definitional equality is decidable, we use it both for typechecking and at runtime. This also ensures that the type operations performed at runtime directly mirror those performed during typechecking. } \subsection{Developing a Safe Semantics} To devise our semantics, we imagine a hypothetical proof of progress and preservation. Progress tells us which expressions we need reduction rules for, and preservation tells us how to step in order to remain well-typed. \subsubsection*{Double Evidence} Since values do not contain terms of the form $\myepsilon_{{\mathrm{2}}} \, \ottsym{(} \myepsilon_{{\mathrm{1}}} \, \evterm{rv} \ottsym{)}$, progress dictates that we need a reduction rule for such a case. If $\cdot \vdash \evterm{rv} \ottsym{:} \gradual{U}$, $ \myepsilon_{{\mathrm{1}}} \vdash \gradual{U} \cong \gradual{U}' $ and $ \myepsilon_{{\mathrm{2}}} \vdash \gradual{U}' \cong \gradual{U}'' $, then $ \myepsilon_{{\mathrm{1}}} \sqcap \myepsilon_{{\mathrm{2}}} \vdash \gradual{U} \cong \gradual{U}'' $, so we step to $\ottsym{(} \myepsilon_{{\mathrm{1}}} \sqcap \myepsilon_{{\mathrm{2}}} \ottsym{)} \evterm{rv}$. If the meet is not defined, then a runtime error occurs. \subsubsection*{Functions with Evidence} \added{There are two complications for reducing applications with evidence. The first is that in} \rev{$\lambda \mathit{x} \ldotp \evterm{t}$, the variable $\mathit{x}$ may be free in evidence ascriptions within $\evterm{t}$. When performing a substitution, we need the type and normal form of the term replacing the variable. We use the notation ${[ \mathit{x} \Mapsto \evterm{t}_{{\mathrm{1}}} ]}^{ \gradual{u} : \gradual{U} } \evterm{t}_{{\mathrm{2}}}$ to denote the syntactic replacement of $\mathit{x} $ by $\evterm{t}_{{\mathrm{1}}}$ in $\evterm{t}_{{\mathrm{2}}}$, where free occurrences of $\mathit{x} $ in evidence within $\evterm{t}_{{\mathrm{2}}}$ are replaced by $\gradual{u}$ (the normal form of $\evterm{t}_{{\mathrm{2}}}$) using hereditary substitution at type $\gradual{U}$. We use this operation to reduce applications. A second issue is that, while the simple rules dictate how to evaluate a $\lambda$-term applied to a value, they do not determine how to proceed for applications of the form $ \ottsym{(} \langle \gradual{U} \rangle \, \lambda \mathit{x} \ldotp \evterm{t} \ottsym{)} \ \ottsym{(} \langle \gradual{U}' \rangle \, \evterm{rv} \ottsym{)} $. In such a case, we know that $\cdot \vdash \ottsym{(} \langle \gradual{U} \rangle \, \lambda \mathit{x} \ldotp \evterm{t} \ottsym{)} \ottsym{:} \gradual{U}_1$ and that $ \langle \gradual{U} \rangle\vdash \gradual{U}_1 \cong \gradual{U}_2 $ for some $\gradual{U}_2$. Computing $ (\ottkw{dom}\ \langle \gradual{U} \rangle ) \sqcap \langle \gradual{U}' \rangle $ yields evidence that the type of $\evterm{rv}$ is consistent with the domain of $\gradual{U}_1$, so we ascribe this evidence during substitution to preserve well-typedness. The evidence-typing rules say that the type of an application is found by normalizing the argument value and substituting into the codomain of the function type. To produce a result at this type, we can normalize $\evterm{rv}$ and substitute it into the codomain of $\langle \gradual{U} \rangle$, thereby producing evidence that the actual result is consistent with the return type. In the case where $\evterm{rv}$ is not ascribed with evidence, we can simply behave as if it were ascribed $\langle {\qm } \rangle$ and proceed using the above process. } \subsubsection*{Applying The Unknown Term} The syntax for values only admits application under binders, so we must somehow reduce terms of the form $ \ottsym{(} \myepsilon \, {\qm } \ottsym{)} \ \evterm{v} $. The solution is simple: if the function is unknown, so is its output. Since the unknown term is always accompanied by evidence at runtime, we calculate the result type by substituting the argument into the codomain of the evidence associated with $ {\qm } $. \subsubsection*{The Full Semantics} \begin{figure} \ottdefnStep{} \caption{\lang: \rev{Dynamic Semantics}} \label{fig:gradual-semantics} \end{figure} All other well-typed terms are either values, or contain a redex as a subterm, either of the simple variety or of the varieties described above. Using contextual rules to account for these remaining cases, we have a semantics that satisfies progress and preservation \textit{by construction}. \Autoref{fig:gradual-semantics} gives the full set of rules. \subsection{Example: Running $\mathtt{head}$ of $\mathtt{nil}$} \label{subsec:nilhead-run} We return to the example from \autoref{subsec:type-headnil}, this time explaining its runtime behaviour. Because of consistency, the term $\ottsym{(} \ottkw{Nil} \ \ottkw{Nat} \dblcolon \ottsym{(} \ottkw{Vec} \ \ottkw{Nat} \ {\qm } \ottsym{)} \ottsym{)}$ is given the evidence $\langle \ottkw{Vec} \ \ottkw{Nat} \ {\qm } \rangle$, obtained by computing ${\langle \ottkw{Vec} \ \ottkw{Nat} \ 0 \sqcap \ottkw{Vec} \ \ottkw{Nat} \ {\qm } \rangle}$. Applying consistency to use this as an argument adds the evidence $\langle \ottkw{Vec} \ \ottkw{Nat} \ 1 \rangle$, since we check $\ottsym{(} \ottkw{Nil} \ \ottkw{Nat} \dblcolon \ottsym{(} \ottkw{Vec} \ \ottkw{Nat} \ {\qm } \ottsym{)} \ottsym{)}$ against $\ottkw{dom}\ ( \ottkw{Vec} \ \ottkw{Nat} \ 1 \to \ottkw{Nat} )$. The rule \rrule{StepContext} dictates that we must evaluate the argument to a function before evaluating the application itself. Our argument is $\langle \ottkw{Vec} \ \ottkw{Nat} \ 1 \rangle\langle \ottkw{Vec} \ \ottkw{Nat} \ 0 \rangle( \ottkw{Nil} \ \ottkw{Nat} )$, and since the meet of the evidence types is undefined, we step to $\mathsf{err}$ with \rrule{StepAscrFail}. \section{Properties of \lang} \label{sec:lang-properties} \lang satisfies all the criteria for gradual languages set forth by \citet{refinedCriteria}. \paragraph{Safety} First, \lang is type \replaced{safe}{sound} \textit{by construction}: the runtime semantics are specifically crafted to maintain progress and preservation. We can then obtain the standard safety result for gradual languages, namely that well-typed terms do not get stuck. \begin{restatable}[Type safety]{theorem}{typeSound} \label{thm:typeSound} If $\cdot \vdash \evterm{t} \ottsym{:} \gradual{U}$, then either $\evterm{t} \longrightarrow^{*} \evterm{v}$ for some $\evterm{v}$, $\evterm{t} \longrightarrow^{*} \mathsf{err}$, or $\evterm{t}$ diverges. \end{restatable} \rev{ This means that gradually well-typed programs in \lang may fail with runtime type errors, but they will never get stuck. Among the three main approaches to deal with gradual types in the literature, \lang follows the original approach of \citet{gradualTypeInitial} and \citet{refinedCriteria}, which enforces types eagerly at boundaries, including at higher-order types. This is in contrast with first-order enforcement (a.k.a as transient semantics \citep{Vitousek:2017:BTL:3093333.3009849}), or simple type erasure (a.k.a as optional typing).\footnote{\citet{Greenman:2018:STS:3243631.3236766} present a detailed comparative semantic account of these three approaches.} In particular, while the transient semantics support open world soundness \citep{Vitousek:2017:BTL:3093333.3009849} when implemented on top of a (safe) dynamic language, it is unclear if and how this approach, which is restricted to checking type constructors, can scale to full-spectrum dependent types. \lang is a sound gradually-typed language that requires elaboration of the complete program in order to insert the pieces of evidence that support runtime checking. } \paragraph{Conservative Extension of\ \slang} It is easy to show that \lang is a conservative extension of \slang. This means that any fully-precise \lang programs enjoy the soundness and \added{logical} consistency properties that \slang guarantees. Any statically-typed term is well-typed in \lang by construction, thanks to AGT: on fully precise gradual types, $\alpha \circ \gamma$ is the identity. Moreover, the \textit{only} additions are those pertaining to $ {\qm } $, meaning that if we restrict ourselves to the static subset of terms (and types) without $ {\qm } $, then we have all the properties of the static system. We formalize this as follows: \begin{restatable}{theorem}{staticEmbed} \label{thm:staticEmbed} \added{} \rev{ If $\gradual{Gamma},\gradual{t},\gradual{U}$ are the embeddings of some $\static{Gamma}, \static{t},\static{U}$ into \lang, and $\gradual{Gamma} \vdash \gradual{t} \Leftarrow \gradual{U}$, then $\static{Gamma} \vdash \static{t} \Leftarrow \static{U}$. Moreover, if $\static{t} \longrightarrow^{*} \static{v} $ and $\gradual{t}$ elaborates to $\evterm{t}$, then there exists some $\evterm{v}$ where $\evterm{t} \longrightarrow^{*} \evterm{v}$, where removing evidence from $\evterm{v}$ yields $\static{v}$ }. \end{restatable} \paragraph{Embedding of Untyped Lambda Calculus} A significant property of \lang is that it can fully embed the untyped lambda calculus, including non-terminating terms. Given an untyped embedding function $\lceil t \rceil$ that (in essence) annotates all terms with $ {\qm } $ we can show that any untyped term can be embedded in our system. Since no type information is present, all evidence objects are formed using $ {\qm } $ or $\to$, and the meet operator never fails and untyped programs behave normally in \lang. \begin{restatable}{theorem}{untypedEmbed} \label{thm:untypedEmbed} For any untyped $\lambda$-term $t$ and closing environment $\ \gradual{Gamma}$ that maps all variables to type $ {\qm } $, then $\gradual{Gamma}\vdash \lceil t \rceil \Rightarrow {\qm } $. \rev{Moreover, if $t$ is closed, then $t \longrightarrow^{*} v$ implies that $\lceil t \rceil$ elaborates to $\evterm{t}$ where $\evterm{t} \longrightarrow^{*} \evterm{v} $ and stripping evidence from $\evterm{v}$ yields $v$}. \end{restatable} \paragraph{Gradual Guarantees} \label{subsec:gg-properties} \lang smoothly supports the full spectrum between dependent and untyped programming---a property known as the gradual guarantee~\cite{refinedCriteria}, which comes in two parts. \added{We say that} \rev{$\gradual{Gamma} \sqsubseteq \gradual{Gamma}'$ if they contain the same variables, and for each $(x : \gradual{U}) \in \gradual{Gamma}$, $(x : \gradual{U}') \in \gradual{Gamma}'$ where $\gradual{U} \sqsubseteq \gradual{U}'$}. \begin{restatable}[Gradual Guarantee]{theorem}{gradGuarantee} \label{thm:gradGuarantee} \quad \textsc{(Static Guarantee)} Suppose $\gradual{Gamma} \vdash \gradual{t} \Leftarrow \gradual{U}$ and $ \gradual{U} \sqsubseteq \gradual{U}' $.\ If $\gradual{Gamma} \sqsubseteq \gradual{Gamma}'$ and $\gradual{t} \sqsubseteq \gradual{t}'$, then $\gradual{Gamma}' \vdash \gradual{t}' \Leftarrow \gradual{U}'$. \textsc{(Dynamic Guarantee)} Suppose that $\cdot \vdash \evterm{t}_{{\mathrm{1}}} \ottsym{:} \gradual{U}$, $\cdot \vdash \evterm{t}'_{{\mathrm{1}}} \ottsym{:} \gradual{U}'$, $\evterm{t}_{{\mathrm{1}}}\sqsubseteq\evterm{t}'_{{\mathrm{1}}}$, and $\gradual{U}\sqsubseteq\gradual{U}'$. If $\evterm{t}_{{\mathrm{1}}}\longrightarrow^{*}\evterm{t}_{{\mathrm{2}}}$, then $\evterm{t}'_{{\mathrm{1}}}\longrightarrow^{*}\evterm{t}'_{{\mathrm{2}}}$ where $\evterm{t}_{{\mathrm{2}}}\sqsubseteq\evterm{t}'_{{\mathrm{2}}}$. \end{restatable} AGT ensures that the gradual guarantee holds by construction. Specifically, because approximate normalization and consistent transitivity are monotone with respect to precision, we can establish a weak bisimulation between the steps of the more and less precise versions~\citep{agt}. A novel insight that arises from our work is that we need a restricted form of the dynamic gradual guarantee {\em for normalization} in order to prove the static gradual guarantee. To differentiate it from the standard one, we call it the {\em normalization gradual guarantee}. Because an $\eta$-long term might be longer at a more precise type, we phrase the guarantee modulo $\eta$-equivalence: \added{we say that} \rev{ $\gradual{U}_1 \sqsubseteq^\eta \gradual{U}_2$ if $\gradual{U}_1 =_\eta \gradual{U}'_1$, $\gradual{U}_2 =_\eta \gradual{U}'_2$ and $\gradual{U}'_1 \sqsubseteq \gradual{U}'_2$}. With these defined, we can state the normalization gradual guarantee: \begin{restatable}[Normalization Gradual Guarantee]{lemma}{normGuarantee} \label{thm:normGuarantee} Suppose $\gradual{Gamma}_{{\mathrm{1}}} \vdash \gradual{u}_{{\mathrm{1}}} \leadsfrom\ \gradual{t}_{{\mathrm{1}}} \Leftarrow \gradual{U}_{{\mathrm{1}}}$. If $\gradual{Gamma}_{{\mathrm{1}}} \sqsubseteq^\eta \gradual{Gamma}_{{\mathrm{2}}}$, $ \gradual{t}_{{\mathrm{1}}} \sqsubseteq \gradual{t}_{{\mathrm{2}}} $, and $ \gradual{U}_{{\mathrm{1}}} \sqsubseteq^\eta \gradual{U}_{{\mathrm{2}}} $, then $\gradual{Gamma}_{{\mathrm{2}}} \vdash \gradual{u}_{{\mathrm{2}}} \leadsfrom\ \gradual{t}_{{\mathrm{2}}} \Leftarrow \gradual{U}_{{\mathrm{2}}}$ where $ \gradual{u}_{{\mathrm{1}}} \sqsubseteq^\eta \gradual{u}_{{\mathrm{2}}} $. \end{restatable} \section{Extension: Inductive Types} \label{sec:inductive} Though \lang provides type safety and the gradual guarantees, its lack of inductive types means that programming is cumbersome. \added{Church encodings allow for some induction, but are strictly less powerful than proper inductive types.} Additionally, induction principles, along with basic facts like $0 \neq 1$, cannot be proven in the purely negative Calculus of Constructions~\citep{stump_2017}. However, we can type such a term if we introduce inductive types with eliminators, and allow types to be defined in terms of such eliminations. This section describes how to extend \lang with a few common inductive types---natural numbers, vectors, and an identity type for equality proofs--- along with their eliminators. While not as useful as user-defined types or pattern matching (both of which are important subjects for future work), this specific development illustrates how our approach can be extended to a more full-fledged dependently-typed language. Note that while we show how inductives can be added to the language, extending our metatheory to include inductives is left as future work. \paragraph{Syntax and Typing} \rev{We augment the syntax for terms as follows:} \begin{align*} \gradual{t},\gradual{T} & ::= & \ldots & | \ottkw{Nat} | 0 | \ottkw{Succ}\ \gradual{t} | \ottkw{Vec} \ \gradual{T} \ \gradual{t} | \ottkw{Eq} \ \gradual{T} \ \gradual{t}_{{\mathrm{1}}} \ \gradual{t}_{{\mathrm{2}}} | \ottkw{Refl} \ \gradual{T} \ \gradual{t} | \ottkw{Nil} \ \gradual{t} | \ottkw{Cons} \ \gradual{T} \ \gradual{t}_{{\mathrm{1}}} \ \gradual{t}_{{\mathrm{2}}} \ \gradual{t}_{{\mathrm{3}}} \\ &&& | \ottkw{natElim}\ \gradual{T} \ \gradual{t}_{{\mathrm{1}}} \ \gradual{t}_{{\mathrm{2}}} \ \gradual{t}_{{\mathrm{3}}} | \ottkw{vecElim}\ \gradual{T}_{{\mathrm{1}}} \ \gradual{t}_{{\mathrm{1}}} \ \gradual{T}_{{\mathrm{2}}} \ \gradual{t}_{{\mathrm{2}}} \ \gradual{t}_{{\mathrm{3}}} \ \gradual{t}_{{\mathrm{4}}} | \ottkw{eqElim}\ \gradual{T}_{{\mathrm{1}}} \ \gradual{T}_{{\mathrm{2}}} \ \gradual{t}_{{\mathrm{1}}} \ \gradual{t}_{{\mathrm{2}}} \ \gradual{t}_{{\mathrm{3}}} \ \gradual{t}_{{\mathrm{4}}} \end{align*} \begin{figure} \begin{minipage}{0.45\textwidth} \begin{align*} \ottkw{Nat} & : && \rev{\ottkw{Type} } _{ \ottsym{1} } \\ \ottkw{Vec} & : && \rev{\ottkw{Type} } _{ \ottnt{i} } \to \ottkw{Nat} \to \rev{\ottkw{Type} } _{ \ottnt{i} } \\ \ottkw{Eq} & : && \ottsym{(} \mathtt{A} \ottsym{:} \rev{\ottkw{Type} } _{ \ottnt{i} } \ottsym{)} \rightarrow \mathtt{A} \to \mathtt{A} \to \rev{\ottkw{Type} } _{ \ottnt{i} } \end{align*} \end{minipage} \begin{minipage}{0.45\textwidth} \begin{align*} 0 & : && \ottkw{Nat} \\ \ottkw{Succ} & : && \ottkw{Nat} \to \ottkw{Nat} \\ \ottkw{Nil} & : && \ottsym{(} \mathtt{A} \ottsym{:} \rev{\ottkw{Type} } _{ \ottnt{i} } \ottsym{)} \rightarrow \ottkw{Vec} \ \mathtt{A} \ 0 \\ \ottkw{Refl} & : && \ottsym{(} \mathtt{A} \ottsym{:} \rev{\ottkw{Type} } _{ \ottnt{i} } \ottsym{)} \rightarrow \ottsym{(} \mathit{x} \ottsym{:} \mathtt{A} \ottsym{)} \rightarrow \ottkw{Eq} \ \mathtt{A} \ \mathit{x} \ \mathit{x} \end{align*} \end{minipage} \begin{align*} \ottkw{Cons} & : && \ottsym{(} \mathtt{A} \ottsym{:} \rev{\ottkw{Type} } _{ \ottnt{i} } \ottsym{)} \rightarrow \ottsym{(} \mathtt{n} \ottsym{:} \ottkw{Nat} \ottsym{)} \rightarrow \ottsym{(} \mathtt{hd} \ottsym{:} \mathtt{A} \ottsym{)} \rightarrow \ottsym{(} \mathtt{tl} \ottsym{:} \ottkw{Vec} \ \mathtt{A} \ \mathtt{n} \ottsym{)} \rightarrow \ottkw{Vec} \ \mathtt{A} \ \ottsym{(} \ottkw{Succ}\ \mathtt{n} \ottsym{)} \\ \ottkw{natElim} & : && \ottsym{(} \mathtt{m} \ottsym{:} \ottsym{(} \ottkw{Nat} \to \rev{\ottkw{Type} } _{ \ottnt{i} } \ottsym{)} \ottsym{)} \rightarrow \ottsym{(} \mathtt{m} \ 0 \ottsym{)} \to \ottsym{(} \ottsym{(} \mathtt{n} \ottsym{:} \ottkw{Nat} \ottsym{)} \rightarrow \mathtt{m} \ \mathtt{n} \to \mathtt{m} \ \ottsym{(} \ottkw{Succ}\ \mathtt{n} \ottsym{)} \ottsym{)} \to \ottsym{(} \mathtt{n} \ottsym{:} \ottkw{Nat} \ottsym{)} \rightarrow \mathtt{m} \ \mathtt{n} \\ \ottkw{vecElim} & : && \ottsym{(} \mathtt{A} \ottsym{:} \rev{\ottkw{Type} } _{ \ottnt{i} } \ottsym{)} \rightarrow \ottsym{(} \mathtt{n} \ottsym{:} \ottkw{Nat} \ottsym{)} \rightarrow \ottsym{(} \mathtt{m} \ottsym{:} \ottsym{(} \ottkw{Vec} \ \mathtt{A} \ \mathtt{n} \to \rev{\ottkw{Type} } _{ \ottnt{i} } \ottsym{)} \ottsym{)} \rightarrow \mathtt{m} \ \ottsym{(} \ottkw{Vec} \ \mathtt{A} \ 0 \ottsym{)} \\ &&& \to \ottsym{(} \ottsym{(} \mathtt{n_2} \ottsym{:} \ottkw{Nat} \ottsym{)} \rightarrow \ottsym{(} \mathtt{h} \ottsym{:} \mathtt{A} \ottsym{)} \rightarrow \ottsym{(} \mathtt{tl} \ottsym{:} \ottkw{Vec} \ \mathtt{A} \ \mathtt{n_2} \ottsym{)} \rightarrow \mathtt{m} \ \mathtt{vec} \to \mathtt{m} \ \ottsym{(} \ottkw{Cons} \ \mathtt{A} \ \ottsym{(} \ottkw{Succ}\ \mathtt{n_2} \ottsym{)} \ \mathtt{hd} \ \mathtt{tl} \ottsym{)} \ottsym{)} \\ &&& \to \ottsym{(} \mathtt{vec} \ottsym{:} \ottkw{Vec} \ \mathtt{A} \ \mathtt{n} \ottsym{)} \rightarrow \mathtt{m} \ \mathtt{vec} \\ \ottkw{eqElim} & : && \ottsym{(} \mathtt{A} \ottsym{:} \rev{\ottkw{Type} } _{ \ottnt{i} } \ottsym{)} \rightarrow \ottsym{(} \mathtt{m} \ottsym{:} \ottsym{(} \mathit{x} \ottsym{:} \mathtt{A} \ottsym{)} \rightarrow \ottsym{(} \mathit{y} \ottsym{:} \mathtt{A} \ottsym{)} \rightarrow \ottkw{Eq} \ \mathtt{A} \ \mathit{x} \ \mathit{y} \to \rev{\ottkw{Type} } _{ \ottnt{i} } \ottsym{)} \\ &&& \rightarrow \ottsym{(} \ottsym{(} \mathit{z} \ottsym{:} \mathtt{A} \ottsym{)} \rightarrow \mathtt{m} \ \mathit{z} \ \mathit{z} \ \ottsym{(} \ottkw{Refl} \ \mathtt{A} \ \mathit{z} \ottsym{)} \ottsym{)} \to \ottsym{(} \mathit{x} \ottsym{:} \mathtt{A} \ottsym{)} \rightarrow \ottsym{(} \mathit{y} \ottsym{:} \mathtt{A} \ottsym{)} \rightarrow \ottsym{(} \mathtt{p} \ottsym{:} \ottkw{Eq} \ \mathtt{A} \ \mathit{x} \ \mathit{y} \ottsym{)} \rightarrow \ottsym{(} \mathtt{m} \ \mathit{x} \ \mathit{y} \ \mathtt{p} \ottsym{)} \end{align*} \caption{Constructor and Eliminator Types} \label{fig:elimTypes} \end{figure} The typing rules are generally straightforward. We omit the full rules, but we essentially type them as functions that must be fully applied, with the types given in \autoref{fig:elimTypes}. Each form checks its arguments against the specified types, and the rule \rrule{GCheckSynth} ensures that typechecking succeeds so long as argument types are consistent with the expected types. Adding these constructs to canonical forms is interesting. Specifically, the introduction forms are added as atomic forms, and the eliminators become new variants of the canonical spines. Since $\ottkw{natElim}$ applied to a $ \ottkw{Nat} $ is a redex, canonical forms can eliminate variables. \added{Eliminators take one fewer argument than in the term version, since the last argument is always the rest of the spine in which the eliminator occurs.} \begin{align*} \gradual{rr},\gradual{RR} & ::= & \ldots | \ottkw{Nat} | 0 | \ottkw{Succ}\ \gradual{u} | \text{etc.\ldots}\\ \gradual{e} & ::= & \ldots | \ottkw{natElim}\ \gradual{u}_{{\mathrm{1}}}\ \gradual{u}_{{\mathrm{2}}}\ \gradual{u}_{{\mathrm{3}}} | \ottkw{vecElim}\ \gradual{U}_{{\mathrm{1}}}\ \gradual{u}_{{\mathrm{1}}}\ \gradual{U}_{{\mathrm{2}}}\ \gradual{u}_{{\mathrm{2}}}\ \gradual{u}_{{\mathrm{3}}}\ | \text{etc.\ldots} \end{align*} \paragraph{Normalization} We extend hereditary substitution to inductive types. \added{Unfortunately, we must treat hereditary substitution as a \textit{relation} between normal forms. The strictly-decreasing metric we previously used no longer holds for inductive types, so we have not proved that hereditary substitution with inductives is a well-defined function; this is left as future work.} For introduction forms, we simply substitute in the subterms. For eliminators, if we are ever replacing $\mathit{x}$ with $\gradual{u}'$ in $ \mathit{x} \gradual{e} \ \ottkw{natElim}\ \gradual{u}_{{\mathrm{1}}}\ \gradual{u}_{{\mathrm{2}}}\ \gradual{u}_{{\mathrm{3}}}$, then we substitute in $ \mathit{x} \gradual{e} $ and see if we get $ 0 $ or $\ottkw{Succ}$ back. If we get $ 0 $, we produce $\gradual{u}_{{\mathrm{2}}}$, and if we get $ \ottkw{Succ}\ \mathtt{n}$, we compute the recursive elimination for $\mathtt{n}$ as $\gradual{u}'_{{\mathrm{2}}}$, and substitute $\mathtt{n}$ and $\gradual{u}'_{{\mathrm{2}}}$ for the arguments of $\gradual{u}_{{\mathrm{3}}}$. Vectors are handled similarly. An application of $\ottkw{eqElim}$ to $ \ottkw{Refl} \ \mathtt{A} \ \mathit{x} $ simply returns the given value of type $ \mathtt{m} \ \mathit{x} \ \mathit{x} \ \ottsym{(} \ottkw{Refl} \ \mathit{x} \ \mathtt{A} \ottsym{)} $ as a value of type $ \mathtt{m} \ \mathit{x} \ \mathit{y} \ \mathtt{p} $. How should we treat eliminations with $ {\qm } $ as a head? Since $ {\qm } $ represents the set of all static values, the result of eliminating it is the abstraction of the eliminations of all possible values. Since these values may produce conflicting results, the abstraction is simply $ {\qm } $, which is our result. However, for equality, we have a special case. Each instance of $\ottkw{eqElim}$ can have only one possible result: the given value, considered as having the output type. Then, we abstract a singleton set. This means we can treat each application of $\ottkw{eqElim}$ to $ {\qm } $ as an application to $ \ottkw{Refl} \ {\qm } \ {\qm } $. This principle holds for any single-constructor inductive type. With only functions, we needed to return $ {\qm } $ any time we applied a dynamically-typed function. However, with eliminators, we are always structurally decreasing on the value being eliminated. For $\ottkw{natElim}$, we can eliminate a $ {\qm } $-typed value provided it is $ 0 $ or $\ottkw{Succ}\ \gradual{u}$, but otherwise we must produce $ {\qm } $ for substitution to be total and type-preserving. Other types are handled similarly. \paragraph{Runtime Semantics} The semantics are straightforward. Eliminations are handled as with hereditary substitution: eliminating $ {\qm } $ produces $ {\qm } $, except with $ \ottkw{Eq} $, where $ {\qm } $ behaves like $ \ottkw{Refl} \ {\qm } \ {\qm } $ when eliminating. When applying eliminators or constructors, evidence is composed as with functions. One advantage of \lang is that the meet operator on evidence \added{allows definitional equality checks to be moved to runtime}. Thus, if we write $ \ottkw{Refl} \ {\qm } \ {\qm } $, but use it at type $ \ottkw{Eq} \ \mathtt{A} \ \mathit{x} \ \mathit{y} $, then it is ascribed with evidence $\langle \ottkw{Eq} \ \mathtt{A} \ \mathit{x} \ \mathit{y} \rangle$. If we ever use this proof to transform a value of type $ \mathtt{P} \ \mathit{x} $ into one of type $ \mathtt{P} \ \mathit{y} $, the meet operation on the evidence ensures that the result actually has type $ \mathtt{P} \ \mathit{y} $. Returning to the $\mathtt{head'}$ function from \autoref{subsec:gdtl-action}, in $ \mathtt{head'} \ \ottkw{Nat} \ 0 \ {\qm } \ {\qm } \ \mathtt{staticNil} $, the second $ {\qm } $ is ascribed with the evidence $\langle \ottkw{Eq} \ \ottkw{Nat} \ 0 \ \ottsym{(} \ottkw{Succ}\ {\qm } \ottsym{)} \rangle$. The call to $\mathtt{rewrite}$ using this proof tries to convert a $ \ottkw{Vec} $ of length $ 0 $ into one of length $ 1 $, which adds the evidence $\langle \ottkw{Eq} \ \ottkw{Nat} \ 0 \ 1 \rangle$ to our proof term. Evaluation tries to compose the layered evidence, but fails with the rule \rrule{StepAscrFail}, since they cannot be composed. \section{Related Work} \label{sec:related} \paragraph{\slang} The static dependently-typed language \slang, from which \lang is derived, incorporates many features and techniques from the literature. The core of the language is very similar to that of $\mathsf{CC}_\omega$~\citep{COQUAND198895}, albeit without an impredicative $\mathsf{Prop}$ sort. The core language of Idris~\citep{idrisPaper}, $\mathsf{TT}$, also features cumulative universes with a single syntactic category for terms and types. Our use of canonical forms draws heavily from work on the Logical Framework (LF)~\citep{Harper:1993:FDL:138027.138060, mechanizingLF}. The bidirectional type system we adopt is inspired by the tutorial of \citet{basicDepTutorial}. Our formulation of hereditary substitution~\citep{hereditary,churchCurry} in \slang is largely drawn from that of~\citet{mechanizingLF}, particularly the type-outputting judgment for substitution on atomic forms, and the treatment of the variable type as an extrinsic argument. \paragraph{Mixing Dependent Types and Non-termination} Dependently-typed languages that admit non-termination either give up on logical consistency altogether ($\Omega$mega~\citep{DBLP:conf/cefp/SheardL07}, Haskell), or isolate a sublanguage of pure terminating expressions. This separation can be either enforced through the type system and/or a termination checker (Aura~\cite{DBLP:conf/icfp/JiaVMZZSZ08}, F$\star$~\cite{mumon}, Idris~\cite{idrisPaper}), or through a strict syntactic separation (Dependent ML~\cite{Xi1999}, ATS~\cite{Chen:2005:CPT:1086365.1086375}). The design space is very wide, reflecting a variety of sensible tradeoffs between expressiveness, guarantees, and flexibility. The Zombie language~\citep{EPTCS76.9, Casinghino:2014:CPP:2535838.2535883} implements a flexible combination of programming and proving. The language is defined as a the programmatic fragment that ensures type safety but not termination, and a logical fragment (a syntactic subset of the programmatic one) that guarantees logical consistency. Programmers must declare in which fragment a given definition lives, but mobile types and cross-fragment case expressions allow interactions between the fragments. Zombie embodies a different tradeoff from \lang: while the logical fragment is consistent as a logic, typechecking may diverge due to normalization of terms from the programmatic fragment. In contrast, \lang eschews logical consistency as soon as imprecision is introduced (with~$ {\qm } $), but approximate normalization ensures that typechecking terminates. In general, gradual dependent types as provided in \lang can be interpreted as a smooth, tight integration of such a two-fragment approach. Indeed, the subset of \lang that is fully precise corresponds to \slang, which is consistent as a logic. However, in the gradual setting, the fragment separation is fluid: it is driven by the precision of types and terms, which is free to evolve at an arbitrarily fine level of granularity. Also, the mentioned approaches are typically not concerned with accommodating the flexibility of a fully dynamically-typed language. \paragraph{Mixing Dependent Types and Simple Types} Several approaches have explored how soundly combine dependent types with non-dependently typed components. \citet{10.1007/1-4020-8141-3_34} support a two-fragment language, where runtime checks at the boundary ensure that dependently-typed properties hold. The approach is limited to properties that are expressible as boolean-valued functions. \citet{Tanter:2015:GCP:2816707.2816710} develop a cast framework for subset types in Coq, allowing one to assert a term of type $A$ to have the subset type $\{ a : A \mid P\;a \}$ for any decidable (or checkable) property $P$. They use an axiom to represent cast errors. \citet{Osera:2012:DI:2103776.2103779} present \textit{dependent interoperability} as a multi-language approach to combine both typing disciplines, mediated by runtime checks. Building on the subset cast framework (reformulated in a monadic setting instead of using axiomatic errors), \citet{dagandAl:icfp2016,dagand_tabareau_tanter_2018} revisit dependent interoperability in Coq via type-theoretic Galois connections that allow automatic lifting of higher-order programs. Dependent interoperability allows exploiting the connection between pre-existing types, such as $ \ottkw{Vec} $ and $ \ottkw{List} $, imposing the overhead of data structure conversions. The fact that $ \ottkw{List} $ is a less precise structure than $ \ottkw{Vec} $ is therefore defined {\em a posteriori}. In contrast, in \lang, one can simply define $ \ottkw{List} \ \mathtt{A} $ as an alias for $ \ottkw{Vec} \ \mathtt{A} \ {\qm } $, thereby avoiding the need for deep structural conversions. The work of \citet{lehmannTanter:popl2017} on gradual refinement types includes some form of dependency in types. Gradual refinement types range from simple types to logically-refined types, i.e. subset types where the refinement is drawn from an SMT-decidable logic. Imprecise logical formulae in a function type can refer to arguments and variables in context. This kind of value dependency is less expressive than the dependent type system considered here. Furthermore, \lang is the first gradual language to allow $ {\qm } $ to be used in both term and type position, and to fully embed the untyped lambda calculus. \paragraph{Programming with Holes} Finally, we observe that using $ {\qm } $ in place of proof terms in \lang is related to the concept of \textit{holes} in dependently-typed languages. Idris~\citep{idrisPaper} and Agda~\citep{agdaPaper} both allow typechecking of programs with typed holes. The main difference between $ {\qm } $ and holes in these languages is that applying a hole to a value results in a stuck term, while in \lang, applying $ {\qm } $ to a value produces another $ {\qm } $. Recently, \citet{DBLP:journals/pacmpl/OmarVCH19} describe Hazelnut, a language and programming system with \textit{typed holes} that fully supports evaluation in presence of holes, including reduction {\em around} holes. The approach is based on Contextual Modal Type Theory~\citep{Nanevski:2008:CMT:1352582.1352591}. It would be interesting to study whether the dependently-typed version of CMTT~\citep{Pientka:2008:PPE:1389449.1389469} could be combined with the evaluation approach of Hazelnut, and the IDE support, in order to provide a rich programming experience with gradual dependent types. \section{Conclusion} \label{sec:conclusion} \lang represents a glimpse of the challenging and potentially large design space induced by combining dependent types and gradual typing. Specifically, this work proposes approximate normalization as a novel technique for designing gradual dependently-typed languages, in a way that ensures decidable typechecking and naturally satisfies the gradual guarantees. Currently, \lang lacks a number of features required of a practical dependently-typed programming language. While we have addressed the most pressing issue of supporting inductive types in Section~\ref{sec:inductive}, the metatheory of this extension, in particular the proof of strong normalization, is future work. It might also be interesting to consider pattern matching as the primitive notion for eliminating inductives, as in Agda, instead of elimination principles as in Coq; the equalities implied by dependent matches could be turned into runtime checks for gradually-typed values. Future work includes supporting implicit arguments and higher-order unification, blame tracking~\citep{10.1007/978-3-642-00590-9_1}, and efficient runtime semantics with erasure of computationally-irrelevant arguments~\cite{DBLP:conf/types/BradyMM03}. Approximate normalization might be made more precise by exploiting {\em termination contracts}~\citep{nguyen2018sizechange}. \paragraph{{\bf Acknowledgments}} We thank the anonymous reviewers for their constructive feedback.
{'timestamp': '2019-08-23T02:09:58', 'yymm': '1906', 'arxiv_id': '1906.06469', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06469'}
arxiv
\subsection{Distribution Shift Error Checking Oracle} As we have discussed in Section~\ref{sec:intro}, in reinforcement learning, we often need to know whether a predictor learned from samples generated from one distribution $\mathcal{D}_1$ can predict well on another distribution $\mathcal{D}_2$. This is related to off-policy learning for which one often needs to bound the probability density ratio between $\mathcal{D}_1$ and $\mathcal{D}_2$ on all state-action pair. When function approximation scheme is used, we naturally arrive at the following oracle. \begin{oracle}[Distribution Shift Error Checking Oracle $\left(\mathcal{D}_1,\mathcal{D}_2,\epsilon_1,\epsilon_2, \Lambda\right)$]\label{oracle:dist_shift_oracle} For two given distributions $\mathcal{D}_1,\mathcal{D}_2$ over $\mathcal{S}$, two real numbers $\epsilon_1$ and $\epsilon_2$, and a regularizer $\Lambda : \mathcal{Q} \times \mathcal{Q} \to \mathbb{R}$, define \begin{align*} v = &\max_{f_1,f_2 \in \mathcal{Q}} \mathbb{E}_{s\sim \mathcal{D}_2}\left[\left(f_1(s)-f_2(s)\right)^2\right]\\ \text{s.t. } &\mathbb{E}_{s \sim \mathcal{D}_1} \left[\left(f_1(s)-f_2(s)\right)^2\right] + \Lambda(f_1,f_2) \le \epsilon_1. \end{align*} The oracle returns $\mathrm{True}$~if $v \ge \epsilon_2$, and $\mathrm{False}$~otherwise. \end{oracle} To motivate this oracle, let $f_2$ be the optimal $Q$-function and $f_1$ is a predictor we learned using samples generated from distribution $\mathcal{D}_1$. In this scenario, we know $f_1$ has a small expected error $\epsilon_1$ on distribution $\mathcal{D}_1$. Note since we maximize over the entire function class $\mathcal{Q}$, $v$ is an upper bound on the expected error of $f_1$ on distribution $\mathcal{D}_2$. If $v$ is large enough, say larger than $\epsilon_2$, then it could be the case that we cannot predict well on distribution $\mathcal{D}_2$. On the other hand, if $v$ is small, we are certain that $f_1$ has small error on $\mathcal{D}_2$. Here we add a regularization term $\Lambda(f_1,f_2)$ to prevent pathological cases. The concrete choice of $\Lambda$ will be given later. In practice, it is impossible to get access to the underlying distributions $\mathcal{D}_1$ and $\mathcal{D}_2$. Thus, we use samples generated from these two distributions instead. \begin{oracle}[Sample-based Distribution Shift Error Checking Oracle $\left(D_1,D_2,\epsilon_1,\epsilon_2, \Lambda\right)$] \label{oracle:dist_shift_oracle_sample} For two set of states $D_1, D_2 \subseteq \mathcal{S}$, two real numbers $\epsilon_1$ and $\epsilon_2$, and a regularizer $\Lambda : \mathcal{Q} \times \mathcal{Q} \to \mathbb{R}$, define \begin{align*} &v = \max_{f_1,f_2 \in \mathcal{Q}} \frac{1}{\abs{D_2}}\sum_{t_i \in D_2}\left[\left(f_1(t_i)-f_2(t_i)\right)^2\right]\\ &\text{s.t. } \frac{1}{\abs{D_1}}\sum_{s_i \in D_1} \left[\left(f_1(s_i)-f_2(s_i)\right)^2\right] + \Lambda(f_1,f_2)\le \epsilon_1. \end{align*} The oracle returns $\mathrm{True}$~if $v \ge \epsilon_2$ and $\mathrm{False}$~otherwise. If $D_1 = \emptyset$, the oracle simply returns $\mathrm{True}$. \end{oracle} An interesting property of Oracle~\ref{oracle:dist_shift_oracle_sample} is that it only depends on the states and does not rely any label information. \subsection{Main Algorithm} Now we describe our algorithm. We maintain three sets of global variables. \begin{enumerate*} \item $\left\{f_h^a\right\}_{a \in \mathcal{A}, h \in [H]}$. These are our estimated $Q$-functions for all actions $a \in \mathcal{A}$ and all levels $h \in [H]$. \item $\left\{\Pi_h\right\}_{h \in [H]}$. For each level $h \in [H]$, $\Pi_h$ is a set of exploration policies for level $h$, which we use to collect data. \item $\left\{D_h\right\}_{h \in [H]}$. For each $h \in [H]$, $D_h = \left\{s_{h,i}\right\}_{i = 1}^N$ is a set of states in $\mathcal{S}_h$. \end{enumerate*} We initialize these global variables in the following manner. For $\left\{f_h^a\right\}_{a \in \mathcal{A}, h \in [H]}$, we initialize them arbitrarily. For each $h \in [H]$, we initialize $\Pi_h$ to be a single purely random exploration policy, i.e., $\Pi_h = \{\pi\}$, where $\pi(s) = \mathrm{unif}\left(\mathcal{A}\right)$ for all $s \in \mathcal{S}$. We initialize $\left\{D_h\right\}_{h \in [H]}$ to be empty sets. Algorithm~\ref{algo:general_main} uses Algorithm~\ref{algo:collect_learn} to learn predictors for each level $h \in [H]$. Algorithm~\ref{algo:collect_learn} takes $h \in [H]$ as input, tries to learn predictors $\left\{f_h^a\right\}_{a \in \mathcal{A}}$ at level $h$. Algorithm~\ref{algo:learn_a_level} takes $h \in [H]$ and $a \in \mathcal{A}$ as inputs, and checks whether the predictors learned for later levels $h' > h$ are accurate enough under the current policy. Now we explain Algorithm~\ref{algo:collect_learn} and Algorithm~\ref{algo:learn_a_level} in more detail. Algorithm~\ref{algo:collect_learn} iterates all actions, and for each action $a \in \mathcal{A}$, it uses Algorithm~\ref{algo:learn_a_level} to check whether we can learn the $Q$-function that corresponds to $a$ well. After executing Algorithm~\ref{algo:learn_a_level}, we are certain that we can learn $f_h^a$ well (we will explain this in the next paragraph), and thus construct a set of new policies $\Pi_h^a = \{\pi_h^a\}_{\pi_h \in \Pi_h}$, in the following way. For each policy $\pi_h \in \Pi_h$, we define $\pi_h^a$ as \begin{align} \pi^a_h(s_{h'}) = \begin{cases} \pi_h(s_{h'}) &\text{ if } h' < h \\ a &\text{ if } h'=h\\ \mathrm{argmax}_{a' \in \mathcal{A}} f_{h'}^{a'}(s_{h'}) &\text{ if } h' > h \end{cases}. \label{eqn:collection_policy} \end{align} This policy uses $\pi_h$ as the roll-in policy till level $h$, choose action $a$ at level $h$ and use greedy policy with respect to $\left\{f_{h'}^a\right\}_{h' > h, a \in \mathcal{A}}$, the current estimates of $Q$-functions at level $h+1,\ldots,H$ as the roll-out policy. In each iteration, we sample one policy $\pi$ uniformly at random from $\Pi^a_h$, and use it to collect $(s, y)$, where $s \in \mathcal{S}_h$ and $y\in \mathbb{R}$ is the on-the-go reward. In total we collect a dataset $D_h^a$ with size $N \cdot \abs{\Pi_h}$, and we use regression to learn a predictor on these data. Formally, we calculate \begin{align}f_h^a = \mathrm{argmin}_{f \in \mathcal{Q}} \left[\frac{1}{N \cdot \abs{\Pi_h}}\sum_{(s,y) \in D_h^{a}}\left(f(s)-y\right)^2 + \Gamma(f)\right] . \label{eqn:regerm} \end{align} Here, $\Gamma(f)$ represents a regularization term on $f$. Finally, we update $D_h$ by using each $\pi_h \in \Pi_h$ to collect $N$ states in $\mathcal{S}_h$. Now we explain Algorithm~\ref{algo:learn_a_level}. For each $\pi_h \in \Pi_h$, we use $\pi_{h}^a$ defined in~\eqref{eqn:collection_policy} to collect $N$ trajectories. For each $h' = h+1,\ldots,H$, we set $\widetilde{D}_{\pi_{h}^a,h'} = \left\{s_{h',i}\right\}_{i=1}^N$, where $s_{h',i}$ is the state at level $h'$ in the $i$-th trajectory. Next, for each $h'=H,\ldots,h+1$, we invoke Oracle~\ref{oracle:dist_shift_oracle_sample} on input $D_{h'}$ and $\widetilde{D}_{\pi_h^a,h'}$. Note that $D_{h'}$ was collected when we execute Algorithm~\ref{algo:collect_learn} to learn the predictors at level $h'$ . The oracle will return whether our current predictors at level $h'$ can still predict well on the distribution that generates $\widetilde{D}_{\pi_{h}^a,h'}$. If not, then we add $\pi_{h}^a$ to our policy set $\Pi_{h'}$, and we execute Algorithm~\ref{algo:collect_learn} to learn the predictors at level $h'$ once again. Note it is crucial to iterate $h'$ from $H$ to $h+1$, so that we will always make sure the predictors at later levels are correct. \begin{algorithm}[t] \floatname{algorithm}{Algorithm} \caption{\textsf{Difference Maximization $Q$-learning}~(DMQ)} \label{algo:general_main} \begin{algorithmic}[1] \Statex \textbf{Output}: A near-optimal policy $\pi$. \For{$h = H,H-1,\ldots,1$} \State Run Algorithm~\ref{algo:collect_learn} on input $h$. \EndFor \State Return $\hat{\pi}$, the greedy policy with respect to $\left\{f_h^a\right\}_{a \in \mathcal{A}, h\in [H]}$. \end{algorithmic} \end{algorithm} \begin{algorithm}[t] \floatname{algorithm}{Algorithm} \caption{} \label{algo:collect_learn} \begin{algorithmic}[1] \Statex \textbf{Input}: $h \in [H]$, a target level. \For{$a \in \mathcal{A}$} \State Execute Algorithm~\ref{algo:learn_a_level} on input $(h,a)$.\label{lst:line:check} \State Initialize $D_h^a = \emptyset$. \State Construct a policy set $\Pi_h^a$ according to~\eqref{eqn:collection_policy}. \For{$i=1,\ldots,N \cdot \abs{\Pi_h^a}$} \State Sample $\pi \sim \mathrm{unif}\left(\Pi_h^a\right)$. \State Use $\pi$ to collect $(s_i,y_i)$, where $s_i \in \mathcal{S}_h$ and $y_i$ is the on-the-go reward. \State Add $(s_i,y_i)$ into $D_h^a$. \EndFor \State Learn a predictor $f_h^a = \mathrm{argmin}_{f \in \mathcal{Q}} \left[\frac{1}{N \cdot \abs{\Pi_h}}\sum_{(s,y) \in D_h^{a}}\left(f(s)-y\right)^2 + \Gamma(f)\right] $. \label{lst:line:learn_new} \EndFor \State Set $D_h = \emptyset$. \For{$\pi_h \in \Pi_h$} \State Use $\pi_h$ to collect a set of states $\left\{s_{\pi_h,i}\right\}_{i=1}^N$, where $s_{\pi_h,i} \in \mathcal{S}_h$. \State Add all states $\left\{s_{\pi_h,i}\right\}_{i=1}^N$ into $D_h$. \label{lst:line:add_states} \EndFor \end{algorithmic} \end{algorithm} \begin{algorithm}[t] \floatname{algorithm}{Algorithm} \caption{} \label{algo:learn_a_level} \begin{algorithmic}[1] \Statex \textbf{Input}: target level $h \in [H]$ and an action $a \in \mathcal{A}$. \For{$\pi_h \in \Pi_h$} \State Collect $N$ trajectories using policy $\pi_{h}^a$ defined in \eqref{eqn:collection_policy}. \For{$h'=H,H-1,\ldots,h+1$} \State Let $\widetilde{D}_{\pi_h^a,h'} = \left\{s_{h',i}\right\}_{i=1}^N$ be the states at level $h'$ on the $N$ trajectories collected using $\pi_h^a$. \label{lst:line:tilde} \State Invoke Oracle~\ref{oracle:dist_shift_oracle_sample} on input $\left(D_{h'}, \widetilde{D}_{\pi_h^a,h'}, \frac{\epsilon_s}{\abs{\Pi_{h'}}}, \epsilon_t, \Lambda_{\Pi_{h'}}\right)$. \label{lst:line:invoke_oracle} \If{Oracle~\ref{oracle:dist_shift_oracle_sample} returns $\mathrm{True}$} \label{lst:line:oracle} \State $\Pi_{h'} = \Pi_{h'} \cup \left\{\pi_{h}^a\right\}$. \label{lst:line:add_policy} \State Execute Algorithm~\ref{algo:collect_learn} on input $h'$. \EndIf \EndFor \EndFor \end{algorithmic} \end{algorithm} \subsection{Organization} \label{sec:org} This paper is organized as follows. In Section~\ref{sec:rel}, we review related work. In Section~\ref{sec:pre}, we introduce necessary notations, definitions and assumptions. In Section~\ref{sec:dsec}, we describe the DSEC oracle in detail. In Section~\ref{sec:algo}, we present our general algorithm for $Q$-learning with function approximation. In Section~\ref{sec:linearq}, we instantiate the general algorithm to the linear function approximation case, and present our main theorem. We conclude and discuss future works in Section~\ref{sec:dis}. All technical proofs are deferred to the appendix. \section{Introduction} \label{sec:intro} \input{intro.tex} \section{Related Work} \label{sec:rel} \input{rel.tex} \section{Preliminaries} \label{sec:pre} \input{pre.tex} \section{Distribution Shift Error Checking Oracle} \label{sec:dsec} \input{desc.tex} \section{Difference Maximization $Q$-learning } \label{sec:algo} \input{general.tex} \section{Provably Efficient $Q$-learning with Linear Function Approximation} \label{sec:linearq} \input{linearq.tex} \section{Discussion} \label{sec:dis} \input{discussions.tex} \section*{Acknowledgements} \label{sec:ack} \input{ack.tex}
{'timestamp': '2019-06-17T02:18:25', 'yymm': '1906', 'arxiv_id': '1906.06321', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06321'}
arxiv
\section{Introduction} \label{introduction} Submodular functions provide a rich class of expressible models for a variety of machine learning problems. Submodular functions occur naturally in two flavors. In minimization problems, they model notions of cooperation, attractive potentials, and economies of scale, while in maximization problems, they model aspects of coverage, diversity, and information. A set function $f: 2^V \to \mathbb R$ over a finite set $V = \{1, 2, \ldots, n\}$ is \emph{submodular} \cite{fujishige2005submodular} if for all subsets $S, T \subseteq V$, it holds that $f(S) + f(T) \geq f(S \cup T) + f(S \cap T)$. Given a set $S \subseteq V$, we define the \emph{gain} of an element $j \notin S$ in the context $S$ as $f(j | S) = f(S \cup j) - f(S)$. A perhaps more intuitive characterization of submodularity is as follows: a function $f$ is submodular if it satisfies \emph{diminishing marginal returns}, namely $f(j | S) \geq f(j | T)$ for all $S \subseteq T, j \notin T$, and is \emph{monotone} if $f(j | S) \geq 0$ for all $j \notin S, S \subseteq V$. \arxiv{Two central optimization problems involving submodular functions are submodular minimization~\cite{fujishige2005submodular, rkiyersemiframework2013} and submodular maximization~\cite{nemhauser1978, feldman2012optimal}. Moreover, it is often natural to want to optimize these functions subject to combinatorial constraints~\cite{nemhauser1978, rkiyersemiframework2013, jegelka2011-inference-gen-graph-cuts, goel2009optimal}. Moreover, several combinatorial optimization problems involve minimizing one submodular function, while maximizing another function. Furthermore, in applications, these occur as maximizing or minimizing a submodular function subject to upper bound or lower bound constraints. These problems are called Submodular Cost Submodular Cover (\textsc{scsc}) and Submodular Cost Submodular Knapsack (\textsc{scsk}) introduced in in~\cite{nipssubcons2013}.\looseness-1} In this paper, we shall study a framework of robust submodular optimization. Often times in applications we want to optimize several objectives (or criteria) together. There are two natural formulations of this. One is the average case, where we can optimize the (weighted) sum of the submodular functions. Examples of this have been studied in data summarization applications~\cite{lin2012learning, tsciatchek14image, gygli2015video}. The other is robust or worst case, where we want to maximize (or minimize) the minimum (equivalently maximum) among the functions. Examples of this have been proposed for sensor placement and observation selection~\cite{krause08robust}. Robust or worst case optimization is becoming increasingly important since solutions achieved by minimization and maximization can be unstable to perturbations in data. Often times submodular functions in applications are instantiated from various properties of the data (features, similarity functions etc.) and obtaining results which are robust to perturbations and variations in this data is critical. Given monotone submodular functions $f_1, f_2, \cdots, f_l$ to minimize and $g_1, g_2, \cdots, g_k$ to maximize, consider the following problems: \begin{align} \mbox{Problem 1: }\min_{X \in \mathcal C} \max_{i = 1:l} f_i(X), \,\,\,\,\,\, \mbox{Problem 2: } \max_{X \in \mathcal C} \min_{i = 1:k} g_i(X) \nonumber \end{align} $\mathcal C$ stands for combinatorial constraints, which include cardinality, matroid, spanning trees, cuts, s-t paths etc. We shall call these problems \textsc{Robust-SubMin} and \textsc{Robust-SubMax}. Note that when $k = 1, l = 1$, we get back constrained submodular minimization and constrained submodular maximization. We will also study special cases of \textsc{Robust-SubMin} and \textsc{Robust-SubMax} when the constraints are defined via another submodular function. We study two problems: a) minimize the functions $f_i$'s while having lower bound constraints on the $g_i$'s (\textsc{Robust-scsc}), and b) maximize the functions $g_i$'s subject to upper bound constraints on $f_i$'s (\textsc{Robust-scsk}). \begin{align} \mbox{Problem 3: } \min_{X \subseteq V} \max_{i=1:l} f_i(X) \,\, | \,\, g_i(X) \geq c_i, i = 1, \cdots k \nonumber \\ \mbox{Problem 4: }\max_{X \subseteq V} \min_{i = 1:k} g_i(X) \,\, | \,\, f_i(X) \leq b_i, i = 1, \cdots l \nonumber \end{align} Problems 3 and 4 attempt to simultaneously minimize the functions $f_i$ while maximizing $g_i$. \arxiv{Finally, a natural extension of these problems is to have a joint average/worst case objective where we optimize $(1 - \lambda) \min_{i = 1:k} g_i(X) + \lambda/k \sum_{i = 1}^k g_i(X)$ and $(1 - \lambda) \max_{i = 1:l} f_i(X) + \lambda/l \sum_{i = 1}^l f_i(X)$ in Problems 1 - 4. We shall call these problems the \textsc{Mixed} versions (\textsc{Mixed-SubMax}, \textsc{Mixed-SubMin} etc.) However we point out that the \textsc{Mixed} case for Problems 1-4 is a special case of \textsc{Robust} optimization. Its easy to see that we can convert this into a \textsc{Robust} formulation by defining $f^{\prime}_i(X) = (1 - \lambda)f_i(X) + \lambda/l \sum_{i = 1}^l f_i(X)$ and $g^{\prime}_i(X) = (1 - \lambda)g_i(X) + \lambda/k \sum_{i = 1}^k g_i(X)$ and then defining the \textsc{Robust} optimization on $f^{\prime}_i$'s and $g^{\prime}_i$.}\looseness-1 \subsection{Motivating Applications} This section provides an overview of two specific applications which motivate Problems 1-4. We also list down a few more motivating applications in the extended version. \noindent \textbf{Robust Co-operative Cuts and Matchings: } Co-operative cuts have proven to be a very rich class of models for image segmentation where one can model co-operation between edges to solve the shrinking bias problem (elongated edges not getting segmented properly)~\cite{jegelka2011-inference-gen-graph-cuts, jegelka2011-nonsubmod-vision}. Another application is co-operative matching where one can use co-operation among spatially similar groups of pixels to be matched together~\cite{iyer2019near}. Both these cases have been formulated as submodular minimization under combinatorial constraints such as s-t cuts and matchings. The way we can model this is by finding a clustering among the pixels and defining clustered concave over modular functions~\cite{jegelka2011-nonsubmod-vision, iyer2019near}. Instead of taking a single clustering or an average among clusterings, one can pose this as a robust case problem where we minimize the worst among the clusterings to achieve more robust segmentations (equivalently assignments). In this case, \textsc{Robust-SubMin} is a natural formulation.\looseness-1 \noindent \textbf{Robust Data Subset Selection: } Submodular functions have successfully been used for several data subset selection in domains such as image classification~\cite{kaushal2019learning}, speech recognition~\cite{wei2013using} and machine translation~\cite{kirchhoff2014-submodmt}. \cite{wei2015submodularity} prove that the problem of selecting the maximum likelihood subset of a training dataset is a submodular optimization problem for several classifiers including nearest neighbor, naive Bayes etc. Another approach, which we shall study in this paper, is selecting data-sets which are robust to several data subset selection models $g_1, \cdots, g_k$. These models can be defined via different submodular functions, different choice of features, perturbations in the feature space and different target distributions where we want to use these models. In this case, we can pose this as an instance of \textsc{Robust-SubMax} where we want to maximize the minimum among the utility functions Furthermore, it is also natural to select subsets of data which minimize the complexity of the dataset~\cite{liu2017svitchboard, lin2011optimal}. In this case, the functions $f$ captures the complexity of the data-sets $X$ (for example, vocabulary size in speech recognition and number of objects in object detection). This is naturally an instance of \textsc{Robust-SCSK} with $g_i$ being the data selection models, while $f$ is the complexity of the selected subset ($l = 1$). We can also define multiple complexity functions $f_i$, where each function is defined via different perturbations in the vocabulary (obtained by say randomly deleting a certain fraction of words from the vocabulary function).\looseness-1 \arxiv{\noindent \textbf{Robust Observation Selection: } \cite{krause2008near} study the problem of robust submodular maximization with multiple submodular objectives. They argue how for several applications including robust experimental design and sensor placement, it is important to select observations which are robust to several objectives. This is an instance of \textsc{Robust-SubMax}. However, often we want to select observations with more general and with multiple co-operative cost constraints (the constraints here would be submodular) and we have an instance of \textsc{Robust-SCSK}. Another natural model here is to \textsc{Mixed-SubMax} and \textsc{Mixed-SCSK}. \noindent \textbf{Submodular Models for Summarization: } Submodular Maximization is a natural formulation for various summarization problems including Document summarization~\cite{linacl, lin2012learning}, image summarization~\cite{tsciatchek14image} and video summarization~\cite{gygli2015video, kaushal2018framework}. Most models today are average case (i.e. sums of submodular components). A better objective is \textsc{Mixed-SubMax} where we weigh both the worst case and average case objectives.} \subsection{Related Work and Our Contributions} \textbf{Submodular Minimization, Maximization and SCSC/SCSK: } Problems 1 and 2 are direct generalizations of constrained submodular minimization and maximization. Both these problems are NP hard under constraints even when $f$ is monotone~\cite{nemhauser1978, wolsey1982analysis, goel2009optimal, jegelka2011-inference-gen-graph-cuts}. The greedy algorithm achieves a $1- 1/e$ approximation for cardinality constrained maximization and a $1/2$ approximation under matroid constraints~\cite{fisher1978analysis}. \cite{chekuri2011submodular} achieved a tight $1 - 1/e$ approximation for matroid constraints using the continuous greedy. \cite{kulik2009maximizing} later provided a similar $1 - 1/e$ approximation under multiple knapsack constraints. Constrained submodular minimization is much harder -- even with simple constraints such as a cardinality lower bound constraints, the problems are not approximable better than a polynomial factor of $\Omega(\sqrt{n} )$~\cite{svitkina2008submodular}. Similarly the problems of minimizing a submodular function under covering constraints~\cite{iwata2009submodular}, spanning trees, perfect matchings, paths~\cite{goel2009approximability} and cuts~\cite{jegelka2011-inference-gen-graph-cuts} have similar polynomial hardness factors. In all of these cases, matching upper bounds (i.e approximation algorithms) have been provided~\cite{svitkina2008submodular,iwata2009submodular,goel2009approximability,jegelka2011-inference-gen-graph-cuts}. In~\cite{rkiyersemiframework2013, curvaturemin}, the authors provide a scalable semi-gradient based framework and curvature based bounds which improve upon the worst case polynomial factors for functions with bounded curvature $\kappa_f$ (which several submodular functions occurring in real world applications have). Problems 3 and 4 generalize SCSC and SCSK studied in~\cite{nipssubcons2013}. The authors provide tight approximation guarantees in this setting using the the semi-gradient framework~\cite{rkiyersemiframework2013} and the Ellipsoidal approximations~\cite{goemans2009approximating}. Similar to~\cite{curvaturemin} the authors also provide curvature based guarantees.\looseness-1 \textbf{Robust Submodular Maximization: } One of the first papers to study robust submodular maximization (problem 2) was~\cite{krause08robust}, where the authors study \textsc{Robust-SubMax} with cardinality constraints. The authors reduce this problem to a submodular set cover problem using the \emph{saturate} trick to provide a bi-criteria approximation guarantee. \cite{anari2019robust} extend this work and study \textsc{Robust-SubMax} subject to matroid constraint. They provide bi-criteria algorithms by creating a union of $O(\log l/\epsilon)$ independent sets, with the union set having a guarantee of $1 - \epsilon$. They also discuss extensions to knapsack and multiple matroid constraints and provide bicriteria approximation of $(1 - \epsilon, O(\log l/\epsilon))$. \cite{powers2017constrained} also study the same problem. However, they take a different approach by presenting a bi-criteria algorithm that outputs a feasible set that is good only for a fraction of the $k$ submodular functions $g_i$. \cite{chen2017robust, wilder2017equilibrium} study a slightly general problem of robust non-convex optimization (of which robust submodular optimization is a special case), but they provide weaker guarantees compared to \cite{krause2008efficient, anari2019robust}. \arxiv{Another related problem, which is also called \emph{Robust Submodular Maximization}~\cite{orlin2018robust} attempts to select subsets which maximize a submodular function and are robust to up to $\tau$ deletions. Mathematically, this problem can be cast as $\max_{|A| \leq k} \min_{Z \subseteq A, |Z| \leq \tau} f(A - Z)$. Note that this is a special case of the robust submodular maximization studied in~\cite{krause08robust} except that $k$ here is potentially exponential in $\tau$. \cite{orlin2018robust} provide constant factor approximation algorithms for this problem. The results were later improved by~\cite{bogunovic2017robust}. Another version of this problem was considered by~\cite{staib2018distributionally} where they study distributionally robust submodular optimization.} \textbf{Robust Min-Max Combinatorial Optimization: } From a minimization perspective, several researchers have studied robust min-max combinatorial optimization (a special case of \textsc{Robust-SubMin} with modular functions) under different combinatorial constraints (see~\cite{aissi2009min, kasperski2016robust} for a survey). Unfortunately these problems are NP hard even for constraints such as knapsack, s-t cuts, s-t paths, assignments and spanning trees where the standard linear cost problems are poly-time solvable~\cite{aissi2009min, kasperski2016robust}. Moreover, the lower bounds on hardness of approximation is $\Omega(log^{1-\epsilon} l)$ ($l$ is the number of functions) for s-t cuts, paths and assignments~\cite{kasperski2009approximability} and $\Omega(log^{1-\epsilon} n)$ for spanning trees~\cite{kasperski2011approximability} for any $\epsilon > 0$. For the case when $l$ is bounded (a constant), fully polynomial time approximation schemes have been proposed for a large class of constraints including s-t paths, knapsack, assignments and spanning trees~\cite{aissi2010general, aissi2009min, kasperski2016robust}. From an approximation algorithm perspective, the best known general result is an approximation factor of $l$ for constraints where the linear function can be exactly optimized in poly-time. For special cases such as spanning trees and shortest paths, one can achieve improved approximation factors of $O(\log n)$~\cite{kasperski2011approximability, kasperski2018approximating} and $\tilde{O}(\sqrt{n})$\footnote{Ignores $\log$ factors} ~\cite{kasperski2018approximating}.\looseness-1 \textbf{Our Contributions: } Among Problems 1-4, past work has mainly focused on \textsc{Robust-SubMax}. In this paper, we close this gap by providing approximation algorithms and hardness results for the rest of the three problems. For \textsc{Robust-SubMin}, we provide several approximation algorithms, which are either combinatorial or rely on continuous relaxations. We show approximation factors for a large class of constraints including cardinality, matroid span, spanning trees, cuts, paths and matchings and their corresponding hardness bounds. Our approximation bounds depend on $n$ (the ground set) and curvature of the submodular functions $f_i$~\cite{curvaturemin}. For \textsc{Robust-SubMax}, we complement previous work by providing an approximation guarantee for multiple knapsack constraints. In the case of Problems \textsc{Robust-SCSC} and \textsc{Robust-SCSK}, we provide bicriteria approximation\footnote{A bicriteria approximation $(\sigma, \rho)$ for a problem $\min\{f(X) | g(X) \geq c\}$ finds a set $\hat{X}$ such that $f(\hat{X}) \leq \sigma f(X^*)$ and $g(\hat{X} \geq \rho c$ for $\sigma \geq 1, \rho \leq 1$.} factors which depend on the curvature of the $f_i$'s and $n$. We also provide lower bounds for both problems. Furthermore, We show that Problems 3 and 4 are closely related to each other and are \emph{duals} in that a bi-criteria approximation algorithm for one of them can provide a bicriteria approximation of the other one. Finally, we demonstrate the performance of our algorithms on real world applications. \section{Main Ideas and Techniques} In this section, we will review some of the constructs and techniques used in this paper to provide approximation algorithms for Problems 1 - 4. \noindent \textbf{The Submodular Polyhedron and Lov\'asz{} extension: } For a submodular function $f$, the submodular polyhedron $\mathcal P_f$ and the corresponding base polytope $\mathcal B_f$ are respectively defined as $\mathcal P_f = \{ x : x(S) \leq f(S), \forall S \subseteq V \} \;\;\; \mathcal B_f = \mathcal P_f \cap \{ x : x(V) = f(V) \}$. For a vector $x \in \mathbb{R}^V$ and a set $X \subseteq V$, we write $x(X) = \sum_{j \in X} x(j)$. Though $\mathcal P_f$ is defined via $2^n$ inequalities, its extreme point can be easily characterized~\cite{fujishige2005submodular, edmondspolyhedra}. Given any permutation $\sigma$ of the ground set $\{1, 2, \cdots, n\}$, and an associated chain $\emptyset = S^{\sigma}_0 \subseteq S^{\sigma}_1 \subseteq \cdots \subseteq S^{\sigma}_n = V$ with $S^{\sigma}_i = \{ \sigma(1), \sigma(2), \dots, \sigma(i) \}$, a vector $h^f_{\sigma}$ satisfying, $h^f_{\sigma}(\sigma(i) = f(S^{\sigma}_i) - f(S^{\sigma}_{i-1}) = f(\sigma(i) | S^{\sigma}_{i-1}), \forall i = 1, \cdots, n$ forms an extreme point of $\mathcal P_f$. Moreover, a natural convex extension of a submodular function, called the Lov\'asz{} extension~\cite{lovasz1983, edmondspolyhedra} is closely related to the submodular polyhedron, and is defined as $\hat{f}(x) = \max_{h \in \mathcal P_f} \langle h, x \rangle$. Thanks to the properties of the polyhedron, $\hat{f}(x)$ can be efficiently computed: Denote $\sigma_x$ as an ordering induced by $x$, such that $x(\sigma_x(1)) \geq x(\sigma_x(2)) \geq \cdots x(\sigma_x(n))$. Then the Lov\'asz{} extension is $\hat{f}(x) = \langle h^f_{\sigma_x}, x \rangle$~\cite{lovasz1983, edmondspolyhedra}. The gradient of the Lov\'asz{} extension $\nabla \hat{f}(x) = \sigma_x$. \noindent \textbf{Modular lower bounds (Sub-gradients) and Modular upper bounds (Super-gradients): } Akin to convex functions, submodular functions have tight modular lower bounds. These bounds are related to the sub-differential $\partial_f(Y)$ of the submodular set function $f$ at a set $Y \subseteq V$, which is defined \cite{fujishige2005submodular} as: $\partial_f(Y) = \{y \in \mathbb{R}^n: f(X) - y(X) \geq f(Y) - y(Y),\; \text{for all } X \subseteq V\}$. Denote a sub-gradient at $Y$ by $h_Y \in \partial_f(Y)$. Define $h_Y = h^f_{\sigma_Y}$ (see the definition of $h^f_{\sigma}$ from the previous paragraph) forms a lower bound of $f$, tight at $Y$ --- i.e., $h_Y(X) = \sum_{j \in X} h_Y(j) \leq f(X), \forall X \subseteq V$ and $h_Y(Y) = f(Y)$. Notice that the extreme points of a sub-differential are a subset of the extreme points of the submodular polyhedron. We can also define super-differentials $\partial^f(Y)$ of a submodular function \cite{jegelka2011-nonsubmod-vision,rkiyersubmodBregman2012} at $Y$: $\partial^f(Y) = \{y \in \mathbb{R}^n: f(X) - y(X) \leq f(Y) - y(Y); \text{for all } X \subseteq V\}$. It is possible, moreover, to provide specific supe-rgradients~\cite{rkiyersubmodBregman2012,rkiyersemiframework2013} that define the following two modular upper bounds: $m^f_{X, 1}(Y) \triangleq f(X) - \sum_{j \in X \backslash Y } f(j| X \backslash j) + \sum_{j \in Y \backslash X} f(j| \emptyset)$ and $m^f_{X, 2}(Y) \triangleq f(X) - \sum_{j \in X \backslash Y } f(j| V \backslash j) + \sum_{j \in Y \backslash X} f(j| X)$. Then $m^f_{X, 1}(Y) \geq f(Y)$ and $m^f_{X, 2}(Y) \geq f(Y), \forall Y \subseteq V$ and $m^f_{X, 1}(X) = m^f_{X, 2}(X) = f(X)$.\looseness-1 \noindent \textbf{Majorization-Minimization (MMin) and Minorization-Maximization (MMax) Framework: } This is a general framework of in~\cite{rkiyersemiframework2013} which has been used for several problems including submodular minimization~\cite{rkiyersemiframework2013, jegelka2011-nonsubmod-vision}, difference of submodular optimization~\cite{narasimhanbilmes, rkiyeruai2012}, SCSC/SCSK~\cite{nipssubcons2013} and many others. The basic idea of this framework is quite simple. The super-gradients and sub-gradients defined above allow one to define upper and lower bounds of a submodular functions which can be iteratively optimized. Our framework iteratively minimizes these upper bounds (equivalently maximizes these lower bounds) at every iteration. \noindent \textbf{Continuous Relaxation Framework: } Another framework for submodular optimization relies on optimizing a suitable relaxation of a submodular function. In the case of minimization problems, a suitable relaxation is a Lov\'asz{} extension~\cite{lovasz1983}, while for maximization, the multilinear extension is used~\cite{chekuri2011submodular}. An important post processing step is to round the continuous solution appropriately to a discrete set.\looseness-1 \noindent \textbf{Ellipsoidal Approximation Framework: } Another generic approximation of a submodular function, introduced by Goemans et.\ al~\cite{goemans2009approximating}, is based on approximating the submodular polyhedron by an ellipsoid. The main result states that any polymatroid (monotone submodular) function $f$, can be approximated by a function of the form $\sqrt{w^f(X)}$ for a certain modular weight vector $w^f \in \mathbb R^V$, such that $\sqrt{w^f(X)} \leq f(X) \leq O(\sqrt{n}\log{n}) \sqrt{w^f(X)}, \forall X \subseteq V$. One can then optimize the submodular function by optimizing the ellipsoidal approximation. \begin{table} \begin{center} \scriptsize{ \begin{tabular}{|l|c|c|c|c|c|c|} \hline Constraint & Hardness & MMin-AA & EA-AA & MMin & EA & CR \\ \hline Knapsack & $K(\sqrt{n}, \kappa)$ & $l K(n, \kappa)$ & $l K(\sqrt{n}\log n, \kappa)$ & $l K(n, \kappa)$ & $\tilde{O}(\sqrt{ln})$ & - \\ Trees & $M(K(n, \kappa), \log n)$ & $l K(n, \kappa)$ & $l K(\sqrt{m}\log m, \kappa)$ & $O(\log n K(n, \kappa))$ & $\tilde{O}(\sqrt{m})$ & $m-n+1$ \\ Matching & $M(K(n, \kappa), \log l)$ & $l K(n, \kappa)$ & $l K(\sqrt{m}\log m, \kappa)$ & $l K(n, \kappa)$ & $\tilde{O}(\sqrt{lm})$ & $n$ \\ s-t Cuts & $M(K(\sqrt{m}, \kappa), \log l)$ & $l K(n, \kappa)$ & $l K(\sqrt{m}\log m, \kappa)$ & $l K(n, \kappa)$ & $\tilde{O}(\sqrt{lm})$ & $n$ \\ s-t Paths & $M(K(\sqrt{m}, \kappa), \log l)$ & $l K(n, \kappa)$ & $l K(\sqrt{m}\log m, \kappa)$ & $l K(n, \kappa)$ & $\tilde{O}(\sqrt{lm})$ & $m$ \\ Edge Cov. & $(n, \kappa)$ & $l K(n, \kappa)$ & $l K(\sqrt{m}\log m, \kappa)$ & $l K(n, \kappa)$ & $\tilde{O}(\sqrt{lm})$ & $n$ \\ Vertex Cov. & $2$ & $l K(n, \kappa)$ & $l K(\sqrt{n}\log n, \kappa)$ & $l K(n, \kappa)$ & $\tilde{O}(\sqrt{ln})$ & $2$ \\ \hline \end{tabular} \label{tab:1} \caption{Approximation bounds and Hardness for \textsc{Robust-SubMin}. $M(.)$ stands for $\max(.)$}} \end{center} \end{table} \section{Robust Submodular Minimization and Maximization (Problems 1 and 2)} \subsection{Robust Submodular Minimization} In this section, we shall go over the hardness and approximation algorithms for \textsc{Robust-SubMin}. \narxiv{All proofs of the results below are in the extended version of this paper.} \setlength\intextsep{0pt} \begin{wraptable}{l}{72mm} \scriptsize{ \begin{tabular}{|l|c|c|c|} \hline Constraint & Hardness & MMin & EA \\ \hline Knapsack & $K(\sqrt{n}, \kappa)$ & $K(n, \kappa)$ & $O(K(\sqrt{n}\log n, \kappa))$ \\ Trees & $K(n, \kappa)$ & $K(n, \kappa)$ & $O(K(\sqrt{m}\log m, \kappa))$ \\ Matchings & $K(n, \kappa)$ & $K(n, \kappa)$ & $O(K(\sqrt{m}\log m, \kappa))$ \\ s-t Paths & $K(n, \kappa)$ & $K(n, \kappa)$ & $O(K(\sqrt{m}\log m, \kappa))$ \\ \hline \end{tabular} \label{tab:2} \caption{Approximation bounds and Hardness of in \textsc{Robust-SubMin} with $l$ constant}} \end{wraptable} We shall consider two cases, one where $l$ is bounded (i.e. its a constant), and the other where $l$ is unbounded. We start by defining the quantity $K(f, \kappa) = f/(1 + (1 - \kappa)(f - 1))$, where $\kappa$ is the curvature of the submodular function for which the bound is obtained. Note that $K(f, \kappa)$ interpolates the bound between $K(f, 1) = f$ and $K(f, 0) = 1$. This quantity shall come up a lot in the approximation and hardness bounds in this paper. Furthermore, in all graph based problems, we denote the graph as $G = (V, E)$ with $|V| = n, |E| = m$. To avoid confusion, we shall denote the ground-set as $\mathcal V$. The submodular functions are all defined on the edges in the case of trees, matchings, cuts, paths and edge covers (so $\mathcal V = E$). In the case of vertex covers, they are defined on the vertices ($\mathcal V = V$). \noindent \textbf{Hardness: } Since \textsc{Robust-SubMin} generalizes robust min-max combinatorial optimization (when the functions are modular), we have the hardness bounds from~\cite{kasperski2009approximability, kasperski2011approximability}. For the modular case, the lower bounds are $\Omega(log^{1-\epsilon} l)$ ($l$ is the number of functions) for s-t cuts, paths and assignments~\cite{kasperski2009approximability} and $\Omega(log^{1-\epsilon} n)$ for spanning trees~\cite{kasperski2011approximability} for any $\epsilon > 0$. These hold unless $NP \subseteq DTIME(n^{poly \log n})$\cite{kasperski2009approximability, kasperski2011approximability}. Moreover, since \textsc{Robust-SubMin} also generalizes constrained submodular minimization, we get the curvature based hardness bounds from~\cite{curvaturemin, goel2009optimal, jegelka2011-inference-gen-graph-cuts}. The hardness results are in the first column of Table~1. The curvature $\kappa$ corresponds to the worst curvature among the functions $f_i$ (i.e. $\kappa = \max_i \kappa_i$). \noindent \textbf{Average Approximation: } A simple observation is that $f_{avg}(X) = 1/l \sum_{i = 1}^l f_i(X)$ approximates $\max_{i = 1:l} f_i(X)$. As a result, minimizing $f_{avg}(X)$ implies an approximation for \textsc{Robust-SubMin}. \begin{theorem} Given a non-negative set function $f$, define $f_{avg}(X) = \frac{1}{l} \sum_{i = 1}^l f_i(X)$. Then $f_{avg}(X) \leq \max_{i = 1:l} f_i(X) \leq lf_{avg}(X)$. Denote $\hat{X}$ as $\beta$-approximate optimizer of $f_{avg}$. Then $\max_{i = 1:l} f_i(\hat{X}) \leq l\beta \max_{i = 1:l} f_i(X^*)$ where $X^*$ is the exact minimizer of \textsc{Robust-SubMin}. \end{theorem} \arxiv{ \begin{proof} To prove the first part, notice that $f_i(X) \leq \max_{i = 1:l} f_i(X)$, and hence $1/l \sum_i f_i(X) \leq \max_{i = 1:l} f_i(X)$. The other inequality also directly follows since the $f_i$'s are non-negative and hence $\max_{i = 1:l} f_i(X) \leq \sum_i f_i(X) = l f_{avg}(X)$. To prove the second part, observe that $\max_i f_i(\hat{X}) \leq lf_{avg}(\hat{X}) \leq l\beta f_{avg}(X^*) \leq l\beta \max_i f_i(X^*)$. The first inequality holds from the first part of this result, the second inequality holds since $\hat{X}$ is a $\beta$-approximate optimizer of $f_{avg}$ and the third part of the theorem holds again from the first part of this result. \end{proof}} Since $f_{avg}$ is a submodular function, we can use the majorization-minimization (which we call MMin-AA) and ellipsoidal approximation (EA-AA) for constrained submodular minimization~\cite{rkiyersemiframework2013, curvaturemin, goel2009optimal, jegelka2011-inference-gen-graph-cuts}. \begin{corollary} Using the majorization minimization (MMin) scheme with the average approximation achieves an approximation guarantee of $l K(|X^*|, \kappa_{avg})$ where $X^*$ is the optimal solution of \textsc{Robust-SubMin} and $\kappa_{avg}$ is the curvature of $f_{avg}$. Using the curvature-normalized ellipsoidal approximation algorithm from~\cite{curvaturemin, goemans2009approximating} achieves a guarantee of $O(lK(|\mathcal V|\log |\mathcal V|, \kappa_{avg}))$ \end{corollary} This corollary directly follows by combining the approximation guarantee of MMin and EA~\cite{curvaturemin, rkiyersemiframework2013} with Theorem 1. Substituting the values of $|\mathcal V|$ and $|X^*|$ for various constraints, we get the results in Table~1. While the average case approximation method provides a bounded approximation guarantee for \textsc{Robust-SubMin}, it defeats the purpose of the robust formulation. Below, we shall study some techniques which directly try to optimize the robust formulation. \textbf{Majorization-Minimization: } The Majorization-Minimization algorithm is a sequential procedure which uses upper bounds of the submodular functions defined via supergradients. Starting with $X^0 = \emptyset$, the algorithm proceeds as follows. At iteration $t$, it constructs modular upper bounds for each function $f_i$, $m^{f_i}_{X^t}$ which is tight at $X^t$. The set $X^{t+1} = \argmin_{X \in \mathcal C} \max_i m^{f_i}_{X^t}(X)$. This is a min-max robust optimization problem. The following theorem provides the approximation guarantee for MMin.\looseness-1 \begin{theorem} \label{thm3} If $l$ is a constant, MMin achieves an approximation guarantee of $(1 + \epsilon)K(|X^*|, \kappa_{wc})$ for the knapsack, spanning trees, matching and s-t path problems. The complexity of this algorithm is exponential in $l$. When $l$ is unbounded, MMin achieves an approximation guarantee of $lK(|X^*|, \kappa_{wc})$. For spanning trees and shortest path constraints, MMin achieves a $O(\min(\log n, l) K(n, \kappa_{wc}))$ and a $O(\min(\sqrt{n}, l) K(n, \kappa_{wc}))$ approximation. Under cardinality and partition matroid constraints, MMin achieves a $O(\log l K(n, \kappa_{wc})/\log\log l)$ approximation. \end{theorem} Substituting the appropriate bounds on $|X^*|$ for the various constraints, we get the results in Tables 1 and 2. $\kappa_{wc}$ corresponds to the worst case curvature $\max_i \kappa_{f_i}$. When $l$ is bounded, the corresponding min-max robust optimization problem in every iteration of MMin can be solved via an FPTAS. In particular, we can obtain a $1+\epsilon$ approximation for shortest paths in $O(n^{l+1}/\epsilon^{l-1})$, trees in $O(mn^{l+4}/\epsilon^l \log{n/\epsilon})$, matchings in $O(mn^{l+4}/\epsilon^l \log{n/\epsilon})$ and knapsack in $O(n^{l+1}/\epsilon^l)$~\cite{aissi2010general}. The results for constant $l$ is shown in Table~2 (column corresponding to MMin). When $l$ is not constant, we cannot use the FPTAS since they are all exponential in $l$. In the case of spanning trees and shortest path constraints, the min-max robust optimization problem can be approximated up to a factor of $O(\log n)$ and $\tilde{O}(\sqrt{n})$ via a randomized LP relaxation~\cite{kasperski2011approximability, kasperski2018approximating}. Similarly in the case of cardinality and partition matroid constraints, we can achieve a $O(\log l/\log \log l)$ approximation using LP relaxations~\cite{kasperski2018approximating}. For the other constraints, we use the modular cost $m_r = \max_i m_{X^t}^{f_i}[r], r \in V$. This provides a $l$ approximation. The approximation guarantees of MMin for unbounded $l$ is shown in Table~\ref{tab:1}. \narxiv{A detailed proof is in the extended version of this paper.} \arxiv{ Before proving the result, we shall make a simple observation. Given a min-max objective function $\min_{X \in \mathcal C} w_{max}(X)$ where $w_{max} = \max_i w_i(X)$, define a modular approximation $w_{modmax}(X) = \sum_{i \in X} \max_j w_j(i)$. Also define $w_{avg}(X) = 1/l \sum_{i, j} w_i(j)$. \begin{lemma} Given $w_i(j) \geq 0$, it holds that $w_{modmax}(X) \geq w_{max}(X) \geq \frac{1}{l} w_{modmax}(X)$. Furthermore, $w_{avg}(X) \leq w_{max}(X) \leq lw_{avg}(X)$. \end{lemma} \begin{proof} The second result follows from Theorem 1, if we define $f_i(X) = w_i(X)$. To prove the first result, we start with proving $w_{max}(X) \leq w_{modmax}(X)$. For a given set $X$, let $i_X$ be the index which maximizes $w_{max}$ so $w_{max}(X) = \sum_{j \in X} w_{i_X}(j)$. Then $w_{i_X}(j) \leq \max_i w_i(j)$ from which we get the result. Next, observe that $w_{modmax}(X) \leq \sum_{i,j} w_i(j) = lw_{avg}(X) \leq lw_{max}(X)$ which proves this part. \end{proof} This shows that $w_{avg}$ and $w_{modmax}$ form upper and lower bounds of $w_{max}$ and moreover, are both $l$-approximations of $w_{max}$. We now elaborate on the Majorization-Minimization algorithm and prove the result. At every round of the majorization-minimization algorithm we need to solve \begin{align} \label{mmin-subproblem} X^{t+1} = \argmin_{X \in \mathcal C} \max_i m^{f_i}_{X^t}(X). \end{align} We consider three cases. The first is when $l$ is a constant. In that case, we can use an FPTAS to solve Eq.~\eqref{mmin-subproblem}~\cite{aissi2009min, aissi2010general}. We can obtain a $1+\epsilon$ approximation for shortest paths in $O(n^{l+1}/\epsilon^{l-1})$, trees in $O(mn^{l+4}/\epsilon^l \log{n/\epsilon})$, matchings in $O(mn^{l+4}/\epsilon^l \log{n/\epsilon})$ and knapsack in $O(n^{l+1}/\epsilon^l)$~\cite{aissi2010general}. The second case is a generic algorithm when $l$ is not constant. In this case, at every iteration of MMin use these two bounds (the \emph{avg} and \emph{modmax} bounds) on the function $\max_i m^{f_i}_{X^t}$ and choose the solution with a better solution. The bound of MMin directly follows from the observation that both the bounds (the \emph{avg} and \emph{modmax} of $m^{f_i}_{X^t}$ are $l$-approximations of $m^{f_i}_{X^t}$. Finally, for the special cases of spanning trees, shortest paths, cardinality and partition matroid constraints, there exist LP relaxation based algorithms which achieve approximation factors of $O(\log n)$, $O(\sqrt{n\log l/\log\log l}$, $O(\log l/\log \log l)$ and $O(\log l/\log \log l)$ respectively. We now prove Theorem~\ref{thm3}. \begin{proof} Assume we have an $\alpha$ approximation algorithm for solving problem~\eqref{mmin-subproblem}. We start MMin with $X^0 = \emptyset$. We prove the bound for MMin for the first iteration. Observe that $m^{f_i}_{\emptyset}(X)$ approximate the submodular functions $f_i(X)$ up to a factor of $K(|X|, \kappa_i)$~\cite{curvaturemin}. If $\kappa_{wc}$ is the maximum curvature among the functions $f_i$, this means that $m^{f_i}_{\emptyset}(X)$ approximate the submodular functions $f_i(X)$ up to a factor of $K(|X|, \kappa_{wc})$ as well. Hence $\max_i m^{f_i}_{\emptyset}(X)$ approximates $\max_i f_i(X)$ with a factor of $K(|X|, \kappa_{wc})$. In other words, $\max_i f_i(X) \leq \max_i m^{f_i}_{\emptyset}(X) \leq K(|X|, \kappa_{wc}) \max_i f_i(X)$. Let $\hat{X_1}$ be the solution obtained by optimizing $m^{f_i}_{\emptyset}$ (using an $\alpha$-approximation algorithms for the three cases described above). It holds that $\max_i m^{f_i}_{\emptyset}(\hat{X}_1) \leq \alpha \max_i m^{f_i}_{\emptyset}(X^m_1)$ where $X^m_1$ is the optimal solution of $\max_i m^{f_i}_{\emptyset}(X)$ over the constraint $\mathcal C$. Furthermore, denote $X^*$ as the optimal solution of $\max_i f_i(X)$ over $\mathcal C$. Then $\max_i m^{f_i}_{\emptyset}(X^m_1) \leq \max_i m^{f_i}_{\emptyset}(X^*) \leq K(|X^*|, \kappa_{wc})\max_i f_i(X^*)$. Combining both, we see that $\max_i f(\hat{X}_1) \leq \max_i m^{f_i}_{\emptyset}(\hat{X}_1) \leq \alpha K(|X^*|, \kappa_{wc})\max_i f_i(X^*)$. We then run MMin for more iterations and only continue if the objective value increases in the next round. Using the values of $\alpha$ for the different cases above, we get the results. \end{proof} } \textbf{Ellipsoidal Approximation: } Next, we use the Ellipsoidal Approximation to approximate the submodular function $f_i$. To account for the curvature of the individual functions $f_i$'s, we use the curve-normalized Ellipsoidal Approximation~\cite{curvaturemin}. We then obtain the functions $\hat{f}_i(X)$ which are of the form $(1 - \kappa_{f_i})\sqrt{w_{f_i}(X)} + \kappa_{f_i}\sum_{j \in X} f_i(j)$, and the problem is then to optimize $\max_i \hat{f}_i(X)$ subject to the constraints $\mathcal C$. This is no longer a min-max optimization problem. The following result shows that we can still achieve approximation guarantees in this case. \begin{theorem} For the case when $l$ is a constant, EA achieves an approximation guarantee of $O(K(\sqrt{|\mathcal V|\log |\mathcal V|}, \kappa_{wc}))$ for the knapsack, spanning trees, matching and s-t path problems. The complexity of this algorithm is exponential in $l$. When $l$ is unbounded, the EA algorithm achieves an approximation guarantee of $O(\sqrt{l}\sqrt{|\mathcal V|} \log |\mathcal V|)$ for all constraints. In the case of spanning trees, shortest paths, the EA achieves approximation factors of $O(\min(\sqrt{\log n}, \sqrt{l}) \sqrt{m}\log m)$, and $O(\min(n^{0.25}, \sqrt{l})\sqrt{m}\log m)$. Under cardinality and partition matroid constraints, EA achieves a $O(\sqrt{\log l/\log\log l} \sqrt{n}\log n)$ approximation. \end{theorem} For the case when $l$ is bounded, we reduce the optimization problem after the Ellipsoidal Approximation into a multi-objective optimization problem, which provides an FPTAS for knapsack, spanning trees, matching and s-t path problems~\cite{papadimitriou2000approximability, mittal2013general}. When $l$ is unbounded, we further reduce the EA approximation objective into a linear objective which then provides the approximation guarantees similar to MMin above. However, as a result, we loose the curvature based guarantee. \narxiv{A detailed proof is in the extended version of this paper. } \arxiv{ \begin{proof} First we start with the case when $l$ is a constant. Observe that the optimization problem is \begin{align} \min_{X \in \mathcal C} \max_i \hat{f}_i(X) = \min_{X \in \mathcal C} \max_i (1 - \kappa_{f_i})\sqrt{w_{f_i}(X)} + \kappa_{f_i}\sum_{j \in X} f_i(j) \end{align} This is of the form $\min_{X \in \mathcal C} \max_i \sqrt{w^i_1(X)} + w^i_2(X)$. Define $h(y^1_1, y^1_2, y^2_2, y^2_2, \cdots, y^l_1, y^l_2) = \max_i \sqrt{y^i_1} + y^i_2$. Note that the optimization problem is $\min_{X \in \mathcal C} h(w^1_1(X), w^1_2(X), \cdots, w^l_1(X), w^l_2(X))$. Observe that $h(\mathbf{y}) \leq h(\mathbf{y^{\prime}})$ if $\mathbf{y} \leq \mathbf{y^{\prime}}$. Furthermore, note that $\mathbf{y} \geq 0$. Then given a $\lambda > 1$, $h(\lambda \mathbf{y}) = \max_i \sqrt{\lambda y^i_1} + \lambda y^i_2 \leq \lambda \sqrt{y^i_1} + \lambda y^i_2 \leq \lambda h(\mathbf{y})$. As a result, we can use Theorem 3.3 from~\cite{mittal2013general} which provides an FPTAS as long as the following exact problem can be solved on $\mathcal C$: Given a constant $C$ and a vector $c \in \mathbf{R}^n$, does there exist a $x$ such that $\langle c, x \rangle = C$? A number of constraints including matchings, knapsacks, s-t paths and spanning trees satisfy this~\cite{papadimitriou2000approximability}. For these constraints, we can obtain a $1 + \epsilon$ approximation algorithm in complexity exponential in $l$. When $l$ is unbounded, we directly use the Ellipsoidal Approximation and the problem then is to optimize $\min_{X \in \mathcal C} \max_i \sqrt{w_{f_i}(X)}$. We then transform this to the following optimization problem: $\min_{X \in \mathcal C} \max_i w_{f_i}(X)$. Assume we can obtain an $\alpha$ approximation to the problem $\min_{X \in \mathcal C} \max_i w_{f_i}(X)$. This means we can achieve a solution $\hat{X}$ such that $\max_i w_{f_i}(\hat{X}) \leq \alpha \max_i w_{f_i}(X^{ea})$ where $X^{ea}$ is the optimal solution for the problem $\min_{X \in \mathcal C} \max_i w_{f_i}(X)$. Then observe that $\max_i \sqrt{w_{f_i}(X^{ea})} \leq \max_i \sqrt{w_{f_i}(X^*)} \leq \max_i f_i(X^*)$. Combining all the inequalities and also using the bound of the Ellipsoidal Approximation, we have $\max_i f_i(\hat{X}) \leq \beta \max_i \sqrt{w_{f_i}(\hat{X})} \leq \beta \sqrt{\alpha} \max_i \sqrt{w_{f_i}(X^{ea})} \leq \beta \sqrt{\alpha} \max_i \sqrt{w_{f_i}(X^*)} \leq \beta \sqrt{\alpha} \max_i f_i(X^*)$ where $\beta$ is the approximation of the Ellipsoidal Approximation. We now use this result to prove the theorem. Consider two cases. First, we optimize the \emph{avg} and \emph{modmax} versions of $w_{f_i}(X)$ which provide $\alpha = l$ approximation. Secondly, for the special cases of spanning trees, shortest paths, cardinality and partition matroid constraints, there exist LP relaxation based algorithms which achieve approximation factors $\alpha$ being $O(\log n)$, $O(\sqrt{n\log l/\log\log l}$, $O(\log l/\log \log l)$ and $O(\log l/\log \log l)$ respectively. Substitute these values of $\alpha$ and using the fact that $\beta = O(\sqrt{|V|}\log |V|)$, we get the approximation bound. \end{proof} } \textbf{Continuous Relaxation: } Here, we use the continuous relaxation of a submodular function. In particular, we use the relaxation $\max_i \hat{f_i}(x), x \in [0, 1]^{|\mathcal V|}$ as the continuous relaxation of the original function $\max_i f_i(X)$ (here $\hat{f}$ is the Lov\'asz{} extension). Its easy to see that this is a continuous relaxation. Since the Lov\'asz{} extension is convex, the function $\max_i \hat{f_i}(x)$ is also a convex function. This means that we can exactly optimize the continuous relaxation over a convex polytope. The remaining question is about the rounding and the resulting approximation guarantee due to the rounding. Given a constraint $\mathcal C$, define the up-monotone polytope similar to~\cite{iyer2014monotone} $\hat{\mathcal P_{\mathcal C}} = \mathcal P_{\mathcal C} + [0,1]^{|\mathcal V|}$. We then use the observation from~\cite{iyer2014monotone} that all the constraints considered in Table 1 (with the exception of knapsack) can be expressed as $\hat{\mathcal P_{\mathcal C}} = \{x \in [0,1]^n | \sum_{i \in W} x_i \geq b_W$ for all $W \in \mathcal W$\} for a family of sets $\mathcal W = \{W_1, \cdots\}$. We then round the solution using the following rounding scheme. Given a continuous vector $\hat{x}$ (which is the optimizer of $\max_i \hat{f_i}(x), x \in \hat{\mathcal P_{\mathcal C}}$, order the elements based on $\sigma_{\hat{x}}$. Denote $X_i = [\sigma_{\hat{x}}[1], \cdots, \sigma_{\hat{x}}[i]]$ so we obtain a chain of sets $\emptyset \subseteq X_1 \subseteq X_2 \subseteq \cdots \subset X_n$. Our rounding scheme picks the smallest $k$ such that $X_k \in \hat{\mathcal C}$. Another way of checking this is if there exists a set $X \subset X_k$ such that $X \in \mathcal C$. Since $\hat{\mathcal C}$ is up-monotone, such a set must exist. The following result shows the approximation guarantee. \begin{theorem} Given submodular functions $f_i$ and constraints $\mathcal C$ which can be expressed as $\{x \in [0,1]^n | \sum_{i \in W} x_i \geq b_W$ for all $W \in \mathcal W$\} for a family of sets $\mathcal W = \{W_1, \cdots\}$, the continuous relaxation scheme achieves an approximation guarantee of $\max_{W \in \mathcal W} |W| - b_W + 1$. If we assume the sets in $\mathcal W$ are disjoint, the integrality bounds matches the approximation bounds. \end{theorem} \narxiv{The proof of this result is in the extended version. The bounds in Table 1 (column CR) follow by appropriately setting the values of $\mathcal W$ and $\max_{W \in \mathcal W} |W| - b_W + 1$ for the different constraints (using the construction from~\cite{iyer2014monotone}. See the extended version for more details.} \arxiv{\begin{proof} The proof of this theorem is closely in line with Lemma 2 and Theorem 1 from~\cite{iyer2014monotone}. We first show the following result. Given monotone submodular functions $f_i, i \in 1, \cdots, l$, and an optimizer $\hat{x}$ of $\max_i \hat{f}(x)$, define $\hat{X_{\theta}} = \{i: \hat{x}_i \geq \theta\}$. We choose $\theta$ such that $\hat{X_{\theta}} \in \mathcal C$. Then $\max_i f_i(\hat{X_{\theta}}) \leq 1/\theta \max_i f_i(X^*)$ where $X^*$ is the optimizer of $\min_{X \in \mathcal C} \max_i f_i(X)$. To prove this, observe that, by definition $\theta 1_{\hat{X_{\theta}}} \leq \hat{x}$\footnote{$1_A$ is the indicator vector of set $A$ such that $1_A[i] = 1$ iff $i\in A$.}. As a result, $\forall i, \hat{f_i}(\theta 1_{\hat{X_{\theta}}}) = \theta f_i(\hat{X_{\theta}}) \leq \hat{f_i}(\hat{x})$ (this follows because of the positive homogeneity of the Lov\'asz{} extension. This implies that $\theta \max_i f_i(\hat{X_{\theta}}) \leq \hat{f_i}(\hat{x}) \leq \min_{x \in \mathcal P_{\mathcal C}} \hat{f_i}(\hat{x}) \leq \min_{X \in \mathcal C} \max_i f_i(X)$. The last inequality holds from the fact that the discrete solution is greater than the continuous one since the continuous one is a relaxation. This proves this part of the theorem. Next, we show that the approximation guarantee holds for the class of constraints defined as $\{x \in [0,1]^n | \sum_{i \in W} x_i \geq b_W$. This follows directly from the Proof of Theorem 1 in~\cite{iyer2014monotone}. \end{proof} We can then obtain the approximation guarantees for different constraints including cardinality, spanning trees, matroids, set covers, edge covers and vertex covers, matchings, cuts and paths by appropriately defining the polytopes $\mathcal P_{\mathcal C}$ and appropriately setting the values of $\mathcal W$ and $\max_{W \in \mathcal W} |W| - b_W + 1$. We refer to the reader to Section 3 in~\cite{iyer2014monotone}. } \noindent \textbf{Tightness of the Bounds: } Given the bounds in Tables 1 and 2, we discuss the tightness of these bounds viz-a-via the hardness. In the case when $l$ is a constant, MMin achieves tight bounds for Trees, Matchings and Paths while the EA achieves tight bounds up to $\log$ factors for knapsack constraints. In the case when $l$ is not a constant, MMin achieves a tight bound up to $\log$ factors for spanning tree constraints. The continuous relaxation scheme obtains tight bounds in the case of vertex covers. In the case when the functions $f_i$ have curvature $\kappa = 1$ CR also obtains tight bounds for edge-covers and matchings. We also point out that the bounds of average approximation (AA) depend on the average case curvature as opposed to the worst case curvature. However, in practice, the functions $f_i$ often belong to the same class of functions in which case all the functions $f_i$ have the same curvature. \subsection{Robust Submodular Maximization} Krause et al~\cite{krause08robust} show that \textsc{Robust-SubMax} is inapproximable upto any polynomial factor unless P = NP even with cardinality constraints. \cite{anari2019robust} extend this to matroid and knapsack constraints. \cite{krause08robust, anari2019robust} provide a bi-criteria approximation factor of $(1 - \epsilon, O(\log l/\epsilon))$ for cardinality constraints. For Matroid constraints, they provide bi-criteria algorithms by creating a union of $O(\log l/\epsilon)$ independent sets, with the union set having a guarantee of $1 - \epsilon$. This result can be extended to multiple matroid constraints~\cite{anari2019robust}. Anari et al~\cite{anari2019robust} also obtained a $(1 - \epsilon, O(\log l/\epsilon))$ approximation for a single knapsack constraint. In the following theorem, we provide a bi-criteria approximation for \textsc{Robust-SubMax} under multiple knapsack constraints.\looseness-1 \begin{theorem} \label{robust-submax-mulknapsack} Using a modified greedy algorithm, we achieve a $(1 - \epsilon, O(l.\mbox{ln }\frac{l}{\epsilon}))$ bi-criteria approximation for \textsc{Robust-SubMax} under $l$ knapsack constraints. Using the continuous greedy algorithm, we can achieve an improved factor of $(1 - \epsilon, O(\mbox{ln }\frac{l}{\epsilon}))$ for the same problem. \end{theorem} Since the greedy algorithm does not work directly for multiple knapsack constraints, we convert the problem first into a single knapsack constraint which provides the bi-criteria approximation. The approximation is worse by a factor $l$. Using the continuous greedy algorithm similar to~\cite{anari2019robust} and the rounding scheme of~\cite{kulik2009maximizing} we achieve the tight approximation guarantee. \arxiv{ \begin{proof} We start with the optimization problem: \begin{align} \max_{X \subseteq V} \min_{i = 1:k} g_i(X) \,\,\ | \,\,\ w_i(X) \leq b_i, i = 1, \cdots, l. \end{align} Note that the constraints can equivalently be written as $\max_i \frac{w_i(X)}{b_i} \leq 1$. We can then define two approximations of this. One is the \emph{modmax} approximation which is $\sum_{i \in X} \max_{j \in 1:l} w_{ij}/b_i$ and the other is the \emph{avg} approximation: $\sum_{i \in X} \sum_{j \in 1:l} w_{ij}/lb_i$. Both these are $l$-approximations of $\max_i \frac{w_i(X)}{b_i} \leq 1$. Denote these approximations as $\hat{w}(X)$ and w.l.o.g assume that $\hat{w}(X) \leq \max_i w_i(X)/b_i \leq l\hat{w}(X)$. We can then convert this to an instance of \textsc{Robust-SubMax} with a single knapsack constraint: \begin{align} \max_{X \subseteq V} \min_{i = 1:k} g_i(X) \,\,\ | \,\,\ \hat{w}(X) \leq 1 \end{align} From~\cite{anari2019robust}, we know that we can achieve a $(1 - \epsilon, \log l/\epsilon)$ bi-criteria approximation. In other words, we can achieve a solution $\hat{X}$ such that $\min_i g_i(\hat{X}) \geq (1 - \epsilon) \min_i g_i(X^*)$ and $\hat{w}(\hat{X}) \leq \log l/\epsilon$. Since we have that $\max_i w_i(X)/b_i \leq l\hat{w}(X)$, this implies $\max_i w_i(X)/b_i \leq l \mbox{ln } l/\epsilon$. This completes the first part. In practice, we can use both the approximations (i.e. the \emph{modmax} and the \emph{avg} approximation and choose the better among the solutions). Next, we prove the second part of the theorem. This uses the continuous greedy algorithm and we use the proof technique from~\cite{anari2019robust}. In particular, first truncate $g_i$'s to $c$, so we can define $g_i^c(X) = \min(g_i(X), c)$. Define the multi-linear extension of $g_i^c$ as $G_i^c$. First we argue that we can obtain a solution $y(\tau)$ at time $\tau$ such that $G^c_i(y(\tau)) \geq (1 - e^{-\tau}) c, \forall i$ where $y(\tau) \in \tau \mathcal P_{\mathcal C}$. In other words, $y(\tau)$ satisfies $\langle y, w_i \rangle/b_i \leq \tau, \forall i$. This follows from Claim 1 in~\cite{anari2019robust} since the result holds for any down-monotone polytope~\cite{chekuri2011submodular}. Next, we use the rounding technique from~\cite{kulik2009maximizing}. In order to do this, we first set $\tau = \mbox{ln } l/\epsilon$ so we can achieve a solution so $G_i^c(y) \geq (1 - \epsilon/l)c$. Notice that this implies $G^c(y) = \sum_i G_i^c(y) \geq (1 - \epsilon/l)c$. Since $G^c$ is a single submodular function, we can round the obtained fractional solution $y$ using the rounding scheme from~\cite{kulik2009maximizing}. This will achieve a discrete solution $X$ such that $g^c(X) \geq (1 - \epsilon/l - \epsilon^{\prime})c$ and satisfies $\max_i w_i(X)/b_i \leq \mbox{ln }\frac{l}{\epsilon}$. The question is what can we say about the original objective. We can show that for all $i = 1:l$, $g^c_i(X) \geq (1 - \epsilon - l\epsilon^{\prime})c$ since suppose this were not the case then there would exist atleast one $i$ such that $g^c_i(X) < (1 - \epsilon - l\epsilon^{\prime})c$. Since $g^c_j \leq c, \forall j = 1:l$, this implies that $\sum_{j=1}^l g^c_j/l < c(l-1)/l + (1 - \epsilon - l\epsilon^{\prime})c < c(1 - \epsilon/l - \epsilon^{\prime})$ which refutes the fact that $g^c(X) = \sum_{j=1}^l g^c_j/l \geq (1 - \epsilon/l - \epsilon^{\prime})c$. Define a new $epsilon$ as $\epsilon + l\epsilon^{\prime}$ and this shows that we can achieve a discrete solution $X$ such that $g^c_i(X) < (1 - \epsilon)c$ and $\max_i w_i(X)/b_i \leq \mbox{ln }\frac{l}{\epsilon}$. We can then the binary search over the values of $c$ (similar to~\cite{anari2019robust}) and obtain a $(1 - \epsilon, O(\mbox{ln }\frac{l}{\epsilon}))$ bicriteria approximation. \end{proof} } \section{Robust SCSC and Robust SCSK (Problems 3 and 4)} We first start by showing that \textsc{Robust-SCSC} and \textsc{Robust-SCSK} are closely related and an approximation algorithm for one of the problems provides an approximation algorithm for the other. We shall call these two problems duals of each other. Proofs of all results are in the extended version. \begin{theorem}\label{robust-scsc-scsk-eq} We can obtain a $((1 - \epsilon)\rho, \sigma)$ approximation for \textsc{Robust-SCSK} using $\log\frac{\min_i g_i(V)/min_j \min_i g_i(j)}{\epsilon}$ calls to a $(\sigma, \rho)$ bicriteria approximation algorithm for \textsc{Robust-SCSC}. Conversely, we can achieve a $((1 + \epsilon)\sigma, \rho)$ bicriteria approximation for \textsc{Robust-SCSC} with $\log\frac{\max_i f_i(V)/min_j \max_i f_i(j)}{\epsilon}$ calls to a $(\rho, \sigma)$ bicriteria approximation for \textsc{Robust-SCSK}. \end{theorem} \arxiv{ \begin{proof} To prove this result, we transform Problems 3 and 4 into the following problems: \begin{align} \min_{X \subseteq V} \max_{i=1:l} f_i(X) \,\, | \,\, \min_{i=1:k} g_i(X)/c_i \geq 1, \nonumber \\ \max_{X \subseteq V} \min_{i = 1:k} g_i(X) \,\, | \,\, \max_{i=1:l} f_i(X)/b_i \leq 1, \nonumber \end{align} Immediately notice that this is similar to SCSC and SCSK except that the objectives $\max_{i=1:l} f_i(X)$ and $\min_{i = 1:k} g_i(X)$ are not submodular. They are however monotone and we can use algorithms 2 and 3 (for a linear search) and algorithms 4 and 5 (for a binary search version) from~\cite{nipssubcons2013} to convert the problems from one form into another. This result follows from Theorem 3.1 and Theorem 3.2 from~\cite{nipssubcons2013}. \end{proof} } Next we discuss the hardness of Problems 3 and 4. Since Problem 3 generalizes \textsc{Robust-SubMin} with cardinality, knapsack and spanning tree constraints ($g$ is the rank of the spanning tree matroid). This provides a hardness of $\Omega(\max\{K(\sqrt{n}, \kappa), \log^{1-\epsilon} n\})$ for any $\epsilon > 0$. The hardness of $K(\sqrt{n}, \kappa)$ since it generalized SCSC and $\log^{1-\epsilon} n$ from generalizing the case when $f_i$'s are modular and $g$ is the rank of a spanning tree matroid~\cite{kasperski2011approximability}. Problem 4 generalizes \textsc{Robust-SubMax} which means one cannot achieve any polynomial approximation factor unless P = NP\footnote{Note that Problem 3 does admit approximation guarantees while Problem 4 can only admit bicriteria guarantees due to this result.}. Since Problems 3 and 4 can be converted into one another, this means Problem 4 also has the same bi-criteria hardness of $\Omega(\max\{K(\sqrt{n}, \kappa), \log^{1-\epsilon} n\})$ for any $\epsilon > 0$\looseness-1 \noindent \textbf{Average Approximation: } We start with the average case approximation of $f_{\max}(X) = \max_i f_i(X)$ as $f_{avg} = 1/l \sum_{i = 1}^l f_i(X)$ and use $f_{avg}$ instead of the $f_{\max}(X)$ in Problems 3 and 4. We start with Problem 3. Using the saturate trick~\cite{krause08robust}, we notice that the constraint is equivalent to $\sum_{i = 1}^k \min(g_i(X), c_i) \geq \sum_i c_i$, which immediately converts \textsc{Robust-SCSC} into an instance of SCSC. Next, we can can use the Majorization-Minimization algorithm on SCSC (which we call MMin-AA) or the Ellipsoidal Approximation (which we call EA-AA) to approximate $f_{avg}$. We can similarly solve \textsc{Robust-SCSK}. In the case of \textsc{Robust-SCSK}, we consider two cases. If we use the majorization-minimization scheme to approximate $f_{avg}$, at every iteration of the majorization-minimization, we get an instance of \textsc{Robust-SubMax} subject to a single knapsack constraint. In the case of the Ellipsoidal Approximation, we use Theorem~\ref{robust-scsc-scsk-eq} and use the approximation algorithm for \textsc{Robust-SCSC} to provide the result.\looseness-1 \begin{theorem} MMin-AA achieves an approximation factor of $lK(n, \kappa_{avg})H(\max_{j} \sum_i g_i(j))$\footnote{$H(.)$ is the harmonic function} for Problem 3 and a bicriteria factor of $(1 - \epsilon, lK(n, \kappa_{avg})\log{l/\epsilon}$ for Problem 4. Similarly EA-AA achieves an approximation factor of $O(lK(\sqrt{n}, \kappa_{avg})H(\max_{j} \sum_i g_i(j))$ for Problem 3 and a bicriteria factor of $(1 - \epsilon, O(lK(\sqrt{n}, \kappa_{avg})H(\max_{j} \sum_i g_i(j)))$ for Problem 4. \end{theorem} \arxiv{ \begin{proof} In this proof, we elaborate a little bit on the summary above. We rewrite the optimization problem 3 and 4 using the average approximation: \begin{align} \mbox{Problem 3': } \min_{X \subseteq V} \frac{1}{l}\sum_{i = 1}^l f_i(X) \,\, | \,\, g_i(X) \geq c_i, i = 1, \cdots k \nonumber \\ \mbox{Problem 4': } \max_{X \subseteq V} \min_{i = 1:k} g_i(X) \,\, | \,\, \frac{1}{l}\sum_{i = 1}^l f_i(X)/b_i \leq 1 \nonumber \end{align} Note that for Problem 3, we approximate $\max_i f_i(X)$ with $\frac{1}{l}\sum_{i = 1}^l f_i(X)$, while for Problem 4 we approximate $\max_i f_i(X)/b_i$ with $\frac{1}{l}\sum_{i = 1}^l f_i(X)/b_i$. Now, observe that the constraints in Problem 3' can be written as $\sum_{i = 1}^k \min(g_i(X), c_i) = \sum_{i = 1}^k c_i$. Problem 3 then becomes an instance of SCSC. We can use the majorization-minimization algorithm (called ISSC in~\cite{nipssubcons2013}) which achieves a guarantee of $K(n, \kappa_{avg}) H(\max_j \sum_i g_i(j))$ for Problem 3'. Finally, we note that $f_{avg}$ is an $l$-approximation of $f_{max}$ which provides us with the guarantee for MMin. Next, we can also use EA for Problem 3' and use the algorithm EASSC from~\cite{nipssubcons2013}. This provides us with a tighter guarantee of $O(K(\sqrt{n}, \kappa_{avg}) H(\max_j \sum_i g_i(j)))$ and again using the fact that $f_{avg}$ is a $l$-approximation of $f_{max}$ achieves the guarantee. Next, we consider Problem 4'. For Problem 4', we can use the majorization-minimization (super-gradient) based upper bounds for the function $\frac{1}{l}\sum_{i = 1}^l f_i(X)/b_i$. This then converts Problem 4' into an instance of \textsc{Robust-SubMax} subject to a knapsack constraints. This achieves a $(1 - \epsilon, O(\log(l/\epsilon)))$ approximation~\cite{anari2019robust}. Furthermore, we know that $\frac{1}{l}\sum_{i = 1}^l f_i(X)/b_i$ is a $l$-approximation to $\max_{i = 1:l} f_i(X)/b_i$ and we use the fact that $\max_{i = 1:l} f_i(X)/b_i \leq l(\frac{1}{l}\sum_{i = 1}^l f_i(X)/b_i) \leq O(l\log(l/\epsilon)))$. This proves the result. Finally for the EA approximation for Problem 4, we use the fact that the EA-AA algorithm achieves a $O(lK(\sqrt{n}, \kappa_{avg}) H(\max_j \sum_i g_i(j)))$-approximation for Problem 3 and using Theorem~\ref{robust-scsc-scsk-eq} we obtain a bound for Problem 4. \end{proof} } \noindent \textbf{Majorization-Minimization: } Next, we directly apply majorization-minimization via the modular upper bounds (super-gradients) to Problems 3 and 4. We then obtain a sequential procedure where at every iteration, we have solve Problems 3 and 4 with $m^{f_i}_{X^t}$ instead of $f_i$. We analyze Problem 4 since it is easier. At every iteration, we then have \textsc{Robust-SubMax} with multiple knapsack constraints. Invoking Theorem~\ref{robust-submax-mulknapsack}, we then get the corresponding approximation guarantee. To obtain an approximation guarantee for Problem 3, we invoke Theorem~\ref{robust-scsc-scsk-eq} to transfer over the bound. \begin{theorem} Majorization-Minimization (MMin) achieves a bicriteria approximation of $(K(n, \kappa_{wc})\log{l/\epsilon}(1 + \epsilon), 1 - \epsilon)$ for Problem 3 and a factor of $(1 - \epsilon, K(n, \kappa_{wc})\log{l/\epsilon})$ for Problem 4. \end{theorem} We get rid of the dependency on $l$ by directly applying Majorization-Minimization. However, we have a slightly weaker dependency on $n$ compared to the EA based schemes. \arxiv{ \begin{proof} To prove this result, we start with Problem 4. We apply the majorization-minimization on the $f_i$'s by sequentially creating modular upper bounds starting at the empty set. Each sub-problem in the MMin becomes an instance of \textsc{Robust-SubMax} subject to multiple knapsack constraints. We can use Theorem~\ref{robust-submax-mulknapsack} which provides a $(1 - \epsilon, O(\mbox{ln }(l/\epsilon))$ approximation. Now the modular upper bounds of $f_i$ satisfies $f_i(X) \leq m^{f_i}_{\emptyset}(X) \leq K(n, \kappa_{wc}) f_i(X)$. At every iteration, majorization-minimization solves the following optimization problem (starting with $X^0 = \emptyset$): \begin{align} \max_X \min_i g_i(X) \,\, | \,\, m^{f_i}_{X^t}(X)/K(n, \kappa_{wc}) \leq b_i \end{align} We now do the analysis for the first iteration. Observe that we can obtain a set $\hat{X}$ such that $m^{f_i}_{\emptyset}(X)/K(n, \kappa_{wc}) \leq b_i \mbox{ln }(l/\epsilon)$. This implies that $m^{f_i}_{\emptyset}(X) \leq K(n, \kappa_{wc}) b_i \mbox{ln }(l/\epsilon)$ and correspondingly, $f_i(X) \leq K(n, \kappa_{wc}) b_i \mbox{ln }(l/\epsilon)$. The first iteration of MMin achieves a bi-criteria approximation factor of $(1 - \epsilon, K(n, \kappa)\log{l/\epsilon})$ for Problem 4. Since subsequent iterations will only improve the objective value, the result holds. To prove the bound for Problem 3, we use Theorem~\ref{robust-scsc-scsk-eq} to transform the above bound into a bicriteria approximation for Problem 3. \end{proof}} \noindent \textbf{Ellipsoidal Approximation: } Finally, we approximate the $f_i$'s with the Ellipsoidal Approximation $\hat{f_i}(X) = \sqrt{w_f^i(X)}$. Again for simplicity, we start with Problem 4. The constraints here are $\sqrt{w_f^i(X)} \leq b_i$ which is equivalent to $w_f^i(X) \leq b_i^2$. We then have \textsc{Robust-SubMax} subject to multiple knapsack constraints and using Theorem~\ref{robust-submax-mulknapsack} we can achieve the following result. \begin{theorem} The Ellipsoidal Approximation Algorithm (EA) achieves a bicriteria approximation of $(O(\sqrt{n}\log n \sqrt{\log{l/\epsilon}}), 1 - \epsilon)$ for Problem 3 and a factor of $(1 - \epsilon, O(\sqrt{n}\log n \sqrt{\log{l/\epsilon}}))$ for Problem 4. \end{theorem} EA matches the hardness upto $\log$ factors when the curvature $\kappa = 0$. \arxiv{ \begin{theorem} We start with Problem 4. The Ellipsoidal Approximation $\sqrt{w_{f_i}(X)}$ approximates the functions $f_i(X)$ such that $\forall i, \sqrt{w_{f_i}(X)} \leq f_i(X) \leq O(\sqrt{n}\log n) \sqrt{w_{f_i}(X)}$. We then replace the functions $f_i$'s in Problem 4 with the Ellipsoidal Approximation: \begin{align} \mbox{Problem 4': } \max_X \min_i g_i(X) \,\, | \,\, \sqrt{w_{f_i}(X)} \leq b_i \end{align} This is equivalent to the constraints $w_{f_i}(X) \leq b_i^2$. From Theorem~\ref{robust-submax-mulknapsack}, we can obtain a set $\hat{X}$ such that $\min_i g_i(\hat{X}) \leq (1 - \epsilon)\min_i g_i(X^*)$ and $w_{f_i}(X) \leq b_i^2 \log{l/\epsilon}$, which implies that $\sqrt{w_{f_i}(X)} \leq b_i \sqrt{\log{l/\epsilon}}$. Finally note that $f_i(X) \leq O(\sqrt{n}\log n) \sqrt{w_{f_i}(X)} \leq O(\sqrt{n}\log n \sqrt{\log{l/\epsilon}}) b_i$ which then proves the result. To achieve an approximation factor for Problem 3, we use Theorem~\ref{robust-scsc-scsk-eq} to obtain a bicriteria approximation for Problem 3 as well. \end{theorem} } \begin{figure} \centering \includegraphics[width = 0.32\textwidth]{synthetic-cardinality.png} \includegraphics[width = 0.32\textwidth]{coop-matching.png} \includegraphics[width = 0.32\textwidth]{vocab.png} \caption{Synthetic (left), co-operative matching (middle) and data subset selection (right).} \label{fig:my_label} \end{figure} \section{Experimental Results} \textbf{Synthetic Experiments: } The first set of experiments are synthetic experiments. We define $f_j(X) = \sum_{i = 1}^{|\mathcal C_j|} \sqrt{w(X \cap C_{ij})}$ for a clustering $\mathcal C_j = \{C_1, C_2, \cdots, C_{|\mathcal C_j|}$. We define $l$ different random clusterings (with $l = 3$ and $l = 10$). We choose the vector $w$ at random with $w \in [0, 1]^n$ and $n = 50$. We compare the different algorithms under cardinality constraints $(|X| \leq 10)$. The results are shown in Figure 1 (left) and are over 20 runs of random choices in $w$ and $\mathcal C$'s. We observe first that as expected, the AA versions of MMin and EA don't perform as well since it optimizes the average case instead of the worst case. Directly optimizing the worst case performs much better. Next, we observe that MMin performs comparably to EA though its a simpler algorithm (a fact which has been noticed in several other scenarios as well~\cite{rkiyersemiframework2013, nipssubcons2013, jegelka2011-inference-gen-graph-cuts}. \textbf{Co-operative Matchings: } Next, we compare \textsc{Robust-SubMin} in co-operative cuts. We follow the experimental setup in~\cite{iyer2019near}. We run this on the House Dataset~\cite{caetano2009learning}. The results in Figure 1 (middle) are with respect to a simple modular (additive) baseline where the image correspondence problem becomes an assignment problem. We compare two baselines. The first is SubMod~\cite{iyer2019near} which uses a single submodular function. The second is \textsc{Robust-SubMin} where we define several functions (over different clusterings of the pixels in the two images) and we define a robust objective. We run our experiments with $l = 10$ different clustering each obtained by different random initializations of k-means. The class of functions is exactly the same as in~\cite{iyer2019near}. We see that the robust technique outperforms a single submodular function. In this experiment, we consider all pairs of images with the difference in image numbers being 20, 40, 60 and 80 (The $x$-axis in Figure 1 (center) -- this is similar to the setting in~\cite{iyer2019near}). \textbf{Limited Vocabulary Speech Data Selection: } Here, we follow the experimental setup from~\cite{liu2017svitchboard}. The function $f$ is the vocabulary function, $f(X) = w(\gamma(X))$~\cite{liu2017svitchboard}. Here, we define several different functions $f_i$ (we set $l = 10$). To define each function, we randomly delete 20\% of the words from the vocabulary and define $f_i(X) = w(\gamma_i(X))$. The function $g$ is the diversity function and we use the feature based function from~\cite{liu2017svitchboard}, except that we define $k = 10$ different functions $g_i$ each defined via small perturbations of the feature values. The functions $g_i$ are normalized so they are all between $[0, 1]$. The intuition of selecting $f_i$'s and $g_i$'s in this way is to be robust to perturbations in features and vocabulary words. We run these experiments on TIMIT~\cite{timit} and we restrict ourselves to a ground-set size of $|V| = 100$. Again, we compare the different algorithms and arrive at similar conclusions to the synthetic experiments. Firstly, the average case algorithms MMin-AA and EA-AA don't perform as well as MMin and EA themselves. Moreover, MMin and EA perform comparably even though EA is orders of magnitude slower. \section{Conclusions} In this paper, we study four classes of robust submodular optimization problems: \textsc{Robust-SubMin}, \textsc{Robust-SubMax}, \textsc{Robust-SCSC} and \textsc{Robust-SCSK}. We study approximation algorithms and hardness results in each case. We propose a scalable majorization-minimization algorithm which has near optimal approximation bounds and also scales well. In future work, we would like to address the gap between the hardness and approximation bounds, and achieve tight curvature-based bounds in each case. We would also like to study other settings and formulations of robust optimization in future work.\looseness-1
{'timestamp': '2019-06-18T02:02:32', 'yymm': '1906', 'arxiv_id': '1906.06393', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06393'}
arxiv
\subsubsection*{Acknowledgments} This work was supported by the ERC grant ERC-2012-AdG 321162-HELIOS, EPSRC grant Seebibyte EP/M013774/1, EPSRC/MURI grant EP/N019474/1 and the Australian Research Council Centre of Excellence for Robotic Vision (project number CE140100016). We would also like to acknowledge the Royal Academy of Engineering and FiveAI, and thank Richard Hartley and Puneet Dokania for helpful discussions. \section{Pruning without supervision} \begin{wraptable}{r}{6cm} \vspace{-4mm} \centering \scriptsize \caption{ Unsupervised pruning results. } \begin{tabular}{l c cccc} \toprule \vspace{1mm} & & \multicolumn{3}{c}{\textbf{depth L}} \\ \textbf{method} & \textbf{supervision} & 3 & 5 & 7 \\ \midrule cs (${\mathcal{D}}^{b}$) & \cmark & $ $ & $ $ & $ $ \\ cs (${\mathcal{D}}^{\text{train}}$) & \cmark & $2.46$ & $2.43$ & $2.61$ \\ \hline\\[-1.8ex] logit & \xmark & $3.31$ & $3.38$ & $3.60$ \\ prob. & \xmark & $3.11$ & $3.37$ & $3.56$ \\ uniform & \xmark & $2.77$ & $2.77$ & $2.94$ \\ \bottomrule \end{tabular} \label{tab:unsupervised} \end{wraptable} So far, we have shown that network pruning, especially on random networks, can be approached from a signal propagation perspective. One remaining factor that constitutes the connection sensitivity for pruning at initialization is the loss term. At a glance, it is not obvious how informative the supervised loss measured on a random network will be for the connection sensitivity. In this section, we discuss about the effect of supervision and extend it to see whether pruning can be done without supervision. We first check the effect of using true labels in the loss computation. Given the standard cross-entropy as the loss function, the total change in the loss being approximated in Eq.~\ref{eq:csc}, is essentially as follows: \begin{equation} \Delta L_j({\mathbf{w}};{\mathcal{D}}) = -\sum_{i=1}^{{\mathcal{D}}} \sum_{x \in {\mathcal{X}}}p_{i}(x)\ \text{log}\frac{q_{i}(x)}{q_{i}^{{\mathbf{w}}_{\neq j}}(x)} \nsim - \sum_{i=1}^{{\mathcal{D}}} \sum_{x \in {\mathcal{X}}} \frac{1}{|{\mathcal{X}}|} \text{log}\frac{q_{i}(x)}{q_{i}^{{\mathbf{w}}_{\neq j}}(x)}\ , \end{equation} where $p_{i}(x)$ denotes the true distribution with the ground-truth label for example $i$ to be replaced with the pseudo uniform distribution ${\mathcal{U}}(|{\mathcal{X}}|)$, and $q_{i}(x)$ and $q_{i}^{{\mathbf{w}}_{\neq j}}(x)$ are the predicted distributions before and after removing parameter $j$, respectively. Notice, that replacing $p_{i}(x)$ with ${\mathcal{U}}$ amplifies the difference between log probabilities of random networks, and the perturbation grows proportionally with the size of dataset $|{\mathcal{D}}|$. On the other hand, this means that the role of supervision can be minimal, especially in a limited data regime (\emph{e.g}\onedot} \def\Eg{\emph{E.g}\onedot, single-shot, online pruning), which could enable unsupervised pruning without causing a large impact on pruning results. Another possible approach to unsupervised pruning is to measure the sensitivity of the output function instead of the error function. In fact, it is noted in~\cite{engelbrecht2001new} that objective function and output function sensitivity are conceptually the same. However, their conclusion is reached under particular assumptions that do not hold for pruning at initialization regime (\emph{e.g}\onedot} \def\Eg{\emph{E.g}\onedot, extremal approximation assumption, Levenberg-Marquardt assumption). We provide empirical results in Table~\ref{tab:unsupervised}. Even though unsupervised pruning results are not as good as the supervised case, the increase in errors can be regarded marginal, especially for the uniform case, considering that no supervision was given. Notably, all previous pruning algorithms premise the existance of supervision as a priori. Being the first demonstration of unsupervised pruning, along with the signal propagation perspective, one could find it useful to apply this unsupervised pruning strategy to scenarios where it lacks labels or is only provided with weak supervision. \section{Related work} \section{Approach} \section{Pruning random networks as deep information propagation} \SKIP{ In this secion, we do blah blah; The goal is to study pruning deep neural networks at random initialization prior to training. Specifically, we aim to answer the following questions: \begin{tight_itemize} \item Q: How can we prune untrained neural networks? \item Q: How important is initialization? What is the effect of using different initialization schemes? Why scaled Gaussian (VS) works whereas unscaled Gaussian does not? What happens with varying/dense scales (plot as a function of scale)? \item Q: Why some scales lead to higher performance and others lead to worse or unstable performance? $\rightarrow$ more faithful CS leading to better pruning; CS and JSV; develop a Theorem (\emph{e.g}\onedot} \def\Eg{\emph{E.g}\onedot, initialization conditions based on JSV can lead to better pruning or can be predictive of good pruning) \item Q: Can we do better? (orthogonal) \item Q: Can we prune networks without supervision? (yes) \item Q: Sparsity \end{tight_itemize} } We now provide our signal propagation perspective for network pruning inspired by the recent literature on dynamical isometry and mean-field theory~\cite{pennington2017resurrecting,poole2016exponential,saxe2013exact,schoenholz2016deep}. Especially, we are interested in understanding the forward and backward signal propagation of a neural network at a given initialization and derive properties on the initialization that would ensure that the computed \gls{CS} is reliably representing the sensitivity of each connection. \subsection{Signal propagation perspective of neural networks} Note that, signal propagation in a network is said to be {\em faithful} if the input signal is propagated to the output with minimal amplification or attenuation in any of its dimensions. In fact, this faithfulness is directly related to the singular value distribution of the input-output Jacobian of the network. To understand this, we first interpret gradients in terms of layerwise Jacobians and derive conditions on the Jacobians to ensure faithful signal propagation. \SKIP{ \subsubsection{Problem setup} \AJ{This can be moved to the beginning of Sec. 3!} We consider $K$-layer feed forward neural network with weight matrices ${\mathbf{W}}^l\in\mathbb{R}^{N\times N}$, biases ${\mathbf{b}}^l\in\mathbb{R}^N$, pre-activations ${\mathbf{h}}^l\in\mathbb{R}^N$, and post-activations ${\mathbf{x}}^l\in\mathbb{R}^N$, with $l \in \{1\ldots K\}$. Now, the feed forward dynamics at layer $l$ can be written as: \begin{equation}\label{eq:forward} {\mathbf{x}}^l = \phi({\mathbf{h}}^l)\ ,\qquad {\mathbf{h}}^l = {\mathbf{W}}^l{\mathbf{x}}^{l-1} + {\mathbf{b}}^l\ , \end{equation} where $\phi: \mathbb{R} \to\mathbb{R}$ is the elementwise nonlinearity and the input is denoted by ${\mathbf{x}}^0$. With this notation, \SKIP{ the loss function for a given datapoint $({\mathbf{x}}^0, {\mathbf{y}})\in{\mathcal{D}}$ can be written as: \begin{equation} L({\mathbf{w}}; ({\mathbf{x}}^0, {\mathbf{y}})) = \ell\left({\mathbf{x}}^K; {\mathbf{y}}\right)\ , \end{equation} where $\ell(\cdot)$ is the standard loss function (\emph{e.g}\onedot} \def\Eg{\emph{E.g}\onedot, cross-entropy loss) and ${\mathbf{w}}\in\mathbb{R}^m$ denotes the vector of all learnable parameters. } given a dataset ${\mathcal{D}} = \{({\mathbf{x}}_i,{\mathbf{y}}_i)\}_{i=1}^n$, the loss function can be written as:\AJ{This must be moved before Sec. 2 or to be revised!} \begin{equation} L({\mathbf{w}}, {\mathcal{D}}) = \frac{1}{n}\sum_{i=1}^n \ell\left({\mathbf{x}}_i^K; {\mathbf{y}}_i\right)\ , \end{equation} where $\ell(\cdot)$ is the standard loss function (\emph{e.g}\onedot} \def\Eg{\emph{E.g}\onedot, cross-entropy loss) and ${\mathbf{w}}\in\mathbb{R}^m$ denotes the vector of all learnable parameters. Notice, the input-output Jacobian takes the following form: \begin{equation}\label{eq:jac0} {\mathbf{J}}^0 = \frac{\partial {\mathbf{x}}^K}{\partial {\mathbf{x}}^0} = \prod_{l=1}^{K} {\mathbf{D}}^l{\mathbf{W}}^l\ , \end{equation} where ${\mathbf{D}}^l\in\mathbb{R}^{N\times N}$ is a diagonal matrix with entries ${\mathbf{D}}^l_{ij} = \phi'(h_i^l)\delta_{ij}$, with $\phi'$ denoting the derivative of $\phi$, and $\delta_{ij}$ is the Kronecker delta. Here, we use ${\mathbf{J}}^0$ to denote the input-output Jacobian and similarly ${\mathbf{J}}^l$ would denote the Jacobian from layer $l$ to the output. } \subsubsection{Gradients in terms of Jacobians} We consider the problem setup in~\secref{sec:prob} where the input-output Jacobian corresponding to a given input ${\mathbf{x}}^0$ can be written as: \begin{equation}\label{eq:jac0} {\mathbf{J}}^{0,K} = \frac{\partial {\mathbf{x}}^K}{\partial {\mathbf{x}}^0} = \prod_{l=1}^{K} {\mathbf{D}}^l{\mathbf{W}}^l\ , \end{equation} where ${\mathbf{D}}^l\in\mathbb{R}^{N\times N}$ is a diagonal matrix with entries ${\mathbf{D}}^l_{ij} = \phi'(h_i^l)\delta_{ij}$, with $\phi'$ denoting the derivative of nonlinearity $\phi$, and $\delta_{ij} = \mathbbm{1}[i=j]$ is the Kronecker delta. Here, we use ${\mathbf{J}}^{k,l}$ to denote the Jacobian from layer $k$ to layer $l$. \SKIP{ To this end, considering the problem setup in~\secref{sec:prob}, given a dataset ${\mathcal{D}} = \{({\mathbf{x}}_i,{\mathbf{y}}_i)\}_{i=1}^n$, the loss function can be written as: \begin{equation} L({\mathbf{w}}, {\mathcal{D}}) = \frac{1}{n}\sum_{i=1}^n \ell\left({\mathbf{x}}_i^K; {\mathbf{y}}_i\right)\ , \end{equation} where $\ell(\cdot)$ is the standard loss function (\emph{e.g}\onedot} \def\Eg{\emph{E.g}\onedot, cross-entropy loss) and ${\mathbf{w}}\in\mathbb{R}^m$ denotes the vector of all learnable parameters. For the rest of the section, for brevity, we consider that the dataset contains only one datapoint, \emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, $n=1$. From the chain rule, the gradient of the loss with respect to the weight matrix ${\mathbf{W}}^l$ for all $l\in\{1\ldots K\}$ can be written as: \begin{equation}\label{eq:grad-chain} {\mathbf{g}}_{{\mathbf{w}}^l} = \frac{\partial L}{\partial {\mathbf{W}}^l} = \frac{\partial L}{\partial {\mathbf{x}}^K} \frac{\partial {\mathbf{x}}^K}{\partial {\mathbf{x}}^l} \frac{\partial {\mathbf{x}}^l}{\partial {\mathbf{W}}^l}\ . \end{equation} Here, the gradient $\partial {\mathbf{y}}/\partial {\mathbf{x}}$ is represented as a matrix of dimension ${\mathbf{y}}$-size $\times$ ${\mathbf{x}}$-size. } Now, we give the relationship between gradients and the Jacobians below. \begin{pro}\label{pro:grad-jacob} Let ${\mathbf{\epsilon}} = \partial L/\partial {\mathbf{x}}^K$ denote the error signal and ${\mathbf{x}}^0$ denote the input signal. Then, \begin{tight_enumerate} \item the gradients satisfy: \begin{equation}\label{eq:grad-compact} {\mathbf{g}}_{{\mathbf{w}}^l}^T = {\mathbf{\epsilon}}\, {\mathbf{J}}^{l,K}{\mathbf{D}}^l \otimes {\mathbf{x}}^{l-1}\ , \end{equation} where ${\mathbf{J}}^{l,K}=\partial {\mathbf{x}}^K/\partial {\mathbf{x}}^l$ is the Jacobian from layer $l$ to the output and $\otimes$ is the Kronecker product. \item additionally, for linear networks, \emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, when $\phi$ is the identity: \begin{equation}\label{eq:grad-jacob} {\mathbf{g}}_{{\mathbf{w}}^l}^T = {\mathbf{\epsilon}}\, {\mathbf{J}}^{l,K} \otimes \left({\mathbf{J}}^{0,l-1}{\mathbf{x}}^0 +{\mathbf{a}}\right)\ , \end{equation} where ${\mathbf{J}}^{0,l-1} = \partial {\mathbf{x}}^{l-1}/\partial {\mathbf{x}}^0$ is the Jacobian from the input to layer $l-1$ and ${\mathbf{a}}\in\mathbb{R}^{N}$ is the constant term that does not depend on ${\mathbf{x}}^0$. \end{tight_enumerate} \end{pro} \begin{proof} This can be proved by an algebraic manipulation of chain rule while using the feed forward dynamics~\plaineqref{eq:forward}. We provide the full derivation in Appendix~\myref{A}. \end{proof} \SKIP{ Since, $\frac{\partial {\mathbf{x}}^K}{\partial {\mathbf{x}}^l} = {\mathbf{J}}^l$ and using the feed forward dynamics~\plaineqref{eq:forward}, we can compactly write the gradients as: \begin{equation}\label{eq:grad-compact} \left(\frac{\partial L}{\partial {\mathbf{W}}^l}\right)^T = \left(\frac{\partial L}{\partial {\mathbf{x}}^K}\right) {\mathbf{J}}^l \otimes {\mathbf{x}}^{l-1}\ , \end{equation} where $\otimes$ denotes the Kronecker product. Note that, the term $\frac{\partial L}{\partial {\mathbf{x}}^K}$ is the error signal and ${\mathbf{x}}^{l-1}$ denotes the input signal propagated upto the layer $l-1$. Precisely, the activation at layer $l$ can be written as a forward signal propagation: \begin{equation}\label{eq:forward-signal} {\mathbf{x}}^{l} = \left(\prod_{k=1}^{l} {\mathbf{W}}^k\right) {\mathbf{x}}^0 + {\mathbf{a}} = \bar{{\mathbf{J}}}^l{\mathbf{x}}^0 +{\mathbf{a}}\ , \end{equation} where ${\mathbf{a}}\in\mathbb{R}^N$ is the contant term that does not depend on the input ${\mathbf{x}}^0$ and $\bar{{\mathbf{J}}}^l$ denotes the Jacobian from input to the layer $l$. Now the gradient can be written in terms of Jacobians as: \begin{equation}\label{eq:grad-jacob} \left(\frac{\partial L}{\partial {\mathbf{W}}^l}\right)^T = \left(\frac{\partial L}{\partial {\mathbf{x}}^K}\right) {\mathbf{J}}^l \otimes \left(\bar{{\mathbf{J}}}^{l-1}{\mathbf{x}}^0 +{\mathbf{a}}\right)\ . \end{equation} } Notice that, the gradient at layer $l$ constitutes both the backward propagation of the error signal ${\mathbf{\epsilon}}$ up to layer $l$ and the forward propagation of the input signal ${\mathbf{x}}^0$ up to layer $l-1$. Moreover, especially in the linear case, the signal propagation in both directions is governed by the corresponding Jacobians. We believe, this interpretation of gradients is useful as it sheds light on how signal propagation affects the gradients. To this end, next we analyze the conditions on the Jacobians which would guarantee faithful signal propagation and consequently faithful gradients. \subsubsection{Ensuring faithful gradients} Here, we first consider the layerwise signal propagation which would be useful to derive properties on the initialization to ensure faithful gradients. To this end, let us consider the layerwise Jacobian: \begin{equation}\label{eq:ljac} {\mathbf{J}}^{l-1,l}=\frac{\partial {\mathbf{x}}^l}{\partial {\mathbf{x}}^{l-1}} = {\mathbf{D}}^l{\mathbf{W}}^l\ . \end{equation} Note that, to ensure faithful signal propagation, it is sufficient to ensure {\em layerwise dynamical isometry} which is defined as the singular values of the layerwise Jacobian ${\mathbf{J}}^{l-1,l}$ being close to one. This would guarantee that the signal from layer $l$ to $l-1$ (or vice versa) is propagated without amplification or attenuation in any of its dimension. From~\proref{pro:grad-jacob}, by induction, it is easy to show that if the layerwise signal propagation is faithful, the error and input signals are faithfully propagated throughout the network, resulting in faithful gradients. For a linear neural network, ${\mathbf{J}}^{l-1,l} = W^l$. Therefore one can initialize the weight matrices to be {\em orthogonal}, meaning for each layer $l$, initialize the weight matrix such that $({\mathbf{W}}^l)^T{\mathbf{W}}^l = {\mathbf{I}}$, where ${\mathbf{I}}$ is the identity matrix of dimension $N$. In this case, all the singular values of ${\mathbf{W}}^l$ are exactly one and such an initialization would guarantee faithful gradients. On the other hand, the case of nonlinear neural networks is more complicated as the diagonal matrix ${\mathbf{D}}^l$ depends on the pre-activations at layer $l$. In this case, the intuitive idea is to make sure that the pre-activations ${\mathbf{h}}^l$ falls into the linear region of the nonlinear function $\phi$. Precisely, {\em mean-field theory}~\cite{schoenholz2016deep} assumes that for large-$N$ limit, the empirical distribution of the pre-activations ${\mathbf{h}}^l$ converges to a Gaussian with zero mean and variance $q^l$, where the variance follows a recursion relation. Therefore, to ensure layerwise faithful signal propagation, the idea is to find the fixed point $q^*$ such that ${\mathbf{h}}^l \sim {\mathcal{N}}(0,q^*)$ for all $l\in\{1\ldots K\}$. Such a fixed point makes ${\mathbf{D}}^l = {\mathbf{D}}$ for all layers, ensuring that the pre-activations are indeed in the linear region of the nonlinearity. In this case, given the nonlinearity, one can find a rescaling such that $({\mathbf{D}}{\mathbf{W}}^l)^T({\mathbf{D}}{\mathbf{W}}^l) = ({\mathbf{W}}^l)^T{\mathbf{W}}^l/\sigma^2_w ={\mathbf{I}}$. The procedure for finding the rescaling $\sigma^2_w$ for various nonlinearties are discussed in~\cite{pennington2017resurrecting,pennington2018emergence}. Note that {\em dynamical isometry} (singular values of the input-output Jacobian being concentrated around one) is regarded as the condition for faithful signal propagation in a network~\cite{pennington2017resurrecting,saxe2013exact}. In fact, this is a weaker condition than our layerwise dynamical isometry. However, in practice, the initialization method suggested in the existing works~\cite{pennington2017resurrecting,xiao2018dynamical}, \emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, {\em orthogonal initialization for weight matrices in each layer with mean-field theory based rescaling}, satisfy layerwise dynamical isomtery, even though this term was not mentioned. \SKIP{ ************************* In the literature~\cite{pennington2017resurrecting,saxe2013exact}, faithful signal propagation is described as preserving the norm of every single error vector and also the angles between different error vectors.(CHECK){} This condition is known as dynamical isometry. \begin{dfn}\label{dfn:di} A neural network is said to have {\em dynamical isometry} if the singular values of its input-output Jacobian are concentrated around 1. \end{dfn} Given a set of weight matrices, the Jacobian can be uniquely determined according to~\eqref{eq:jac0} and consequently the singular values of the Jacobian can be computed to check for dynamical isometry. However, in practice, to guarantee ``faithful'' signal propagation, in addition to dynamical isometry, the existing works in the literature~\cite{pennington2017resurrecting, etc} recommend {\em orthogonal initialization} for weight matrices in each layer. Precisely, for each layer $l$, initialize the weight matrix such that $({\mathbf{W}}^l)^T{\mathbf{W}}^l = {\mathbf{I}}$, where ${\mathbf{I}}$ is the identity matrix of dimension $N$. In this case, all the singlular values of ${\mathbf{W}}^l$ are exactly $1$. In particular, considering~\eqref{eq:linear-forward}, orthogonal initialization guarantees that the signal propagation in each layer is faithful in the sense that none of the dimensions of the incoming signal is amplified or attenuated. This, by induction, guarantees that the gradients are faithful, meaning that the gradients do not explode or vanish even when the number of layers is large. Furthermore, it is easy to see that such an initialization satisfies dynamical isometry but it is indeed a stronger condition. \subsubsection{Signal propagation in nonlinear networks} So far, we have discussed deep linear networks but the signal propagation perspective is applicable to nonlinear networks as well~\cite{pennington2017resurrecting}. In fact, for a nonlinear network the input-output Jacobian takes the following form: \begin{equation}\label{eq:jac0-nl} {\mathbf{J}}^0 = \frac{\partial {\mathbf{x}}^K}{\partial {\mathbf{x}}^0} = \prod_{l=1}^{K} {\mathbf{D}}^l{\mathbf{W}}^l\ . \end{equation} Here ${\mathbf{D}}^l$ is a diagonal matrix with entries ${\mathbf{D}}^l_{ij} = \phi'(h_i^l)\delta_{ij}$, where $\phi:\mathbb{R}\to\mathbb{R}$ is the elementwise nonlinearity, ${\mathbf{h}}^l\in \mathbb{R}^l$ is the pre-activation and ${\mathbf{x}}^l = \phi({\mathbf{h}}^l)$. In this case, to ensure layerwise faithful signal propagation, the intuitive idea is to initialize weights such that the pre-activations falls into the linear region of the nonlinear function $\phi$.\AJ{solidify this statement}. Formally, initialise weight matrices such that $({\mathbf{W}}^l)^T{\mathbf{W}}^l = \sigma^2_w{\mathbf{I}}$, where $\sigma_w$ depends on the nonlinearity $\phi$. } \SKIP{ \subsection{A perspective of signal propagation to pruning random networks} \AJ{I think we don't need to explain everything regarding dynamical isometry and mean-field theory. We just need to define what is dynamical isometry and say that (citing the relevant papers) if we have DI, signal propagation is ``faithful'' in both forward and backward direction. This implies connection sensitivity is faithful, leading to good sparse networks.} a recap of dynamical isometry and mean field theory; \paragraph{dynamical isometry \cite{saxe2013exact}} For deep linear networks, dynamical isometry can be achieved through orthogonal weight initialization and has been shown to dramatically speed up learning; explain the isometry property, semi-orthogonal matrix; \paragraph{mean field theory} it is about signal propagation (\cite{poole2016exponential} and \cite{schoenholz2016deep}); \cite{schoenholz2016deep} summarizes \cite{poole2016exponential}; fully-connected, untrained, feed-forward, neural network of depth $L$ with layer width $N_{l}$ and some nonlinearity $\phi$; weights and biases are respectively i.i.d as $W_{i,j}^{l} \sim \mathcal{N}(0, \sigma_{w}^{2}/N_{l})$ and $b_{i}^{l} \sim \mathcal{N}(0, \sigma_{b}^{2})$; ``mean-field'' approximation is then to replace the preactivation by a Gaussian whose first two moments match those of the preactivations; (from review in \cite{pennington2017resurrecting}) it means that this empirical distribution (\emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot preactivation) converges to a Gaussian with zero mean and variance $q^{l}$ where $q^{l}$ obeys a recursion relation induced by the dynamics in Eqn. (1); this recursion has a fixed point; if start at the fixed point the distribution of $D^{l}$ becomes independent of $l$; (even if not start at the fixed point) so for large $L$, assuming $q^{l}=q^{\ast}$ at all depths $l$ is a good approximation in computing the spectrum of $J$. another important quantity governing signal propagation through deep networks is $\chi$; $\chi(\sigma_{w}, \sigma_{b})$ separates the $(\sigma_{w}, \sigma_{b})$ plane into chaotic and ordered phases; $\chi=1$ is a critical line of initializations with neither vanishing nor exploding gradients. \cite{pennington2017resurrecting} uses free probability theory to ``establish a theory of the entire singular value distribution of J''; ``controlling the entire distribution of Jacobian singular values is an important design consideration in deep learning''; ``The input-output Jacobian J is closely related to the backpropagation operator mapping output errors to weight matrices at a given layer; if the former is well conditioned, then the latter tends to be well-conditioned for all weight layers.''; \paragraph{jacobian singular values, gradients, and connection sensitivity} \AJ{A rough sketch for this section would look like the following (or at least that is what I'm thinking):} \begin{tight_itemize} \item Signal propagation: Consider, ${\mathbf{y}}=W{\mathbf{x}}$, if all the singular values of $W$ are $1$, we can say perfect signal propagation as none of the dimensions of ${\mathbf{x}}$ are amplified or attenuated! \item For a linear network, since $(\partial L/\partial w^l)^T = \epsilon (J_l \otimes \bar{J}_l) {\mathbf{x}}$, where $\epsilon$ is the error signal, ${\mathbf{x}}$ is the input, $J_l$ is the Jacobian from layer $l$ to the end and $\bar{J}_l$ is Jacobian up to layer $l$. So, to have ``faithful'' gradients we need $(J_l \otimes \bar{J}_l)$ to have all singular values close to $1$. (CHECK) \AJ{This might not be useful!} \item Now, since $\partial L/\partial {\mathbf{c}} = \partial L/\partial({\mathbf{c}}\odot {\mathbf{w}})\odot {\mathbf{w}}$, given gradients, the connection sensitivity for each weight is amplified (or attenuated) by the corresponding element of ${\mathbf{w}}$. \emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, $w_j = 0 \to s_j = 0$ as $w_j=0$ does not contribute to the forward signal propagation. Therefore, we can say if gradients are faithful, then connection sensitivity (CS) is faithful. (CHECK){} May be we want the weight matrices in each layer to be of same scale, to ensure that CS is not poorly scaled for different layers, as only a global threshold is used! \item May be we can define ``faithful'' as the values in each layer to be of same scale? (WORTH THINKING ABOUT THIS) \end{tight_itemize} \begin{tight_itemize} \item Q: Can we develop a mathematical link, from norm-preserving, to trainability, dynamical isometry, to pruning criteria (\emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, connection sensitivity)? \item the condition for dynamical isometry through J has relation to backpropagation operator as stated in \cite{pennington2017resurrecting}; this means that it is also connected to the connection sensitivity in SNIP; SHOW THIS!; \item refer to explanations in ``Dynamical Isometry- 10k CNN'' paper about the signal flow for both forward/backward based on mean field theory \end{tight_itemize} \paragraph{orthogonal initialization as alternative} compare different initialization schemes and present orthogonal init.\\ 1) generalization errors\\ 2) visualize the structure of pruned sparse networks; check for any sign of structural advantage (\emph{e.g}\onedot} \def\Eg{\emph{E.g}\onedot, irregularity, randomness); based on the result the pattern from orthogonal init may better for the standard compressed sparse row format.\\ \AJ{I think you should add all the available results and placeholders for the ones to do! This is important as the majority of the text would depend on the results! Having results in this draft would also make it easier to discuss with Steve when we meet.} } \subsection{Ensuring faithful connection sensitivity} \SKIP{ So far, we have analysed the signal propagation of a neural network to initialize a network such that one can effectively train much deeper networks efficiently (\emph{e.g}\onedot} \def\Eg{\emph{E.g}\onedot, 10,000 layers of CNN without skip connections and/or batch normalization~\cite{xiao2018dynamical}). However, our objective is to initialize a network such that the computed connectiion sensitivity is faithful. In fact, our hope is that if the connection sensitivity is faithful, one can rely on the connection sensitivity to effectively obtain extremely sparse trainable subnetworks in single shot using SNIP.\AJ{polish later} } So far, we have discussed how one should initialize a network to have faithful gradients based on signal propagation. Now, we give the relationship between \gls{CS} and the gradients and show that the same conditions are sufficient to guarantee faithful \gls{CS}. Note that, from~\eqref{eq:sens}, \gls{CS} is a normalized magnitude of gradients with respect to the connectivity parameters ${\mathbf{c}}$. Here, we use the vectorized notation where ${\mathbf{w}}$ denotes all learnable parameters and ${\mathbf{c}}$ denotes the corresponding connectivity parameters. From chain rule, we can write: \begin{equation}\label{sens-to-grad} \left.\frac{\partial L({\mathbf{c}}\odot{\mathbf{w}};{\mathcal{D}})}{\partial {\mathbf{c}}}\right|_{{\mathbf{c}}=\boldsymbol{1}} = \left.\frac{\partial L({\mathbf{c}}\odot{\mathbf{w}};{\mathcal{D}})}{\partial ({\mathbf{c}}\odot{\mathbf{w}})}\right|_{{\mathbf{c}}=\boldsymbol{1}}\odot{\mathbf{w}} = \frac{\partial L({\mathbf{w}};{\mathcal{D}})}{\partial {\mathbf{w}}}\odot{\mathbf{w}}\ . \end{equation} Therefore, $\partial L/\partial {\mathbf{c}}$ is simply the gradients $\partial L/\partial {\mathbf{w}}$ amplified (or attenuated) by the corresponding weights ${\mathbf{w}}$, \emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, $\partial L/\partial c_j= \partial L/\partial w_j\,w_j$ for all $j\in\{1\ldots m\}$. Considering $\partial L/\partial c_j$ for a given $j$, since $w_j$ does not depend on any other layers or signal propagation, the only term that depends on signal propagation of the network is the gradient term $\partial L/\partial w_j$. Therefore, a necessary condition to ensure faithful $\partial L/\partial {\mathbf{c}}$ (and \gls{CS}) is that the gradients $\partial L/\partial {\mathbf{w}}$ need to be faithful. Another important point to consider is that, in \acrshort{SNIP}~\cite{lee2018snip}, a global threshold is chosen based on \gls{CS} to obtain the pruned network (refer~\secref{sec:snip}), which requires the \gls{CS} scores to be of the same scale for each layer. To this end, for faithful \gls{CS}, we require the gradients to be faithful and the weights to be in the same scale for all the layers. Notice, this condition is trivially satisfied when the layerwise dynamical isometry is ensured, as each layer is initialized identically (\emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, orthogonal initialization) and the gradients are guaranteed to be faithful. Note that, based on this signal propagation perspective for network pruning, we explain the failure cases of pruning considered in~\secref{sec:init}. To this end, we measure the singular value distribution of the input-output Jacobian (${\mathbf{J}}^{0,K}$) for the the $7$-layer, fully-connected tanh network and the results are reported in~\tabref{tab:jsv-l7-tanh}. Note that, while \gls{CS} based pruning is robust to moderate changes in the Jacobian singular values, it failed catastrophically when the condition number of the Jacobian is very large ($>1\mathrm{e}{+11}$). In fact, these failure cases correspond to completely disconnected networks as a consequence of pruning based on unreliable \gls{CS} resulted from poorly conditioned initial Jacobians. As we will show subsequently, these findings extend to modern architectures, and our recommended orthogonal initialization yields well-conditioned Jacobians and in turn the best pruning results. \SKIP{ ******************** However, another important point to consider is that, in SNIP~\cite{lee2018snip}, while pruning based on connection sensitivity, top-$\kappa$ elements based on the computed \gls{CS} are retained (where $\kappa$ is the given sparsity level). Since a global threshold is chosen based on \gls{CS}, to reduce the effect of architecture variations it is important to ensure that \gls{CS} scores are of the same scale for each layer. To this end, both the gradients and the weights need to be in the same scale. Note that, the standard way to initialize a network to have dynamical isometry is via the orthogonal initialization where the variance of the weights are the same for each layer~\cite{?}. In other words, in practice, weights and biases in each layer are initialized identically (with a $0$ mean and fixed variance normal distribution) and the weight matrices are constrained to be orthogonal. This can be done even for convolutional layers, see~\cite{xiao2018dynamical}. Such an initialization ensures that both the gradients ($\partial L/\partial {\mathbf{w}}$) and the weights (${\mathbf{w}}$) are of the same scale for each layer which ensures that the connection sensitivity computed at such an initialization will be of same scale for each layer. This is a key contribution of our paper which we believe explains why pruning an untrained neural network with a global threshold was able to obtain a trainable sparse network. This further sheds light on how one should initialize a network for pruning and reinforces our hypothesis that pruning can in fact be considered as finding a subnetwork that ensures faithful signal propagation in forward and backward directions. (CHECK){} Notice, the authors of SNIP~\cite{lee2018snip} suggested a variance scaling initialization~\cite{glorot2010understanding} to compute connection sensitivity. Even though such an initialization does not guarantee dynamical isometry, it has the norm preserving property~\cite{saxe2013exact}, meaning the norm of the gradients are preserved. Furthermore, since the variance of the weights depend on the architectural properties (\emph{e.g}\onedot} \def\Eg{\emph{E.g}\onedot, no of neurons in each layer) the weights in each layer are not guaranteed to be of same scale. Therefore, we believe, the performance of SNIP can be further improved by using the orthogonal initialization which is verified by our experiments as well. } \SKIP{ \subsection{Relation to sparsification} \AJ{ I don't think we have space in the main paper for this} Q: How pruning affects JSV distribution? Can we provide/develop a theoretical result? $\rightarrow$ relation between sparsity and JSV $\rightarrow$ a Theorem; effect of pruning in JSV distribution; theoretical results; empirical results; possible results: 1) sparsification will affect differently Gaussian and orthogonal networks (linear/nonlinear); 2) sparsification will break dynamical isometry (this is bad, but at least orthogonal case is better); Q: Does JSV ``gradually change'' as the sparsity ``gradually increases''? $\rightarrow$ This could mean something very important. This is saying that connection sensitivity is indeed measuring the right thing, because otherwise it would be not ``gradual''. effect of varying level of sparsity; } \begin{table}[t] \centering \scriptsize \caption{ Jacobian singular values and resulting sparse networks for 7-layer tanh MLP network considered in~\secref{sec:init}. Note that the \underline{failure cases} correspond to unreliable \gls{CS} resulted from poorly conditioned initial Jacobians. SG, CN, and Sparsity refer to Scaled Gaussian, Condition Number (\emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, $s_{\text{max}}/s_{\text{min}}$, where $s_{\text{max}}$ and $s_{\text{min}}$ are the maximum and minimum Jacobian singular values), and a ratio of pruned prameters to total number of parameters, respectively. } \begin{tabular}{l c ccc c c c c} \toprule & & \multicolumn{3}{c}{\scriptsize \textbf{Jacobian singular values}} & & \scriptsize \textbf{Sparsity in pruned network} & \\ \addlinespace[0.3em] \multicolumn{1}{c}{\scriptsize \textbf{Initialization}} & & \scriptsize Mean & \scriptsize Std & \scriptsize CN & & l1 \enspace | \enspace l2 \enspace | \enspace l3 \enspace | \enspace l4 \enspace | \enspace l5 \enspace | \enspace l6 \enspace | \enspace l7 & & \scriptsize \textbf{Error}\\ \midrule SG ($\gamma$=$10^{-4}$) & & $2.46\mathrm{e}{-07}$ & $9.90\mathrm{e}{-08}$ & $4.66\mathrm{e}{+00}$ & & $0.97$ | $0.80$ | $0.80$ | $0.80$ | $0.80$ | $0.81$ | $0.48$ & & $2.66$ \\ SG ($\gamma$=$10^{-3}$) & & $5.74\mathrm{e}{-04}$ & $2.45\mathrm{e}{-04}$ & $8.54\mathrm{e}{+00}$ & & $0.97$ | $0.80$ | $0.80$ | $0.80$ | $0.80$ | $0.81$ | $0.48$ & & $2.67$ \\ SG ($\gamma$=$10^{-2}$) & & $4.49\mathrm{e}{-01}$ & $2.51\mathrm{e}{-01}$ & $5.14\mathrm{e}{+01}$ & & $0.96$ | $0.80$ | $0.80$ | $0.80$ | $0.81$ | $0.81$ | $0.49$ & & $2.67$ \\ SG ($\gamma$=$10^{-1}$) & & $2.30\mathrm{e}{+01}$ & $2.56\mathrm{e}{+01}$ & $2.92\mathrm{e}{+04}$ & & $0.96$ | $0.81$ | $0.82$ | $0.82$ | $0.82$ | $0.80$ | $0.45$ & & $2.61$ \\ SG ($\gamma$=$10^{0}$) & & $1.03\mathrm{e}{+03}$ & $2.61\mathrm{e}{+03}$ & $3.34\mathrm{e}{+11}$ & & $0.85$ | $0.88$ | $0.99$ | \textcolor{red}{$1.00$} | \textcolor{red}{$1.00$} | \textcolor{red}{$1.00$} | $0.91$ & & $\underline{90.2}$ \\ SG ($\gamma$=$10^{1}$) & & $3.67\mathrm{e}{+04}$ & $2.64\mathrm{e}{+05}$ & inf & & $0.84$ | $0.95$ | \textcolor{red}{$1.00$} | \textcolor{red}{$1.00$} | \textcolor{red}{$1.00$} | \textcolor{red}{$1.00$} | \textcolor{red}{$1.00$} & & $\underline{90.2}$ \\ \bottomrule \end{tabular} \label{tab:jsv-l7-tanh} \vspace{-3ex} \end{table} \SKIP{ \midrule VS-L~\cite{LeCun1998fficient} & $3.19\mathrm{e}{-01}$ & $1.51\mathrm{e}{-01}$ & $1.81\mathrm{e}{+01}$ & $5.78\mathrm{e}{+00}$ & $0.97$ | $0.80$ | $0.80$ | $0.80$ | $0.81$ | $0.81$ | $0.48$ & $445$ & $2.66$ \\ VS-G~\cite{glorot2010understanding} & $4.71\mathrm{e}{-01}$ & $2.31\mathrm{e}{-01}$ & $2.20\mathrm{e}{+01}$ & $1.03\mathrm{e}{+01}$ & $0.97$ | $0.80$ | $0.80$ | $0.80$ | $0.81$ | $0.81$ | $0.48$ & $433$ & $2.62$ \\ VS-H~\cite{he2015delving} & $1.14\mathrm{e}{+00}$ & $6.43\mathrm{e}{-01}$ & $4.52\mathrm{e}{+01}$ & $5.16\mathrm{e}{+01}$ & $0.97$ | $0.79$ | $0.80$ | $0.80$ | $0.81$ | $0.81$ | $0.48$ & $404$ & $2.69$ \\ \midrule Orthogonal & $3.41\mathrm{e}{-01}$ & $7.35\mathrm{e}{-02}$ & $5.77\mathrm{e}{+00}$ & $1.97\mathrm{e}{+00}$ & $0.97$ | $0.80$ | $0.80$ | $0.80$ | $0.80$ | $0.81$ | $0.47$ & $457$ & $2.61$ \\ } \section{Connection sensitivities for varying $\gamma$} \SKIP{ \section{Effect of re-initialization} \begin{figure}[h!] \centering \includegraphics[height=25mm, trim=0mm 0mm 88mm 0mm, clip]{figure/reinit/reinit_lecun.eps} \includegraphics[height=25mm, trim=15mm 0mm 20mm 0mm, clip]{figure/reinit/reinit_lecun.eps} \includegraphics[height=25mm, trim=15mm 0mm 20mm 0mm, clip]{figure/reinit/reinit_glorot.eps} \includegraphics[height=25mm, trim=15mm 0mm 20mm 0mm, clip]{figure/reinit/reinit_he.eps} % \includegraphics[height=25mm, trim=80mm 0mm 0mm 0mm, clip]{figure/reinit/reinit_he.eps} \vspace{-3mm} \caption{ Effect of re-initialization for MLP-tanh of varying depths and sparsity levels: the changes in generalization error by re-initializing the weights are displayed. Re-initializing does not bring in large differences compared to keeping the original weights. } \label{fig:effect-reinit} \end{figure} We carry out experiments to check the effect of re-initialization. After pruning a dense network, and before starting training the pruned network, we re-initialize it with the same initialization method used to initialize the dense network before pruning. We note that when it comes to re-initialization, we do not consider the structure of the pruned network. This makes the weights be of the same random distribution as ones used for pruning, but different samples; \emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, re-initialization meaning re-sampling of weights. After the re-initialization, we train the same standard way. The results are presented in Figure~\ref{fig:effect-reinit}. In all cases, we find the discrepancy introduced by re-initialization is not distinctive. This should be expected under the pruning-at-initialization regime, since the initial weights on the pruned network are anyway untrained random. This result implies that it is not the particular samples that are important for pruning; rather, it is the distribution that matters. Our finding is consistent with recent research results in~\cite{liu2018rethinking} where they showed that keeping the initial weights for the pruned model does not improve over re-sampling, and that the resulting pruned architectures are more likely to be what brings the benefit. The same was observed with large scale experiments in~\cite{gale2019state}. Unlike the aforementioned works, however, the sparse topology was found from a purely untrained network rather than more or less pretrained network, reinforcing results on the pure effect of re-initialization. } \section{Gradients in terms of Jacobians} \begin{pro}\label{pro:grad-jacob1} Let ${\mathbf{\epsilon}} = \partial L/\partial {\mathbf{x}}^K$ denote the error signal and ${\mathbf{x}}^0$ denote the input signal. Then, \begin{tight_enumerate} \item the gradients satisfy: \begin{equation}\label{eq:grad-compact1} {\mathbf{g}}_{{\mathbf{w}}^l}^T = {\mathbf{\epsilon}}\, {\mathbf{J}}^{l,K}{\mathbf{D}}^l \otimes {\mathbf{x}}^{l-1}\ , \end{equation} where ${\mathbf{J}}^{l,K}=\partial {\mathbf{x}}^K/\partial {\mathbf{x}}^l$ is the Jacobian from layer $l$ to the output and $\otimes$ is the Kronecker product. \item additionally, for linear networks, \emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, when $\phi$ is the identity: \begin{equation}\label{eq:grad-jacob1} {\mathbf{g}}_{{\mathbf{w}}^l}^T = {\mathbf{\epsilon}}\, {\mathbf{J}}^{l,K} \otimes \left({\mathbf{J}}^{0,l-1}{\mathbf{x}}^0 +{\mathbf{a}}\right)\ , \end{equation} where ${\mathbf{J}}^{0,l-1} = \partial {\mathbf{x}}^{l-1}/\partial {\mathbf{x}}^0$ is the Jacobian from the input to layer $l-1$ and ${\mathbf{a}}\in\mathbb{R}^{N}$ is the constant term that does not depend on ${\mathbf{x}}^0$. \end{tight_enumerate} \end{pro} \begin{proof} The proof is based on a simple algebraic manipulation of the chain rule. However, we give it here for completeness. From the chain rule, the gradient of the loss with respect to the weight matrix ${\mathbf{W}}^l$ can be written as: \begin{equation}\label{eq:grad-chain1} {\mathbf{g}}_{{\mathbf{w}}^l} = \frac{\partial L}{\partial {\mathbf{W}}^l} = \frac{\partial L}{\partial {\mathbf{x}}^K} \frac{\partial {\mathbf{x}}^K}{\partial {\mathbf{x}}^l} \frac{\partial {\mathbf{x}}^l}{\partial {\mathbf{W}}^l}\ . \end{equation} Here, the gradient $\partial {\mathbf{y}}/\partial {\mathbf{x}}$ is represented as a matrix of dimension ${\mathbf{y}}$-size $\times$ ${\mathbf{x}}$-size. For gradients with respect to matrices, their vectorized from is used. Notice, \begin{equation} \frac{\partial {\mathbf{x}}^l}{\partial {\mathbf{W}}^l} = \frac{\partial {\mathbf{x}}^l}{\partial {\mathbf{h}}^l}\frac{\partial {\mathbf{h}}^l}{\partial {\mathbf{W}}^l} = {\mathbf{D}}^l \frac{\partial {\mathbf{h}}^l}{\partial {\mathbf{W}}^l}\ . \end{equation} Considering the feed-forward dynamics for a particular neuron $i$, \begin{align} h^l_i &= \sum_{j} W^l_{ij} x^{l-1}_j + b^l_i\ ,\\\nonumber \frac{\partial h^l_i}{\partial W^l_{ij}} &= x^{l-1}_j\ . \end{align} Therefore, using the Kronecker product, we can compactly write: \begin{equation} \frac{\partial {\mathbf{x}}^l}{\partial {\mathbf{W}}^l} = ({\mathbf{D}}^l)^T \otimes ({\mathbf{x}}^{l-1})^T\ . \end{equation} Now,~\eqref{eq:grad-chain1} can be written as: \begin{align} {\mathbf{g}}_{{\mathbf{w}}^l} &= ({\mathbf{\epsilon}}\,{\mathbf{J}}^{l,K}{\mathbf{D}}^l)^T \otimes ({\mathbf{x}}^{l-1})^T\ ,\\\nonumber {\mathbf{g}}_{{\mathbf{w}}^l}^T &= {\mathbf{\epsilon}}\,{\mathbf{J}}^{l,K}{\mathbf{D}}^l \otimes {\mathbf{x}}^{l-1}\ . \end{align} Here, ${\mathbf{A}}^T \otimes {\mathbf{B}}^T = ({\mathbf{A}} \otimes {\mathbf{B}})^T$ is used. Moreover, for linear networks ${\mathbf{D}}^l = {\mathbf{I}}$ and ${\mathbf{x}}^l = {\mathbf{h}}^l$ for all $l\in\{1\ldots K\}$. Therefore, ${\mathbf{x}}^{l-1}$ can be written as: \begin{align} {\mathbf{x}}^{l-1} &= \phi({\mathbf{W}}^{l-1}\phi({\mathbf{W}}^{l-2}\ldots\phi({\mathbf{W}}^1{\mathbf{x}}^0 + {\mathbf{b}}^1)\ldots + {\mathbf{b}}^{l-2})+ {\mathbf{b}}^{l-1})\ ,\\\nonumber &= {\mathbf{W}}^{l-1}({\mathbf{W}}^{l-2}\ldots({\mathbf{W}}^1{\mathbf{x}}^0 + {\mathbf{b}}^1)\ldots + {\mathbf{b}}^{l-2})+ {\mathbf{b}}^{l-1}\ ,\\\nonumber &= \prod_{k=1}^{l-1} {\mathbf{W}}^k {\mathbf{x}}^0 + \prod_{k=2}^{l-1} {\mathbf{W}}^k {\mathbf{b}}^1 + \ldots + {\mathbf{b}}^{l-1}\ ,\\\nonumber &= {\mathbf{J}}^{0,l-1} {\mathbf{x}}^0 + {\mathbf{a}}\ , \end{align} where ${\mathbf{a}}$ is the constant term that does not depend on ${\mathbf{x}}^0$. Hence, the proof is complete. \end{proof} \newpage \section{Experiment settings} \label{sec:setting} We evaluate for MNIST, CIFAR-10, and Tiny-ImageNet image classification tasks. We use sgd with momentum and train up to $80$k (for MNIST) or $100$k (for CIFAR-10 and Tiny-ImageNet) iterations. The initial learning is set $0.1$ and decays by $1/10$ at every $20$k (MNIST) or $25$k (CIFAR-10 and Tiny-ImageNet). The mini-batch size is set to be $100$, $128$, and $200$ for MNIST, CIFAR-10, and Tiny-ImageNet, respectively. For all experiments, we use $10$\% of training set for the validation set. We evaluate at every $1$k and record the lowest test error. All results are the average of either $10$ (for MNIST) or $5$ (for CIFAR-10 and Tiny-ImageNet) runs. When computing \gls{CS}, we always use all examples in the training set to prevent stochasticity by a particular mini-batch. We also use the entire training set when computing Jacobian singular values of a network. Unless stated otherwise, we set the default pruning sparsity level to be $\bar{\kappa}=90$\% (\emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, $90$\% of the entire parameters in the network is pruned away). For all tested architectures, pruning such level of sparsity does not lead to a large accuracy drop. \SKIP{ \section{Early JSV analysis - temporary} \begin{table}[h!] \centering \tiny \caption{ Jacobian singular values and resulting sparse networks for different initialization schemes. L7-tanh.\AJ{Explain the table. say even though robust when Jacobian is badly conditioned SNIP fails} } \begin{tabular}{l cccc c c c} \toprule & \multicolumn{4}{c}{\scriptsize \textbf{Jacobian singular values}} & \scriptsize \textbf{Sparsity in pruned network} & & \\ \multicolumn{1}{c}{\scriptsize \textbf{Initialization}} & \scriptsize mean & \scriptsize std & \scriptsize cn & \scriptsize mean$\times$cn & w1 | w2 | w3 | w4 | w5 | w6 | w7 & \scriptsize \textbf{\# of} \bm{$\vec{0}$} & \scriptsize \textbf{Error}\\ \midrule SG ($\gamma$=$10^{-4}$) & $2.46\mathrm{e}{-07}$ & $9.90\mathrm{e}{-08}$ & $4.66\mathrm{e}{+00}$ & $1.15\mathrm{e}{-06}$ & $0.97$ | $0.80$ | $0.80$ | $0.80$ | $0.80$ | $0.81$ | $0.48$ & $461$ & $2.66$ \\ SG ($\gamma$=$10^{-3}$) & $5.74\mathrm{e}{-04}$ & $2.45\mathrm{e}{-04}$ & $8.54\mathrm{e}{+00}$ & $4.90\mathrm{e}{-03}$ & $0.97$ | $0.80$ | $0.80$ | $0.80$ | $0.80$ | $0.81$ | $0.48$ & $456$ & $2.67$ \\ SG ($\gamma$=$10^{-2}$) & $4.49\mathrm{e}{-01}$ & $2.51\mathrm{e}{-01}$ & $5.14\mathrm{e}{+01}$ & $2.31\mathrm{e}{+01}$ & $0.96$ | $0.80$ | $0.80$ | $0.80$ | $0.81$ | $0.81$ | $0.49$ & $417$ & $2.67$ \\ SG ($\gamma$=$10^{-1}$) & $2.30\mathrm{e}{+01}$ & $2.56\mathrm{e}{+01}$ & $2.92\mathrm{e}{+04}$ & $6.70\mathrm{e}{+05}$ & $0.96$ | $0.81$ | $0.82$ | $0.82$ | $0.82$ | $0.80$ | $0.45$ & $321$ & $2.61$ \\ SG ($\gamma$=$10^{0}$) & $1.03\mathrm{e}{+03}$ & $2.61\mathrm{e}{+03}$ & $3.34\mathrm{e}{+11}$ & $3.45\mathrm{e}{+14}$ & $0.85$ | $0.88$ | $0.99$ | $1.00$ | $1.00$ | $1.00$ | $0.91$ & $679$ & $90.2$ \\ SG ($\gamma$=$10^{1}$) & $3.67\mathrm{e}{+04}$ & $2.64\mathrm{e}{+05}$ & inf & inf & $0.84$ | $0.95$ | $1.00$ | $1.00$ | $1.00$ | $1.00$ | $1.00$ & $916$ & $90.2$ \\ \midrule VS-L~\cite{LeCun1998fficient} & $3.19\mathrm{e}{-01}$ & $1.51\mathrm{e}{-01}$ & $1.81\mathrm{e}{+01}$ & $5.78\mathrm{e}{+00}$ & $0.97$ | $0.80$ | $0.80$ | $0.80$ | $0.81$ | $0.81$ | $0.48$ & $445$ & $2.66$ \\ VS-G~\cite{glorot2010understanding} & $4.71\mathrm{e}{-01}$ & $2.31\mathrm{e}{-01}$ & $2.20\mathrm{e}{+01}$ & $1.03\mathrm{e}{+01}$ & $0.97$ | $0.80$ | $0.80$ | $0.80$ | $0.81$ | $0.81$ | $0.48$ & $433$ & $2.62$ \\ VS-H~\cite{he2015delving} & $1.14\mathrm{e}{+00}$ & $6.43\mathrm{e}{-01}$ & $4.52\mathrm{e}{+01}$ & $5.16\mathrm{e}{+01}$ & $0.97$ | $0.79$ | $0.80$ | $0.80$ | $0.81$ | $0.81$ | $0.48$ & $404$ & $2.69$ \\ \midrule Orthogonal & $3.41\mathrm{e}{-01}$ & $7.35\mathrm{e}{-02}$ & $5.77\mathrm{e}{+00}$ & $1.97\mathrm{e}{+00}$ & $0.97$ | $0.80$ | $0.80$ | $0.80$ | $0.80$ | $0.81$ | $0.47$ & $457$ & $2.61$ \\ \bottomrule \end{tabular} \label{tab:jsv-l7-tanh1} \end{table} \begin{table}[h!] \centering \tiny \caption{ Jacobian singular values and resulting sparse networks for different initialization schemes. L5-tanh \NL{Update according to changes to be made in the main table.} } \begin{tabular}{l cccc c c c} \toprule & \multicolumn{4}{c}{\scriptsize \textbf{Jacobian singular values}} & \scriptsize \textbf{Sparsity in pruned network} & & \\ \multicolumn{1}{c}{\scriptsize \textbf{Initialization}} & \scriptsize mean & \scriptsize std & \scriptsize cn & \scriptsize mean$\times$cn & w1 | w2 | w3 | w4 | w5 & \scriptsize \textbf{\# of} \bm{$\vec{0}$} & \scriptsize \textbf{Error}\\ \midrule SG ($\gamma$=$10^{-4}$) & $2.44\mathrm{e}{-05}$ & $7.90\mathrm{e}{-06}$ & $3.56\mathrm{e}{+00}$ & $8.69\mathrm{e}{-05}$ & $0.96$ | $0.76$ | $0.76$ | $0.77$ | $0.45$ & $443$ & $2.55$ \\ SG ($\gamma$=$10^{-3}$) & $5.70\mathrm{e}{-03}$ & $2.01\mathrm{e}{-03}$ & $6.64\mathrm{e}{+00}$ & $3.78\mathrm{e}{-02}$ & $0.96$ | $0.76$ | $0.76$ | $0.77$ | $0.44$ & $438$ & $2.53$ \\ SG ($\gamma$=$10^{-2}$) & $5.59\mathrm{e}{-01}$ & $2.74\mathrm{e}{-01}$ & $3.80\mathrm{e}{+01}$ & $2.13\mathrm{e}{+01}$ & $0.96$ | $0.77$ | $0.77$ | $0.77$ | $0.44$ & $368$ & $2.53$ \\ SG ($\gamma$=$10^{-1}$) & $1.28\mathrm{e}{+01}$ & $1.22\mathrm{e}{+01}$ & $9.19\mathrm{e}{+03}$ & $1.17\mathrm{e}{+05}$ & $0.96$ | $0.77$ | $0.77$ | $0.77$ | $0.42$ & $262$ & $2.51$ \\ SG ($\gamma$=$10^{0}$) & $2.19\mathrm{e}{+02}$ & $4.55\mathrm{e}{+02}$ & $1.34\mathrm{e}{+11}$ & $2.94\mathrm{e}{+13}$ & $0.90$ | $0.87$ | $0.91$ | $0.91$ | $0.58$ & $69 $ & $2.45$ \\ SG ($\gamma$=$10^{1}$) & $3.00\mathrm{e}{+03}$ & $1.51\mathrm{e}{+04}$ & inf & $- $ & $0.86$ | $0.97$ | $1.00$ | $1.00$ | $0.97$ & $498$ & $90.2$ \\ \midrule VS-L~\cite{LeCun1998fficient} & $3.86\mathrm{e}{-01}$ & $1.52\mathrm{e}{-01}$ & $1.20\mathrm{e}{+01}$ & $4.62\mathrm{e}{+00}$ & $0.96$ | $0.76$ | $0.76$ | $0.77$ | $0.44$ & $422$ & $2.57$ \\ VS-G~\cite{glorot2010understanding} & $5.77\mathrm{e}{-01}$ & $2.38\mathrm{e}{-01}$ & $1.48\mathrm{e}{+01}$ & $8.57\mathrm{e}{+00}$ & $0.96$ | $0.76$ | $0.76$ | $0.77$ | $0.43$ & $403$ & $2.57$ \\ VS-H~\cite{he2015delving} & $1.08\mathrm{e}{+00}$ & $5.01\mathrm{e}{-01}$ & $2.30\mathrm{e}{+01}$ & $2.49\mathrm{e}{+01}$ & $0.96$ | $0.76$ | $0.76$ | $0.77$ | $0.43$ & $371$ & $2.50$ \\ \midrule Orthogonal & $4.13\mathrm{e}{-01}$ & $8.31\mathrm{e}{-02}$ & $5.14\mathrm{e}{+00}$ & $2.12\mathrm{e}{+00}$ & $0.96$ | $0.76$ | $0.77$ | $0.77$ | $0.43$ & $424$ & $2.43$ \\ \bottomrule \end{tabular} \label{tab:jsv-l5-tanh1} \end{table} } \section{Implementation, practical details} truncated normal distribution has issues \begin{tight_itemize} \item no longer strictly Gaussian \item implementation issues in tensorflow \item ``truncated_normal'' does not re-scale the variance, meaning that the samples using this distribution will not have the desired variance (\emph{e.g}\onedot} \def\Eg{\emph{E.g}\onedot, 1.0). \item difference TF versions use different VS initialization; e.g., in TF-1.3, the variance does not get re-scaled, whereas TF (higher) the variance gets re-scaled. \end{tight_itemize} Therefore, it might be better to use ``untruncated_normal'' distribution for both for itself and for VS initialization. upgrade to the highest TF. \section{Introduction} Deep learning has made great strides in machine learning and been applied to various fields from computer vision and natural language processing, to health care and board games~\cite{lecun2015deep}. Despite the immense success, however, it remains challenging to deal with the excessive computational and memory requirements of large neural network models. To this end, lightweight models are often preferred, and \emph{network pruning}, a technique to reduce the number of parameters in a network, has been widely employed to compress deep neural networks~\cite{han2015deep}. Nonetheless, designing pruning algorithms has been lacking rigorous underpinning, because pruning was typically carried out on a pretrained model as a post-processing step, or it has been incorporated within the training procedure. Recently,~\citet{lee2018snip} have shown that pruning can be done on randomly initialized neural networks, without a laborious pretraining step, at single-shot prior to training (\emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, \emph{pruning at initialization}). They empirically showed that as long as the initial random weights are drawn from a scaled Gaussian (\emph{e.g}\onedot} \def\Eg{\emph{E.g}\onedot,~\cite{glorot2010understanding}), their pruning criterion called \gls{CS} can be used to prune deep neural networks, often to an extreme level of sparsity while maintaining good accuracy once trained. However, it remains unclear as to how pruning at initialization is feasible, how it should be understood and whether it can be extended further. In this work, we first empirically analyze the effect of initialization on their pruning criterion and the result of pruning for fully-connected networks with varying depths and nonlinearities. Precisely, even though \acrshort{SNIP}~\cite{lee2018snip} is robust to various initialization schemes, it fails catastrophically in some cases. Deeper investigation shows that the failure cases of \acrshort{SNIP} corresponds to the cases where the computed \gls{CS} is unreliable, in that it does not faithfully measure the sensitivity of each connection. This observation leads to a signal propagation perspective for pruning at initialization, by noting that, to ensure faithful \gls{CS}, it is important to guarantee that the input and error signals propagates with minimal amplification or attenuation in the forward and backward directions, respectively. Such an interpretation enables us to provide a formal characterization of how one should initialize a network to have faithful \gls{CS} and in turn effective pruning at initialization. Our signal propagation perspective is inspired by the recent literature on dynamical isometry and mean-field theory~\cite{pennington2017resurrecting,poole2016exponential,saxe2013exact,schoenholz2016deep} where the objective is to understand and ensure faithful signal propagation while training. In this work, we extend this signal propagation perspective to network pruning at initialization by noting that \gls{CS} is a form of gradient signal. Then, we show that a sufficient condition to ensure faithful \gls{CS} is {\em layerwise dynamical isometry}, which is defined as the singular values of the layerwise Jacobians being close to one. Note that this is a stronger condition than {\em dynamical isometry} (singular values of the input-output Jacobian being concentrated around one), and yet, the initialization method suggested in existing works, \emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, {\em orthogonal initialization}~\cite{pennington2017resurrecting,xiao2018dynamical} in fact satisfies layerwise dynamical isometry and can be employed to obtain faithful \gls{CS}. Notice, perfect layerwise dynamical isometry cannot always be ensured in the modern networks that have components such as \acrlong{RELU} nonlinearities~\cite{pennington2017resurrecting} and/or batch normalization~\cite{yang2019mean}. However, even in such cases, our experiments on various modern architectures (including convolutional, residual and recurrent networks) indicate that \gls{CS} computed based on orthogonal initialization is robust and results in effective pruning consistently outperforming pruning based on other initializations. This indicates that the signal propagation perspective is not only important to theoretically understand pruning at initialization, but also it improves the results of pruning for a range of networks of practical interest. Furthermore, this signal propagation perspective for pruning poses another important question: how informative is the error signal computed on random networks, or can we prune neural networks even without supervision? To understand this, we compute \gls{CS} with different unsupervised surrogate losses and evaluate the pruning results. Interestingly, our results indicate that we can in fact prune networks in an unsupervised manner to extreme sparsity levels without compromising accuracy, and it often compares competitively to pruning with supervision. Moreover, we test if pruning at initialization can be extended to obtain architectures that yield better performance than standard pre-designed architectures with the same number of parameters. In fact, this process, which we call {\em neural architecture sculpting}, compares favorably against hand-designed architectures, taking network pruning one step further towards neural architecture search. \SKIP{ Our contributions are summarized in the following: \vspace{-2mm} \begin{tight_itemize} \item We provide a formal characterization on initialization conditions suited for pruning at initialization based on a signal propagation perspective. \item We find in our experiments on a range of architectures and standard image classification datasets that the statistics of a network's Jacobian singular values highly correlate with pruning results, and the orthogonal initialization consistently outperforms other initialization alternatives. \item We demonstrate the effectiveness of unsupervised pruning as well as neural architecture sculpting. \end{tight_itemize} } \SKIP{ We summarize our contributions: \vspace{-\topsep} \begin{tight_itemize} \item signal propagation perspective to pruning random networks at initialization \item theoretical results \item experiments: evaluate on various networks, extend to unsupervised pruning, architecture sculpting, showing potential \end{tight_itemize} \AJ{revise, once the experimental section is finalized!} } \SKIP{ We explain this (\emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, how pruning can be done on untrained neural networks using connection sensitivity measured at random initialization) from the perspective of signal propagation. We draw a link between connection sensitivity and signal propagation based on mean field theory. We claim that connection sensitivity can be measured more reliably by making the signal flow more faithful, for which the signal propagates better. In essence, it is because the connection sensitivity is based on gradient which is related to jacobian signular values; if jacobian singular value distribution is well conditioned, the signal propagates better. We give this as the reason why scaled Gaussian led to better pruning compared to unscaled Gaussian. Under some conditions where dynamical isometry is achieved pruning can be improved further (orthogonal initialization). As a result, this enhanced sensitivity can improve pruning. We show that orthogonal weights initialization, rather than Gaussian, can improve pruning. We claim that signal propgation perspective is a new important idea for network pruning. Also, we develop some theory (\emph{e.g}\onedot} \def\Eg{\emph{E.g}\onedot, relation between cs and jsv, restricted/delta dynamical isometry, sparsification). We show that pruning can be done without supervision, showing that the pruning is irrelevant to task. We show that our theoretical results are supported by extensive experiments. We show that in general connection sensitivity with good initialization (good conditions preserving dynamical isometry) can improve pruning. We start with deep linear neural networks, an important starting point for understanding pruning neural networks at initialization. (deep linear network exhibits highly nonlinear learning dynamics with non-convex error surface, thereby connection sesntivitiy as well;) We show that pattern observed in the ideal case carries over to non-ideal settings and popular networks. We show that it works well for recurrent neural networks. We show others (\emph{e.g}\onedot} \def\Eg{\emph{E.g}\onedot, trainability, ). Summarize the contributions. builds based on the fact that, \gls{CS} is in fact a form of gradient~\cite{lee2018snip}, and therefore, to ensure faithful \gls{CS} it is sufficient to ensure faithful signal propagation in the forward and backward directions of the neural network. Specifically, we show that a sufficient condition to ensure faithful \gls{CS} is {\em layerwise dynamical isometry}, which is defined as the singular values of the layerwise Jacobians being close to $1$. We would like to point out that, in the literature~\cite{pennington2017resurrecting,saxe2013exact}, {\em dynamical isometry} (singular values of the input-output Jacobian being concentrated around $1$) is regarded as the condition for faithful signal propagation in a network. In fact, this is a weaker condition than our layerwise dynamical isometry, however, in practice, the initialization method suggested in the existing works~\cite{pennington2017resurrecting,xiao2018dynamical} in fact satisfies layerwise dynamical isometry. Precisely, to ensure faithful \gls{CS}, each layer in the network needs to be initialized identically where the weight matrices are scaled orthogonal with the scale determined by the nonlinearity. } \section{Preliminaries}\label{sec:snip} \vspace{-1ex} The ultimate goal of network pruning is to find an architecture that balances between the model complexity and generalization~\cite{reed1993pruning}. While doing so, the principle behind conventional approaches is to find unnecessary parameters such that by eliminating them it reduces the complexity of a model while minimizing the impact on what is learned. Naturally, a typical pruning algorithm starts after convergence to a minimum or is performed during training. This pretraining requirement has been left unattended until a recent work~\cite{lee2018snip}, where the authors showed that pruning can be performed on untrained networks at initiailzation prior to training. They proposed a method called \acrshort{SNIP} which relies on a new saliency criterion (\emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, \gls{CS}) that is designed to be computed at initialization, to identify redundant parameters. Specifically, \gls{CS} is defined as: \begin{equation}\label{eq:sens} s_j ({\mathbf{w}}; {\mathcal{D}}) = \frac{\left|g_j({\mathbf{w}};{\mathcal{D}})\right| }{\sum_{k=1}^m \left|g_k({\mathbf{w}};{\mathcal{D}})\right|}\ ,\qquad \text{where}\quad g_j({\mathbf{w}};{\mathcal{D}}) = \left.\frac{\partial L({\mathbf{c}}\odot{\mathbf{w}};{\mathcal{D}})}{\partial c_j}\right|_{{\mathbf{c}}=\boldsymbol{1}}\ . \end{equation} Here, $s_j$ is the saliency of the parameter $j$, ${\mathbf{w}}$ is the network parameters, ${\mathbf{c}}$ is the auxiliary indicator variables representing the connectivity of network parameters, and ${\mathcal{D}}$ is a given dataset. Also, $g_j$ is the derivative of the loss $L$ with respect to $c_j$, which turned out to be an infinitesimal approximation of the change in the loss with respect to removing the parameter $j$. Based on the above sensitivity, pruning is performed by choosing top-$\kappa$ (where $\kappa$ denotes a desired sparsity level) salient parameters. It is found that \acrshort{SNIP} tends to be reliable as long as the sensitivity is measured at initial weights drawn from a layerwise scaled Gaussian (\emph{e.g}\onedot} \def\Eg{\emph{E.g}\onedot, \cite{glorot2010understanding}). However, it remains rather unclear as to what it means to measure saliency scores on untrained neural networks. We investigate this throughout the paper. \SKIP{ The ultimate goal of network pruning is to find an architecture that balances between the model complexity and generalization~\cite{reed1993pruning}. While doing so, the principle behind conventional approaches is to find unnecessary parameters such that by eliminating them it reduces the complexity of a model while minimizing the impact on what is learned. Naturally, a typical pruning algorithm starts after convergence to a minimum or is performed during training. This pretraining requirement has been left unattended until a recent work~\cite{lee2018snip}, where the authors showed that pruning can be performed on untrained neural networks at initiailzation prior to training. They proposed a method called \acrshort{SNIP} which relies on a new saliency criterion (\gls{CS}) that is designed to be computed at initialization, to identify unnecessary parameters. Specifically, \gls{CS} is defined as: \begin{equation}\label{eq:sens} s_j ({\mathbf{w}}; {\mathcal{D}}) = \frac{\left|g_j({\mathbf{w}};{\mathcal{D}})\right| }{\sum_{k=1}^m \left|g_k({\mathbf{w}};{\mathcal{D}})\right|}\ ,\qquad\qquad g_j({\mathbf{w}};{\mathcal{D}}) = \left.\frac{\partial L({\mathbf{c}}\odot{\mathbf{w}};{\mathcal{D}})}{\partial c_j}\right|_{{\mathbf{c}}=\boldsymbol{1}}\ , \end{equation} where $s_j$ is the saliency of the parameter $j$, ${\mathbf{w}}$ is the network parameters, and ${\mathcal{D}}$ is a given dataset. Also, $g_j$ is the derivative of the loss $L$ with respect to $c_j$, which turned out to be an infinitesimal approximation of the change in the loss, and ${\mathbf{c}}$ is the auxiliary indicator variables representing connectivity of parameters. Based on the above sensitivity, pruning is performed by choosing top-$\kappa$ (where $\kappa$ denotes a desired sparsity level) salient parameters. It is found that \acrshort{SNIP} tends to be reliable as long as the sensitivity is measured at initial weights drawn from a layerwise scaled Gaussian (\emph{e.g}\onedot} \def\Eg{\emph{E.g}\onedot, \cite{glorot2010understanding}). However, it remains rather unclear as to what it means to measure saliency scores on untrained neural networks. We investigate this throughout the paper. } \SKIP{ \SKIP{ The ultimate goal of network pruning is to find an architecture that balances between the model complexity and generalization. The principle behind conventional approaches is to find unnecessary parameters such that by eliminating them it reduces the complexity of a model while minimizing the impact on what is learned. Naturally, a typical pruning algorithm starts after convergence to a minimum or is performed during training. \AJ{Not sure about the purpose of the above paragraph? Shouldn't this be already discussed in the intro?} } \AJ{May be shortened and just say CS is a normalized magnitude of ${\mathbf{g}}$ where ${\mathbf{g}}$ is the derivative of loss wrt to the connectivity parameters ${\mathbf{c}}$? } In this section, we briefly review a recent pruning method, \acrshort{SNIP}~\cite{lee2018snip}, that prunes a given network in single-shot at initialization prior to training. In fact, this approach viewed pruning in an architecture selection perspective as opposed to the traditional methods~\AJ{cite} where pruning is treated as an optimization to remove redundant parameters while minimizing the impact on what has been learned on the model. The core idea of \acrshort{SNIP} is a new saliency criterion called \acrfull{CS} that is designed to be computed at initialization, with which pruning can be done on untrained neural networks. To be specific, the basic idea of \gls{CS} was to measure how removing a learnable parameter $w_j$ from the network affect the loss, denoted as: \begin{equation} \Delta L_j({\mathbf{w}};{\mathcal{D}}) = L(\boldsymbol{1} \odot {\mathbf{w}}; {\mathcal{D}}) - L((\boldsymbol{1} - {\mathbf{e}}_j)\odot {\mathbf{w}}; {\mathcal{D}})\ , \end{equation} where $L$ is the network loss function which depends on the learnable parameters ${\mathbf{w}}$ and the dataset ${\mathcal{D}}$, and ${\mathbf{e}}_j$ is the indicator vector of element $j$. In \acrshort{SNIP}, for computational efficiency, $\Delta L_j({\mathbf{w}};{\mathcal{D}})$ is approximated by its infinitesimal version: \begin{align}\label{eq:csc} \Delta L_j({\mathbf{w}};{\mathcal{D}}) &\approx g_j({\mathbf{w}};{\mathcal{D}}) = \left.\frac{\partial L({\mathbf{c}}\odot{\mathbf{w}};{\mathcal{D}})}{\partial c_j}\right|_{{\mathbf{c}}=\boldsymbol{1}} = \left.\lim_{\delta\to 0} \frac{L({\mathbf{c}} \odot{\mathbf{w}};{\mathcal{D}}) - L(({\mathbf{c}} - \delta\,{\mathbf{e}}_j) \odot{\mathbf{w}};{\mathcal{D}})}{\delta}\right|_{{\mathbf{c}}=\boldsymbol{1}}\ , \\[-7mm]\nonumber \end{align} where ${\mathbf{c}}$ is the newly introduced auxiliary indicator variables representing the connectivity of parameters. Now, \gls{CS} for parameter $j$ is defined as the normalized magnitude of the gradients ${\mathbf{g}}({\mathbf{w}}; {\mathcal{D}})$: \begin{equation}\label{eq:sens} s_j ({\mathbf{w}}; {\mathcal{D}}) = \frac{\left|g_j({\mathbf{w}};{\mathcal{D}})\right| }{\sum_{k=1}^m \left|g_k({\mathbf{w}};{\mathcal{D}})\right|}\ \end{equation} Pruning is then performed by choosing top-$\kappa$ (where $\kappa$ denotes the desired sparsity level) salient parameters based on \gls{CS} vector ${\mathbf{s}}$. Notably, in \acrshort{SNIP}, \gls{CS} is computed at initialization, specifically ${\mathbf{w}}$ is a sample from a variance scaling distribution~\cite{glorot2010understanding} and they recommend the use of a minibatch of data. Even though, they empirically showed that \gls{CS} is reliable as long as ${\mathbf{w}}$ is initialized using variance scaling, it remains rather unclear as to what it means to measure some saliency scores on untrained neural networks. In the following sections, we first investigate the effect of initialization empirically and then provide a signal propagating perspective which would ensure that the computed \gls{CS} is reliable. } \section{Validation and extensions} In this section, we evaluate the idea of employing faithful initialization on a wide variety of settings. We further study the role of supervision under the pruning at initialization regime, extending it to unsupervised pruning. Our results show that indeed, pruning can be approached from the signal propagation perspective at varying scale, bringing forth the notion of neural architecture sculpting. All experiments were conducted using TensorFlow, and the experiment settings used to generate the presented results are described in detail in Appendix~\ref{sec:setting}. \subsection{Evaluation on various neural networks and datasets} \begin{table}[t!] \centering \scriptsize \caption{ Pruning results for various neural networks on different datasets. All networks are pruned for the sparsity $\bar{\kappa}=90$\%. We report condition numbers (CN) and generalization errors on MNIST (LeNet, GRU) and CIFAR-10 (VGG16, ResNets). (d) and (s) refer to dense and sparse networks, corresponding to the network before and after pruning, respectively. The \underline{lowest} (or closest to 1) condition numbers and \textbf{best} errors are highlighted in each column. } \begin{tabular}{l c rrr | rrr | rrr} \toprule \addlinespace[0.5em] & & \multicolumn{3}{c}{\textbf{LeNet}} & \multicolumn{3}{c}{\textbf{GRU}} & \multicolumn{3}{c}{\textbf{VGG16}} \\ \addlinespace[0.1em] \textbf{Initialization} & \textbf{Superv.} & CN (d) & CN (s) & Error & CN (d) & CN (s) & Error & CN (d) & CN (s) & Error \\ \midrule VS-L~\cite{LeCun1998fficient} & \cmark & 6.7 & 8.1 & 1.69 & 4.8 & 4.8 & 1.25 & 3.7 & 5.7 & 8.16 \\ VS-G~\cite{glorot2010understanding} & \cmark & 6.7 & 9.4 & 1.75 & 3.9 & 3.9 & 1.20 & 3.7 & 5.0 & 8.18 \\ VS-H~\cite{he2015delving} & \cmark & 6.7 & 9.6 & 1.81 & 5.4 & 5.7 & 1.28 & 3.7 & 11.4 & 8.36 \\ Orthogonal & \cmark & \underline{4.5} & \underline{5.7} & \textbf{1.61} & \underline{3.3} & \underline{3.4} & \textbf{1.18} & \underline{2.9} & \underline{4.2} & \textbf{8.11} \\ Orthogonal & \xmark & \underline{4.5} & 7.9 & 1.83 & \underline{3.3} & 3.6 & 1.35 & \underline{2.9} & 9.1 & 8.25 \\ \midrule \addlinespace[0.5em] & & \multicolumn{3}{c}{\textbf{ResNet32}} & \multicolumn{3}{c}{\textbf{ResNet56}} & \multicolumn{3}{c}{\textbf{ResNet110}} \\ \addlinespace[0.1em] \textbf{Initialization} & \textbf{Superv.} & CN (d) & CN (s) & Error & CN (d) & CN (s) & Error & CN (d) & CN (s) & Error \\ \midrule VS-L~\cite{LeCun1998fficient} & \cmark & 10.4 & 50.9 & 11.96 & 35.3 & 185.3 & 10.43 & \underline{66.2} & 1530.9 & 9.13 \\ VS-G~\cite{glorot2010understanding} & \cmark & 11.0 & 55.0 & 11.89 & 36.9 & 191.1 & 10.60 & 74.0 & 1450.0 & 9.17 \\ VS-H~\cite{he2015delving} & \cmark & 14.6 & 234.9 & 12.21 & 78.7 & 2489.4 & 10.63 & 182.7 & 150757.4 & 9.08 \\ Orthogonal & \cmark & \underline{8.1} & \underline{36.3} & \textbf{11.55} & \underline{31.3} & \underline{170.4} & \textbf{10.08} & 83.1 & 1176.7 & 8.88 \\ Orthogonal & \xmark & \underline{8.1} & 38.4 & 11.69 & \underline{31.3} & 186.1 & 11.01 & 83.1 & \underline{1081.4} & \textbf{8.82} \\ \bottomrule \end{tabular} \label{tab:modern-networks} \end{table} In this section, we validate our signal propagation perspective for pruning networks at initialization. To this end, we demonstrate that the orthogonal initialization enables faithful signal propagation, yielding enhanced pruning results. Specifically, we provide condition numbers of the input-output Jacobian of the networks (\emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, $s_{\text{max}}/s_{\text{min}}$) for both before and after pruning, and show that they correlate highly with the performance of pruned sparse networks. We evaluate various network models on different image classification datasets. All results are the average of multiple runs (\emph{e.g}\onedot} \def\Eg{\emph{E.g}\onedot, 10 runs for MNIST and 5 runs for CIFAR-10), and we do not optimize anything specific for a particular case (see Appendix~\ref{sec:setting} for experiment settings). The results are presented in Table~\ref{tab:modern-networks}. First of all, the best pruning results are achieved with the orthogonal initialization. Looking it closely, it is evident that there exists a high correlation between the condition numbers (both before and after pruning) and the performance of pruned networks; \emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, the network initialized or pruned to have the \underline{lowest} condition number achieves the \textbf{best} generalization error (with an exception for ResNet110). Note, all Jacobian singular values being close to 1 (\emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, dynamical isometry), by definition, states how faithful a network will be with regard to letting signals to propagate without amplifying or attenuating. Therefore, the fact that the condition number of the dense network being close to 1 (or relatively closer towards 1) tends to yield good generalization errors, validates that our signal propagation perspective is indeed effective for pruning at initialization. Furthermore, in~\tabref{tab:modern-networks}, there is a clear correlation between condition numbers of the Jacobians before and after pruning based on \gls{CS}, \emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, the lower CN of the dense network leads to lower CN of the sparse network in most cases. This clearly indicates that \gls{CS} is not drastically destroying the signal propagation properties of the network while pruning, even though this is not explicitly enforced. To validate this, we performed random pruning on LeNet with orthogonal initialization for the same sparsity level. Indeed, even though initial Jacobian is well-conditioned, random pruning completely destroyed the signal propagation yielding a sparse network with an extremely large condition number and the higher generalization error of $2.67$\%. \begin{wraptable}{r}{5.5cm} \vspace{-4mm} \centering \scriptsize \caption{ Tiny-ImageNet results. } \begin{tabular}{l cc} \toprule \textbf{Initialization} & \textbf{WRN-16} & \textbf{WRN-22}\\ \midrule VS-L~\cite{LeCun1998fficient} & 45.08 (0.345) & 44.20 (1.006) \\ VS-G~\cite{glorot2010understanding} & 44.56 (0.339) & 43.11 (0.274) \\ VS-H~\cite{he2015delving} & 46.62 (0.684) & 44.77 (0.461) \\ Orthogonal & \textbf{44.20} (0.314) & \textbf{42.53} (0.348) \\ \bottomrule \end{tabular} \vspace{-2mm} \label{tab:tiny-imagenet} \end{wraptable} We further evaluate for wide residual networks on Tiny-ImageNet, and find that the results are consistent (see Table~\ref{tab:tiny-imagenet}). We note that Tiny-Imagenet is in general harder than the original ImageNet, due to the reduced resolution and the number of examples but still a large number of classes. Moreover, pruning of very deep residual networks (\emph{e.g}\onedot} \def\Eg{\emph{E.g}\onedot, $110$ layers) is rarely tested in the literature. \newpage \subsection{Pruning without supervision} \begin{wraptable}{r}{6cm} \vspace{-3mm} \centering \scriptsize \caption{ Unsupervised pruning results. For all cases orthogonal initialization is used, and pruned for the sparsity of $\bar{\kappa}=90$\%. } \begin{tabular}{l@{\hspace{.6\tabcolsep}} c cccc} \toprule \vspace{1mm} & & \multicolumn{3}{c}{\textbf{Depth $K$}} \\ \textbf{Loss} & \textbf{Superv.} & 3 & 5 & 7 \\ \midrule GT & \cmark & $2.46$ & $2.43$ & $2.61$ \\ \hline\\[-1.8ex] Pred. (raw) & \xmark & $3.31$ & $3.38$ & $3.60$ \\ Pred. (softmax) & \xmark & $3.11$ & $3.37$ & $3.56$ \\ Unif. & \xmark & $2.77$ & $2.77$ & $2.94$ \\ \bottomrule \end{tabular} \label{tab:unsupervised} \end{wraptable} So far, we have shown that pruning random networks can be approached from a signal propagation perspective by ensuring faithful \gls{CS}. Notice, another factor that constitutes \gls{CS} is the loss term. At a glance, it is not obvious how informative the supervised loss measured on a random network will be for \gls{CS}. In this section, we check the effect of supervision, by simply replacing the loss computed using ground-truth labels with different unsupervised surrogate losses as follows: replacing the target distribution using ground-truth labels with uniform distribution (Unif.), and using the averaged output prediction of the network (Pred.; softmax/raw). The results on MLP networks are in Table~\ref{tab:unsupervised}. Even though unsupervised pruning results are not as good as the supervised case, the results are still interesting, especially for the uniform case, in that there was no supervision given to compute \gls{CS}. We thus experiment the uniform case on other networks as well (see Supervision=\xmark\ in Table~\ref{tab:modern-networks}). Surprisingly, unsupervised pruning is not significantly worse than the supervised, and often yields competitive results (\emph{e.g}\onedot} \def\Eg{\emph{E.g}\onedot, ResNet110). Notably, previous pruning algorithms premise the existance of supervision as a priori. Being the first demonstration of unsupervised pruning, along with the signal propagation perspective, one could find it useful to apply this unsupervised pruning strategy to scenarios where it lacks labels or is only provided with weak supervision. \subsection{Neural architecture sculpting} \begin{wrapfigure}{R}{0.4\textwidth} \vspace{-4mm} \centering \includegraphics[width=0.38\textwidth, trim=8mm 10mm 8mm 9mm, clip]{figure/architecture-sculpting/result.eps} \vspace{-1mm} \caption{ Neural architecture sculpting. While all have the same number of parameters, sparse networks outperform the referece dense network. Errors on CIFAR-10 (average over $5$ runs). } \vspace{-3mm} \label{fig:nas} \end{wrapfigure} We have shown that the signal propagation perspective enables pruning of networks at initialization, even without supervision. This sparks curiosity of whether pruning needs to be limited to pre-shaped architectures. In other words, what if pruning starts with a bulky network and is treated as \emph{sculpting} an archiecture? To seek for an answer, we conduct the following experiments: we take a popular pre-designed architecture (ResNet20) as a base network, and consider a range of variants that are originally bigger than the base model, but pruned to have the same number of parameters as the base dense network. Specifically, we consider the following {\em equivalents}: {\bf (1)} the same number of residual blocks, but with larger widths; {\bf (2)} a reduced number of residual blocks with larger widths; {\bf (3)} a larger residual block and the same width. The results are presented in Figure~\ref{fig:nas}. Overall, the sparse equivalents record lower generalization errors than the dense base model. Notice that some models are pruned to extreme sparsity levels (\emph{e.g}\onedot} \def\Eg{\emph{E.g}\onedot, Equivalent 1 pruned for $\bar{\kappa}=98.4$\%). This result is well aligned with recent research findings in~\cite{kalchbrenner2018efficient}: large sparse networks outperform the small dense network counterpart, and with a dedicated implementation for sparsity, large sparse models can even enjoy a similar computational efficiency as the small dense model in practice. We further note that unlike previous works, the sparse networks are discovered by sculpting, without pretraining nor supervision. \section{Discussion} \vspace{-2mm} In this work, we have approached network pruning from a signal propagation perspective and formally characterized initialization conditions for a network to be pruned prior to training. Based on this, we found in our experiments that orthogonal initialization produced the best pruning results compared to other initialization schemes on various modern architectures. While pruning on orthogonal initialization empirically produces trainable sparse networks, it would be immensely beneficial if there is a way to guarantee that. We believe, our signal propagation perspective provides a means to formulate this as an optimization problem by maximizing the ``trainability'' of sparse networks (measured by the Jacobian singluar values) while pruning, and we intend to explore this direction as a future work. \SKIP{ In this work, we have approached pruning at initialization from a signal propagation perspective and formally characterized how one should initialize a network to prune prior to training. Based on this, we recommended orthogonal initialization which as shown in our experiments produced the best pruning results compared to other initialization schemes on various modern architectures. In fact, pruning on orthogonal initialization empirically produces trainable sparse networks, however, it would be immensely beneficial if there is a way to guarantee that. We believe, our signal propagation perspective provides a means to formulate this as an optimization problem by maximizing the ``trainability'' of sparse networks (measured by the Jacobian singluar values) while pruning, and we intend to explore this direction as a follow-up work. } \SKIP{ (summary, contribution, potential) (drawback and future work) we focused on ``pruning''; there is no guarantee that the pruned sparse networks will have dynamical isometry; however, ultimately it could be combined with ``pruning'' and ``training''; as a future work, prune such that it preserves dynamical isometry; In this work, we have approached pruning at initialization from a signal propagation perspective and theoretically characterized how one should initialize a network to prune prior to training. From this, we recommended orthogonal initialization which as shown in our experiments outperformed other initialization schemes on various modern architectures. Note that, orthogonal initialization only ensures well-conditioned Jacobians and consequently faithful saliency criterion (\gls{CS}) for pruning, however, the resulting sparse networks after pruning are not guaranteed to have well-conditioned Jacobians and/or being trainable. In fact, as evidenced by our experiments orthogonally initialized \acrshort{SNIP} yields trainable sparse networks, it would be solid if there is a way to guarantee trainable sparse networks given an initialization. We beileve, our signal propagation perspective provides the means to formulate this as an optimization by maximizing the ``trainability'' of sparse networks (measured by the Jacobian singluar values) while pruning and we intend to explore this direction as a follow-up work. \AJ{very preliminary} } \section{Probing into the effect of initialization on pruning}\label{sec:init} \vspace{-1ex} In this section, we provide an empirical analysis on the effect of initialization for pruning untrained random neural networks. To this end, our aim is to provide grounds for the signal propagation perspective to pruning random networks, which we will formalize in the next section. \vspace{-1ex} \subsection{Problem setup}\label{sec:prob} Consider a fully-connected, feed-forward neural network with weight matrices ${{\mathbf{W}}^l\in\mathbb{R}^{N\times N}}$, biases ${\mathbf{b}}^l\in\mathbb{R}^{N}$, pre-activations ${\mathbf{h}}^l\in\mathbb{R}^{N}$, and post-activations ${\mathbf{x}}^l\in\mathbb{R}^{N}$, for $l \in \{1\ldots K\}$ up to $K$ layers. Now, the feed-forward dynamics of a network can be written as, \begin{equation}\label{eq:forward} {\mathbf{x}}^l = \phi({\mathbf{h}}^l)\ ,\qquad {\mathbf{h}}^l = {\mathbf{W}}^l{\mathbf{x}}^{l-1} + {\mathbf{b}}^l\ , \end{equation} where $\phi: \mathbb{R} \to\mathbb{R}$ is an elementwise nonlinearity, and the input is denoted by ${\mathbf{x}}^0$. Given the network configuration, the parameters are initialized by sampling from a probability distribution, typically a zero mean Gaussian with a layerwise variance scaling (\emph{e.g}\onedot} \def\Eg{\emph{E.g}\onedot,~\cite{glorot2010understanding,he2015delving,LeCun1998fficient}) for enhanced trainability. As noted in~\citet{lee2018snip}, a variance scaling initialization scheme tends to improve pruning results. In essence, a variance scaling initialization scheme re-scales the standard deviation of the distribution from $\sigma \rightarrow \frac{\alpha}{\psi_l}\sigma$, where $\alpha$ is a global amplifier and $\psi_l$ a layerwise attenuator that depends on a predefined architecture specification (\emph{e.g}\onedot} \def\Eg{\emph{E.g}\onedot, fan-in). Notice that in case of a network with layers of the same width, the variance can be controlled by a single scalar $\gamma=\frac{\alpha}{\psi}$ as $\psi_l = \psi$ for all layers $l$. Since \gls{CS} is computed at initialization, we wish to understand the role of initial weights for pruning. In particular, we will look into the effect of varying initialization on linear and tanh MLP networks of layers $K\in\{3, 5, 7\}$ and $N=100$ on MNIST with $\sigma=1$ as the default, similar to~\cite{saxe2013exact}. \vspace{-1ex} \subsection{Observations} Our interest is to see the effect of different initialization (\emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, sampling distribution controlled by $\gamma$) on the pruning results. Precisely, we initialize a network with different $\gamma$, compute \gls{CS}, prune the network, and train~\footnote{ In order to focus on the effect of initialization purely on pruning, for this experiment only, we re-initialize pruned networks using~\cite{glorot2010understanding} before training. This way, potential influence from different initial weights to training and thereby generalization errors are controlled, while the subnetworks are well-initialized for stable training. }. We first present the generalization errors in Table~\ref{tab:error-by-gamma}. Note, even though the training policy is the same and reliable across all experiments, depending on $\gamma$, the results can vary critically (\emph{e.g}\onedot} \def\Eg{\emph{E.g}\onedot, the failure case of tanh network; $K=7$, $\gamma=1.0$). This indicates that a different sampling distribution results in a different subnetwork structure or topology as a result of pruning \SKIP{ As noted in~\cite{lee2018snip}, a variance scaling initialization scheme results in reliable \gls{CS} and in turn high quality pruned networks. In essence, a variance scaling initialization scheme re-scales the standard deviation of the distribution from $\sigma \rightarrow \frac{\alpha}{\psi_l}\sigma$, where $\alpha$ is a global amplifier and $\psi_l$ a layerwise attenuator that depends on a predefined architecture specification (\emph{e.g}\onedot} \def\Eg{\emph{E.g}\onedot, fan-in). Notice that in case of a network with layers of the same width, the variance can be controlled by a single scalar $\gamma=\frac{\alpha}{\psi}$ as $\psi_l = \psi$ for all layers $l$. Our idea is to vary the scalar $\gamma$ and observe the effect of it on \gls{CS} and the generalization errors of the resulting pruned networks. Precisely, we initialize a network with different $\gamma$, compute \gls{CS}, and prune the networks. Note that, to focus on the effect of initialization purely on pruning, for this experiment only, we re-initialize pruned networks using a variance scaling initialization scheme~\cite{glorot2010understanding}, before training. This way, potential influence from different initial weights to training and thereby generalization errors are controlled, while the subnetworks are well-initialized for stable training. To consolidate our experimental choice, we show the effect of re-initialization at the end of this section. \AJ{I felt this way is a bit more logical, you can revert it back if you don't like it} } \SKIP{ ~\footnote At this stage, the remaining weights in pruned subnetworks are still of samples from different distributions. In order to focus on the effect of initialization purely on pruning, for this experiment only, we re-initialize pruned networks using a variance scaling initialization scheme~\cite{glorot2010understanding}, before training. This way, potential influence from different initial weights to training and thereby generalization errors are controlled, while the subnetworks are well-initialized for stable training. }. } \SKIP{ Then, the pruned networks are trained the same standard way and the results are displayed in Table~\ref{tab:error-by-gamma}. Note, even though the training policy is the same and reliable across all experiments, depending on $\gamma$, the results often vary critically. This indicates that a different sampling distribution results in a different subnetwork structure or topology as a result of pruning, for which training outcomes can vary significantly. } To further investigate, we visualize the resulting pruning patterns ${\mathbf{c}}$ of each layer as well as the corresponding \gls{CS} used for pruning in Figure~\ref{fig:sparsification-pattern}. It is seen in the sparsity patterns that for the tanh case, unlike the linear case, more number of parameters tend to be pruned in the later layers than the earlier layers. This becomes critical to learning when a high sparsity level is requested; \emph{e.g}\onedot} \def\Eg{\emph{E.g}\onedot, for $\bar{\kappa}=90$\%, only a few parameters in later layers are retained after pruning, severely limiting the learning capability of the subnetwork. This is explained by the \gls{CS} plot. The sensitivity of parameters in the tanh network tends to decrease towards the later layers, and therefore, by choosing the top-$\kappa$ parameters globally based on \gls{CS} scores, it will result in a subnetwork in which retained parameters are distributed highly non-uniformly and sparsely throughout the network. We posit that this unreliability of \gls{CS} is due to the poor signal propagation: an initialization that leads the forward signal to explode (by a large $\gamma$) will saturate the backward signal, \emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, gradients, and since \gls{CS} is directly related to the gradients, such initialization will result in unreliable \gls{CS}, and thereby poor pruning results, even completely disconnecting the inputs and outptus. Note that while it becomes worse for tanh networks as the depth $K$ increases, this is not the case for linear networks because a linear network can be essentially represented as a single layer network regardless of the depth. In the following section, we formalize this signal propagation perspective and recommend an initialization that would ensure \gls{CS} to be reliable. \SKIP{ We posit that this unreliability of \gls{CS} is due to the poor signal propagation: the forward signal is not faithfully propagated through the network, resulting in unreliable backward signal (\emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, \gls{CS}). Specifically, for tanh networks, as initialization with larger $\gamma$ results in larger weights, the resulting pre-activations are saturated by the nonlinearity. Therefore, when measuring \gls{CS} (or gradients), small changes in weights would not be accurately reflected in the output activations, yielding unreliable \gls{CS}. \AJ{Your previous CS plot with different $\gamma$ is clearly showing this effect, I think.} This saturation effect is amplified with increasing depth, leading to imbalanced sparsity structures. Note that, this is not the case for linear networks and in fact, a linear network can be essentially represented as a single layer network regardless of the depth. In the following section, we formalize this signal propagation perspective and recommend an initialization that would ensure that the computed \gls{CS} is reliable. } \SKIP{ -- Namhoon's version We posit that this is due to the poor signal propagation: an initialization that leads the forward signal to either vanish or explode will saturate the backward signal, \emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, gradients, and since \gls{CS} is directly related to the gradients, the initial signal propagation can directly affect the pruning results. Note that this will not be the case for linear networks because the signal propagating through a linear network can be essentially represented as a signal through single layer network regardless of the depth, preventing saturating gradients. } \SKIP{ Let us begin with an untrained, fully-connected, feed-forward neural network of depth $L$ with layer width $N_l$ and some nonlinearity $\phi: \mathbb{R} \rightarrow \mathbb{R}$. Given such configuration, the network parameters are to be sampled from a normal distribution $\mathcal{N}(\mu, \sigma^{2})$, or a variance scaling version (\emph{e.g}\onedot} \def\Eg{\emph{E.g}\onedot, \cite{LeCun1998fficient,glorot2010understanding,he2015delving}) to enhance the trainability. A variance scaling initialization scheme can also be used to improve pruning as noted in~\cite{lee2018snip}, however, without being provided with any analysis, it remains unclear as to how such initialization can help the process of pruning untrained neural networks. In essence, a variance scaling initialization scheme re-scales the standard deviation of the sampling distribution from $\sigma \rightarrow \frac{\alpha}{\psi_l}\sigma$, where $\alpha$ is a global amplifier and $\psi_l$ a layer-wise attenuator that depends on a pre-defined architecture specification (\emph{e.g}\onedot} \def\Eg{\emph{E.g}\onedot, fan-in). Notice that in case of a network with layers of the same width, \emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, $N_l=N$ for all $l$, the sample variance can be controlled with a single scalar $\gamma=\frac{\alpha}{\psi_l}$. We first look into the effect of varying $\gamma$ for generalization errors. We initialize a network with different $\gamma$, compute the connection sensitivities, and prune the networks~\footnote{\scriptsize At this stage, the remaining weights in pruned subnetworks are still of samples from different distributions. In order to focus on the effect of initialization purely on pruning, for this experiment only, we re-initialize pruned networks using a variance scaling initialization scheme~\cite{glorot2010understanding}, before training. This way, potential influence from different initial weights to training and thereby generalization errors are controlled, while the subnetworks are well-initialized for stable training. }. The pruned subnetworks are trained the same standard way. The results are displayed in Table~\ref{tab:error-by-gamma}. Note, that even though the training policy is the same and reliable across all experiments, depending on $\gamma$, the results vary often critically. This indicates that a different sampling distribution results in a different subnetwork structure or topology as a result of pruning, for which training outcomes can vary significantly. To further investigate, we visualize the resulting pruning patterns ${\mathbf{c}}$ in each layer as well as the corresponding connection sensitivity ${\mathbf{s}}$ used for pruning in Figure~\ref{fig:sparsification-pattern}. It is seen in the sparsity patterns that for the tanh case, unlike the linear case, a more number of parameters tend to be pruned in the later layers than the earlier layers. This becomes critical when a high sparsity level is requested; for example, with $\bar{\kappa}=90$, only a few parameters in later layers are retained after pruning, severely limiting the learning capability of the subnetwork. This is explained by the connection sensitivity plot. The sensitivity of parameters in the tanh network tends to decrease towards the later layers, and therefore, by choosing the top $\kappa$ parameters globally based on sensitivity scores, it will result in a subnetwork in which parameters are retained highly non-uniformly and decreasingly throughout the network. We posit that this is due to the poor signal propagation flow: an initialization that leads the forward signal to either vanish or explode will saturate the backward signal, \emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, gradients, and since the connection sensitivity is directly related to the gradients, the initial signal propagation can directly affect the pruning results. Note that this will not be the case for linear networks because the signal propagating through a linear network can be essentially represented as a signal through single layer network regardless of the depth, preventing saturating gradients. Next, we also carry out experiments to check the effect of re-initialization. We first prune a dense network, and before we start training the pruned, we re-initialize it with the same initialization method used at the pruning step. This makes the weights be of the same random distribution as ones used for pruning, but different samples. The results are presented in Table~\ref{tab:effect-reinit}. In all cases, we find no difference introduced by re-initialization. This should be expected under the pruning-at-initialization regime, since the initail weights on the pruned network are anyway untrained random. However, this is non-trivial since it means that it is not the particular samples that are important for pruning; rather, it is the distribution that matters. Our finding is consistent with recent research results in~\cite{liu2018rethinking} where they showed that fine-tuning the pruned model with inherited weights does not improve over training it from scratch and that the resulting pruned architectures are more likely to be what brings the benefit. The same was observed with large scale experiments in~\cite{gale2019state}. Note that unlike the aforementioned works, however, the sparse topology was found from a purely untrained network rather than more or less pretrained network, reinforcing results on the pure effect of re-initialization. } \begin{table}[t!] \centering \scriptsize \caption{ Effect of initialization on generalization errors of pruned networks. Linear and tanh MLP networks of different depths $K$ are initialized with varying $\gamma\in\{10^{-4}, .., 10^{1}\}$, pruned for the sparsity level $\bar{\kappa}=90\%$, and trained the same standard way. While tanh networks achieve lower generalization errors than linear ones in general (due to their ability to learn a non-linear function, unsurprisingly), there are critical \underline{failure cases} for some tanh cases, indicating that the topology of subnetworks after pruning can vary significantly depending on the initialization before pruning. } \begin{tabular}{c c cccccc c cccccc} \toprule \vspace{1mm} & & \multicolumn{6}{c}{\textbf{linear}} & & \multicolumn{6}{c}{\textbf{tanh}} \\ \textbf{K} & & $10^{-4}$ &$10^{-3}$ & $10^{-2}$ & $10^{-1}$ & $10^{0}$ & $10^{1}$ & & $10^{-4}$ &$10^{-3}$ & $10^{-2}$ & $10^{-1}$ & $10^{0}$ & $10^{1}$ \\ \midrule $3$ & & $7.99$ & $8.00$ & $7.72$ & $7.69$ & $7.69$ & $7.69$ & & $2.54$ & $2.50$ & $2.52$ & $2.50$ & $2.57$ & $2.59$ \\ $5$ & & $8.21$ & $8.15$ & $8.06$ & $8.02$ & $8.01$ & $8.01$ & & $2.55$ & $2.53$ & $2.53$ & $2.51$ & $2.45$ & $\underline{90.2}$ \\ $7$ & & $8.30$ & $8.27$ & $8.37$ & $8.44$ & $8.43$ & $8.44$ & & $2.66$ & $2.70$ & $2.67$ & $2.61$ & $\underline{90.2}$ & $\underline{90.2}$ \\ \bottomrule \end{tabular} \label{tab:error-by-gamma} \vspace{-1ex} \end{table} \begin{figure}[t!] \captionsetup[subfigure]{labelformat=empty} \centering \footnotesize \setlength{\tabcolsep}{0.3pt} \renewcommand{\arraystretch}{0.3} \begin{subfigure}{.46\textwidth} \begin{tabular}{c ccccc c ccccc} $\bar{\kappa}$ & \multicolumn{5}{c}{linear ($K$=$7$)} & & \multicolumn{5}{c}{tanh ($K$=$7$)} \\ {} \\ \raisebox{1.7mm}{10\ } & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-linear/normal_custom-1.0/{ts-0.1_layer-w2}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-linear/normal_custom-1.0/{ts-0.1_layer-w3}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-linear/normal_custom-1.0/{ts-0.1_layer-w4}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-linear/normal_custom-1.0/{ts-0.1_layer-w5}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-linear/normal_custom-1.0/{ts-0.1_layer-w6}.eps} & {\enspace} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-tanh/normal_custom-1.0/{ts-0.1_layer-w2}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-tanh/normal_custom-1.0/{ts-0.1_layer-w3}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-tanh/normal_custom-1.0/{ts-0.1_layer-w4}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-tanh/normal_custom-1.0/{ts-0.1_layer-w5}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-tanh/normal_custom-1.0/{ts-0.1_layer-w6}.eps} \\ \raisebox{1.7mm}{30\ } & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-linear/normal_custom-1.0/{ts-0.3_layer-w2}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-linear/normal_custom-1.0/{ts-0.3_layer-w3}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-linear/normal_custom-1.0/{ts-0.3_layer-w4}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-linear/normal_custom-1.0/{ts-0.3_layer-w5}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-linear/normal_custom-1.0/{ts-0.3_layer-w6}.eps} & {\enspace} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-tanh/normal_custom-1.0/{ts-0.3_layer-w2}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-tanh/normal_custom-1.0/{ts-0.3_layer-w3}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-tanh/normal_custom-1.0/{ts-0.3_layer-w4}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-tanh/normal_custom-1.0/{ts-0.3_layer-w5}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-tanh/normal_custom-1.0/{ts-0.3_layer-w6}.eps} \\ \raisebox{1.7mm}{50\ } & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-linear/normal_custom-1.0/{ts-0.5_layer-w2}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-linear/normal_custom-1.0/{ts-0.5_layer-w3}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-linear/normal_custom-1.0/{ts-0.5_layer-w4}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-linear/normal_custom-1.0/{ts-0.5_layer-w5}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-linear/normal_custom-1.0/{ts-0.5_layer-w6}.eps} & {\enspace} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-tanh/normal_custom-1.0/{ts-0.5_layer-w2}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-tanh/normal_custom-1.0/{ts-0.5_layer-w3}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-tanh/normal_custom-1.0/{ts-0.5_layer-w4}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-tanh/normal_custom-1.0/{ts-0.5_layer-w5}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-tanh/normal_custom-1.0/{ts-0.5_layer-w6}.eps} \\ \raisebox{1.7mm}{70\ } & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-linear/normal_custom-1.0/{ts-0.7_layer-w2}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-linear/normal_custom-1.0/{ts-0.7_layer-w3}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-linear/normal_custom-1.0/{ts-0.7_layer-w4}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-linear/normal_custom-1.0/{ts-0.7_layer-w5}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-linear/normal_custom-1.0/{ts-0.7_layer-w6}.eps} & {\enspace} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-tanh/normal_custom-1.0/{ts-0.7_layer-w2}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-tanh/normal_custom-1.0/{ts-0.7_layer-w3}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-tanh/normal_custom-1.0/{ts-0.7_layer-w4}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-tanh/normal_custom-1.0/{ts-0.7_layer-w5}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-tanh/normal_custom-1.0/{ts-0.7_layer-w6}.eps} \\ \raisebox{1.7mm}{90\ } & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-linear/normal_custom-1.0/{ts-0.9_layer-w2}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-linear/normal_custom-1.0/{ts-0.9_layer-w3}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-linear/normal_custom-1.0/{ts-0.9_layer-w4}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-linear/normal_custom-1.0/{ts-0.9_layer-w5}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-linear/normal_custom-1.0/{ts-0.9_layer-w6}.eps} & {\enspace} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-tanh/normal_custom-1.0/{ts-0.9_layer-w2}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-tanh/normal_custom-1.0/{ts-0.9_layer-w3}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-tanh/normal_custom-1.0/{ts-0.9_layer-w4}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-tanh/normal_custom-1.0/{ts-0.9_layer-w5}.eps} & \includegraphics[height=5.5mm]{figure/sparse-mask-vis/mlp-7-100-tanh/normal_custom-1.0/{ts-0.9_layer-w6}.eps} \\ {\ } \\ & l2 & l3 & l4 & l5 & l6 & & l2 & l3 & l4 & l5 & l6 \\ \end{tabular} \end{subfigure} \begin{subfigure}{.26\textwidth} \caption{\quad linear ($K$=$7$)} \vspace{-2mm} \includegraphics[width=1.0\textwidth]{figure/cs-distribution/cs-raw-n1000-linear.eps} \end{subfigure} \begin{subfigure}{.26\textwidth} \caption{\quad tanh ($K$=$7$)} \vspace{-2mm} \includegraphics[width=1.0\textwidth]{figure/cs-distribution/cs-raw-n1000-tanh.eps} \end{subfigure} \caption{ (left) Pruning patterns $c \in \{0,1\}^{100\times100}$ of each layer: black($0$)/white($1$) pixels refer to pruned/retained parameters; (right) connection sensitivities measured for the parameters in each layer. Networks are initialized with $\gamma=1.0$. Unlike the linear case, the sparsity pattern for the tanh network is non-uniform over different layers. This becomes critical when pruning for a high sparsity level; for example, there are only a few parameters retained in later layers for $\bar{\kappa}=90$\%, which leads to poor learning capability and accounts for critical failure cases observed in Table~\ref{tab:error-by-gamma}. This is explained by the connection sensitivity plot. For tanh networks, parameters in later layers tend to have lower connection sensitivities compared to parameters in earlier layers. } \label{fig:sparsification-pattern} \vspace{-3ex} \end{figure}
{'timestamp': '2019-06-17T02:17:59', 'yymm': '1906', 'arxiv_id': '1906.06307', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06307'}
arxiv
\section{Introduction} Training deep neural networks usually requires a large pool of labeled data, yet obtaining large datasets for tasks such as image classification remains a fundamental challenge. Although there has been explosive progress in the production of vast quantities of high resolution images, large collections of labeled data required for supervised learning remain scarce. Especially in domains such as medical imaging, datasets are limited in size due to privacy issues, and manual annotation by medical experts is expensive, time-consuming, and prone to subjectivity, human error, and variance across different experts. Even when large labeled datasets become available, they are often highly imbalanced and nonuniformly distributed. For instance, in an imbalanced medical dataset there will be an over-representation of common medical problems and an under-representation of rare conditions. Such biases make the training of neural networks across multiple classes with similar effectiveness very challenging. The small-training-data problem is traditionally mitigated through simplistic and cumbersome data augmentation, often by creating new training examples through translation, rotation, flipping, etc. The missing or mismatched label problem can be addressed by evaluating similarity measures over the training examples. This is not always robust and the efficiency largely depends on the performance of the similarity measuring algorithms. \begin{figure} \centering \subcaptionbox{}{\includegraphics[width=0.3\linewidth,height=0.3\linewidth]{gan_fake}} \hfill \subcaptionbox{}{\includegraphics[width=0.3\linewidth,height=0.3\linewidth]{vae_blurry}} \hfill \subcaptionbox{}{\includegraphics[width=0.3\linewidth,height=0.3\linewidth,trim={0 0 0 1.5},clip]{svhn_collapse}} \caption{Synthetic images generated from CIFAR-10: (a) Relatively good generation by a GAN. (b) Blurry images generated by a VAE. From SVHN: (c) mode collapsed generation by a GAN.} \label{fig:gan_collapse} \end{figure} Generative models, such as VAEs \citep{kingma2013auto} and GANs \citep{goodfellow2014generative}, have recently become popular because of their ability to learn underlying data distributions from training samples. This has made generative models more practical in ever-frequent scenarios where there is an abundance of unlabeled data. With minimal annotation, an efficient semi-supervised learning model could be a go-to approach. More specifically, based on small quantities of annotation, generative models could be utilized to learn real-data distributions and synthesize realistic new training images. Both VAEs and GANs can be employed for this purpose. VAEs can learn the dimensionality-reduced representation of training data and, with an explicit density estimation, can generate new samples. However VAE-generated samples are usually blurry (Fig.~\ref{fig:gan_collapse}b). On the other hand, despite the successes in generating images and semi-supervised classifications, GAN frameworks are still very difficult to train and there are challenges in using GAN models, such as non-convergence due to unstable training, mode collapsed image generation (Fig.~\ref{fig:gan_collapse}c), diminished gradient, overfitting, and high sensitivity to hyper-parameters. To stabilize GAN training and combat mode collapse, several variants have been proposed. \citet{nguyen2017dual} proposed a model, where a single generator is used alongside dual discriminators. \citet{durugkar2016generative} proposed a model with a single generator and feedback aggregated over several discriminators considering either the average loss of all discriminators or by picking only the discriminator with the maximum loss in relation to the generator's output. \citet{neyshabur2017stabilizing} proposed a framework where a single generator simultaneously trains against an array of discriminators, each of which operates on a different low-dimensional projection of the data. \citet{mordido2018dropout}, arguing that all the previous approaches restrict the discriminator's architecture, which compromises the extensibility of the framework, instead proposed a Dropout-GAN, where a single generator is trained against a dynamically changing ensemble of discriminators. However, there could be a risk of dropping out all the discriminators. Feature matching and minibatch discrimination techniques have been proposed \citep{salimans2016improvedT} for eliminating mode collapsing and preventing overfitting in GAN training. Although there have been wide ranging efforts in high quality image generation with GANs and VAEs, accuracy and image quality are usually not ensured in the same model, especially in multi-class image classification. To tackle this issue, we propose a novel method that can learn joint image generation and multi-class image classification. Our specific contribution is the Multi-Adversarial Variational autoEncoder Network, or MAVEN, a novel multi-class image classification model incorporating an ensemble of discriminators in a combined VAE-GAN network. An ensemble layer combines the feedback from multiple discriminators at the end of each batch. With the inclusion of ensemble learning at the end of a VAE-GAN, both generated image quality and classification accuracy are improved simultaneously. We also introduce a simplified version of the Descriptive Distribution Distance (DDD) measure for evaluating any generative model, which better represents the distribution of the generated data and quantifies its closeness to the real data. Our experimental results on a number of different datasets in both the computer vision and medical imaging domains indicate that our MAVEN model improves upon the joint image generation and classification performance of a GAN and a VAE-GAN with the same set of hyper-parameters. \section{Related Work} Generative modeling has attracted much attention in the computer vision and medical imaging research communities. In particular, realistic image generation greatly helps address many problems involving the scarcity of labeled data. GANs and their variants have been applied in different architectures in continuing efforts to improve the accuracy and effectiveness of image classification. The GAN framework has been utilized in numerous works as a more generic approach to generating realistic training images that synthetically augment datasets in order to combat overfitting; e.g., for synthetic data augmentation in liver lesions \citep{frid2018gan}, retinal fundi \citep{guibas2017synthetic}, histopathology \citep{hou2017unsupervised}, and chest X-rays \citep{salehinejad2018generalization}. \citet{calimeri2017biomedical} employed a LAPGAN \citep{Denton2015DeepGI} and \citet{han2018gan} used a WGAN \citep{arjovsky2017wasserstein} to generate synthetic brain MR images. \citet{bermudez2018learning} used a DCGAN \citep{radford2015unsupervised} to generate 2D brain MR images followed by an autoencoder for image denoising. \citet{chuquicusma2018fool} utilized a DCGAN to generate lung nodules and then conducted a Turing test to evaluate the quality of the generated samples. GAN frameworks were also shown to improve accuracy of image classification via generation of new synthetic training images. \citet{frid2018gan} used a DCGAN and a ACGAN \citep{Odena2017Conditional} to generate images of three liver lesion classes to synthetically augment the limited dataset and improve the performance of CNN for liver lesion classification. Similarly, \citet{salehinejad2018generalization} employed a DCGAN to artificially simulate pathology across five classes of chest X-rays in order to augment the original imbalanced dataset and improve the performance of a CNN model in chest pathology classification. The GAN framework has also been utilized in semi-supervised learning architectures to help leverage the vast number of unlabeled data alongside limited labeled data. The following efforts demonstrate how incorporating unlabeled data in the GAN framework has led to significant improvements in the accuracy of image-level classification: \citet{madani2018semi} used an order of magnitude less labeled data with a DCGAN in semi-supervised learning and showed comparable performance to a traditional supervised CNN classifier. Furthermore, their study also demonstrated reduced domain over-fitting by simply supplying unlabeled test domain images. \citet{springenberg2015unsupervised} combined a WGAN and CatGAN \citep{wang2017catgan} for unsupervised and semi-supervised learning of feature representation of dermoscopy images. Despite these successes, GAN frameworks are very difficult to train, as was discussed in the previous section. Our work mitigates the limitations of training the GAN framework; it enables training on a limited number of labeled data, prevents overfitting to a specific data domain source, prevents mode collapse, and enables multi-class image classification. \section{MAVEN Architecture} \begin{figure} \centering \includegraphics[width=\linewidth]{maven_archs} \caption{Our MAVEN architecture compared to those of VAE, GAN, and VAE-GAN. In the MAVEN, inputs to $D$ can be real data $X$, generated data $\hat{X}$, or $\tilde{X}$. An ensemble ensures the combined feedback from the discriminators to the generator.} \label{fig:archs} \end{figure} Fig.~\ref{fig:archs} illustrates the preliminary models building up to our MAVEN architecture. The VAE is an explicit generative model that uses two neural nets---an encoder $E$ and decoder $D^\prime$. Network $E$ learns an efficient compression of the real data point $x$ into a lower dimensional latent representation space $z(x)$; i.e., $q_\lambda(z\vert x)$. With neural network likelihoods, computing the gradient becomes intractable. However via differentiable, non-centered re-parameterization, sampling is performed from an approximate function $q_{\lambda}(z\vert x) = N(z; \mu_{\lambda}, \sigma_{\lambda}^2)$, where $z = \mu_\lambda + \sigma_\lambda \odot \hat{\varepsilon}$ with $\hat{\varepsilon} \sim N(0, 1)$. Encoder $E$ results in $\mu$ and $\sigma$, and with the re-parameterization trick, $z$ is sampled from a Gaussian distribution. Then with $D^\prime$, new samples are generated or real data samples are reconstructed. So, $D^\prime$ provides parameters for the real data distribution; i.e., $p_\lambda(x\vert z)$. Later, a sample drawn from $p_\phi(x\vert z)$ may be used to reconstruct the real data by marginalizing out $z$. The GAN is an implicit generative model where a generator $G$ and a discriminator $D$ compete in a mini-max game over the training data to improve their performance. Generator $G$ tries to mimic the underlying distribution of the training data and generates fake samples while discriminator $D$ learns to discriminate fake generated samples from real samples. The GAN model is trained on the following objectives: \begin{align} \label{eqn:discriminator} \max_{D}V(D) &= E_{x\sim p_\text{data}(x)}[\log D(x)] + E_{x\sim p_g(z)}[\log(1 - D(G(z))];\\ \label{eqn:generator} \min_{G}V(G) &= E_{x \sim p_z(z)}[\log(1 - D(G(z))]. \end{align} $G$ takes a noise sample $z\sim p_g(z)$ and learns to map into image space as if they are coming from the original data distribution $p_\text{data}(x)$. The discriminator $D$ takes either real image data or fake image data as the input and provides feedback to the generator $G$, regarding whether the input to $D$ is real or fake. $D$ wants to maximize the likelihood for real samples and minimize the likelihood of generated samples. On the other hand, $G$ wants $D$ to maximize the likelihood of generated samples. A Nash equilibrium state is possible when $D$ can no longer distinguish real and generated samples meaning that the model distribution will be the same as the data distribution. \begin{figure} \centering \includegraphics[width=0.75\linewidth]{arch_EGD} \caption{The three convolutional neural networks, $E$, $G$, and $D$, in the MAVEN.} \label{fig:arch_details} \end{figure} \citet{makhzani2015adversarial} proposed the adversarial training of VAEs; i.e., VAE-GANs. Although they kept both $D^\prime$ and $G$, one can merge $D^\prime$ and $G$ since both can generate data samples from the noise samples of the representation $z$. In this case, $D$ either receives generated samples $\tilde{x}$ via $G$ or fake samples $\hat{x}$, and real data samples $x$. Although $G$ and $D$ compete against each other, at some point the feedback from $D$ becomes predictable for $G$ and it keeps generating samples from the same class. At that time, the generated samples lack variety. Fig.~\ref{fig:gan_collapse}c shows an example where all the generated images are of the same class. \citet{durugkar2016generative} proposed that using multiple discriminators in a GAN model helps improve performance, especially resolving the mode collapse issue. Moreover, a dynamic ensemble of multiple discriminators has recently been proposed, addressing the same issue \citep{mordido2018dropout}. In our MAVEN, the VAE-GAN combination is extended to have multiple discriminators aggregated in an ensemble layer. As in a VAE-GAN, the MAVEN has three components $E$, $G$, and $D$; all are convolutional neural networks with convolutional or transposed convolutional layers (Fig.~\ref{fig:arch_details}). $E$ takes real samples and generates a dimensionality-reduced representation $z(x)$. $G$ can take samples from noise distribution $z\sim p_g(z)$ or sampled noise $z(x)\sim q_\lambda(x)$, and it generates fake or completely new samples. $D$ takes inputs from distributions of real labeled data, real unlabeled data, and fake generated data. Fractionally strided convolutions are performed in $G$ to obtain the image dimension from the latent code. The goal of an autoencoder is to maximize the Evidence Lower Bound (ELBO). The intuition here is to show the network more real data. The more real data that it sees, the more evidence is available to it and, as a result, the ELBO can be maximized faster. $K$ discriminators are collected in an ensemble layer and the combined feedback \begin{equation} \label{eqn: mean_ensemble} V(D) = \frac{1}{K}\sum_{i=1}^K w_iD_i \end{equation} is passed to $G$. In order to randomize the feedback from multiple discriminators, a single discriminator is randomly selected. \begin{algorithm}[t] \caption{MAVEN Training procedure.\\ $m$ is the number of samples; $B$ is the minibatch-size; and $K$ is the number of discriminators.} \label{alg:MAVEN} \begin{algorithmic} \STATE $steps \leftarrow \frac{m}{B}$ \FOR{each {\bf epoch}} \FOR{each step in $steps$} \FOR{k = 1 to {\bf K}} \STATE Sample minibatch $z_i;{z^{(1)},\dots,z^{(m)}},z_i\sim p_g(z)$ \STATE Sample minibatch $x_i; {x^{(1)},\dots,x^{(m)}}, x_i\sim p_\text{data}(x)$ \STATE Update discriminator $D_k$ by ascending along its gradient: \begin{equation*} \nabla_{\theta_{D_k}} \frac{1}{m}\sum_{i=1}^m[\log D_k(x_i) + \log(1 - D_k(G(z_i)))] \end{equation*} \ENDFOR \STATE Sample minibatch $z_{k_i}, i=1,\dots, m, k=1,\dots, K, z_{k_i}\sim p_g(z)$ \IF{ensemble is `mean'} \STATE Assign weights $w_k$ for each of the discriminators $D_k$ \STATE Determine the mean discriminator $D_\mu$ of the discriminators $D_1,...,D_k$ \begin{equation*} D_\mu = \frac{1}{K}\sum_i^K w_iD_i \end{equation*} \ENDIF \STATE Update the generator $G$ by descending along its gradient from the ensemble of discriminator $D_{\mu}$: \begin{equation*} \nabla_{\theta_{G}} \frac{1}{m}\sum_{i=1}^m[\log(1 - D_{\mu}(G(z_i)))] \end{equation*} \STATE Sample minibatch $x_i; {x^{(1)},\dots,x^{(m)}}, x_i\sim p_\text{data}(x)$ \STATE Update encoder along its expectation function: \begin{equation*} \nabla_{\theta_{ E_{q_\lambda(z|x)}}} \left[\log \frac{p(z)}{q_\lambda (z|x)} \right] \end{equation*} \ENDFOR \ENDFOR \end{algorithmic} \end{algorithm} \section{Semi-Supervised Learning} The overall training procedure of the proposed MAVEN model is presented in Algorithm~\ref{alg:MAVEN}. In the forward pass, the real samples to $E$ and noise samples to $G$ are presented multiple times for the presence of multiple discriminators. In the backward pass, the combined feedback from the $D$s is determined and passed to $G$ and $E$. In the original image generator GAN, $D$ works as a binary classifier---it classifies the input image as real or synthetic. In order to facilitate the training for a $n$-class classifier, the role of $D$ is changed to an $(n+1)$-classifier. For multiple logit generation, the sigmoid function is replaced by a softmax function. Now, it can receive an image $x$ as input and outputs an $(n+1)$-dimensional vector of logits $\{{l}_1, {l}_2,\dots,{l}_{n+1}\}$. These logits are finally transformed into class probabilities for the final classification. Class ${(n+1)}$ is for the fake data and the remaining $n$ are for the multiple labels in the real data. The probability of $x$ being fake is \begin{equation} \label{eqn:fake_prob} p(y = n+1 | x) = \frac{\exp(l_{n+1})}{\sum_{j=1}^{n+1}\exp(l_j)}, \end{equation} and the probability that $x$ is real and belongs to class $i$ is \begin{equation} \label{eqn:real_prob} p(y= i|x, i< n+1) = \frac{\exp(l_i)}{\sum_{j=1}^{n+1}\exp(l_j)}. \end{equation} As a semi-supervised classifier, the model only takes labels for a small portion of training data. For the labeled data, it is then like supervised learning, while it learns in an unsupervised manner for the unlabeled data. The advantage comes from generating new samples. The model learns the classifier by generating samples from different classes. \subsection{Losses} Three networks $E$, $G$, and $D$ are trained on different objectives. $E$ is trained on maximizing the ELBO, $G$ is trained on generating realistic samples, and $D$ is trained to learn a classifier that classifies fake generated samples or particular classes for the real data samples. \paragraph{D Loss:} Since the model is trained on both labeled and unlabeled training data, the loss function of $D$ includes both supervised and unsupervised losses. When the model receives real labeled data, it is just the standard supervised learning loss \begin{equation} \label{eqn:supervised_loss} L_{D_\text{supervised}} = - \mathbb{E}_{\mathbf{x},y\sim p_\text{data}} \log[p(y = i|\mathbf{x}, i< n+1)]. \end{equation} When it receives unlabeled data from three different sources, the unsupervised loss contains the original GAN loss for real and fake data from two different sources: fake1 directly from $G$ and fake2 from $E$ via $G$. The three losses \begin{equation} \label{eqn:D_real} L_{D_\text{real}} = - \mathbb{E}_{x \sim p_\text{data}} \log [ 1 - p(y = n+1 | \mathbf{x})], \end{equation} \begin{equation} \label{eqn:D_fake} L_{D_\text{fake1}} = - \mathbb{E}_{\hat{x} \sim G} \log [p(y = n+1 | \hat{\mathbf{x}})], \end{equation} and \begin{equation} \label{eqn:D_recon} L_{D_\text{fake2}}=-\mathbb{E}_{\tilde{x} \sim G} \log [p(y = n+1 | \tilde{x})], \end{equation} are combined as the unsupervised loss in $D$: \begin{equation} \label{eqn:D_unsupervised} L_{D_\text{unsupervised}} = L_{D_\text{real}} + L_{D_\text{fake1}} + L_{D_\text{fake2}}. \end{equation} \paragraph{G Loss:} For $G$, the feature loss is used along with the original GAN loss. Activation $f(x)$ from an intermediate layer of $D$ is used to match the feature between real and fake samples. Feature matching has shown a lot of potential in semi-supervised learning \citep{salimans2016improvedT}. The goal of feature matching is to push the generator to generate data that matches real data statistics. The discriminator specifies those statistics; it is natural that $D$ can find the most discriminative features in real data against data generated by the model: \begin{equation} \label{eqn:G_feature} L_{G_\text{feature}} = || \mathbb{E}_{x \sim p_\text{data}} f(x) - \mathbb{E}_{\hat{x} \sim G}f(\hat{x}) ||^2_2. \end{equation} The total $G$ loss becomes the combined feature loss and $G$ costs maximizing the log-probability of $D$ making a mistake for generated data (fake1/fake2). Therefore, the $G$ loss \begin{equation} \label{eqn:G_loss} L_G = L_{G_\text{feature}} + L_{G_\text{fake1}} + L_{G_\text{fake2}}. \end{equation} is the combination of three losses, (\ref{eqn:G_feature}), \begin{equation} \label{eqn:G_fake} L_{G_\text{fake1}} = - \mathbb{E}_{\hat{x} \sim G} \log [ 1 - p(y = n+1 | \hat{x})], \end{equation} and \begin{equation} \label{eqn:G_recon} L_{G_\text{fake2}} = - \mathbb{E}_{\tilde{\mathbf{x}} \sim G} \log [ 1 - p(y = n+1 | \tilde{x}]. \end{equation} \paragraph{E Loss:} In the encoder $E$, the maximization of ELBO is equivalent to minimization of KL-divergence, allowing approximate posterior inferences. Therefore the loss function includes the KL-divergence and also a feature loss to match the features in the fake2 data with the real data distribution. The loss for the encoder is \begin{equation} \label{eqn:E_loss} L_E = L_{E_\text{KL}} + L_{E_\text{feature}}, \end{equation} where \begin{equation} L_{E_\text{KL}} = -KL [q_{\lambda}(z|x)|| p(z)] = \mathbb{E}_{q_\lambda(z|x)} \left[\log \frac{p(z)}{q_\lambda (z|x)} \right] \approx \mathbb{E}_{q_\lambda(z|x)} \end{equation} and \begin{equation} L_{E_\text{feature}} = || \mathbb{E}_{x \sim p_\text{data}} f(x) - \mathbb{E}_{\tilde{x} \sim G}f(\tilde{x}) ||^2_2. \end{equation} \section{Experiments and Results} \subsection{Data} We used three datasets to evaluate our MAVEN model for image generation and automatic image classification from 2D images in a semi-supervised learning scheme, and we constrained the experiments to limited labeled training data, considering that a large portion of annotation is missing; specifically: \begin{enumerate} \item The Street View House Numbers (SVHN) dataset \citep{netzer2011reading}. There are 73,257 digit images for training and 26,032 digit images for testing in the SVHN dataset. Out of two versions of the images, we used the version which has MNIST-like $32\times32$ pixel images centered around a single character, in RGB channels. Each of the training and test images are labeled as one of the ten digits (0--9). \item The CIFAR-10 dataset \citep{krizhevsky2009learning}, which consists of 60,000 $32\times32$ pixel color images in 10 classes. There are 50,000 training images and 10,000 test images in the CIFAR-10 dataset. This is a 10-class classification with classes airplane, automobile, bird, cat, deer, dog, frog, horse, ship, and truck. \item The anterior-posterior Chest X-Ray (CXR) dataset \citep{kermany2018identifying} for the classification of pneumonia and normal images. We performed 3-class classification: normal, bacterial pneumonia, and virus pneumonia. The dataset contains 5,216 training and 624 test images. \end{enumerate} \subsection{Implementation Details} To compare the image generation and multi-class classification performance of our MAVEN model, we used two baselines: DC-GAN and VAE-GAN. The same generator and discriminator architectures were used for DC-GAN and MAVEN models and the same encoder was used for the VAE-GAN and MAVEN models. For our MAVENs, we experimented with 2, 3, and 5 discriminators. In addition to using the proposed mean feedback of the multiple discriminators, we also experimented with feedback from a randomly selected discriminator. All the models were implemented in TensorFlow and run on a single Nvidia Titan GTX (12GB) GPU. For the CXR dataset, the images were normalized and resized to $128\times128$ pixels before passing them to the models, while for the SVHN and CIFAR-10 datasets, the normalized images were passed to the models in their original $(32\times32\times3)$ pixel sizes. For the discriminator, after every convolutional layer, a dropout layer was added with a dropout rate of 0.4. For all the models, we consistently used the Adam optimizer with a learning rate of $2e-4$ for $G$ and $D$, and $1e-5$ for $E$ with a momentum of 0.5. All the convolutional layers were followed by batch normalizations. Leaky ReLU activations were used with $\alpha = 0.2$. For all the experiments, only 10\% training data were used along with the corresponding labels. The classification performance was measured with cross-validation and average scores were reported after running each model 10 times. \subsection{Evaluation} \paragraph{Image Generation Performance:} There are no perfect performance metrics for the unsupervised learning in measuring the quality of generated samples. However, to assess the quality of the generated images, we employed the widely used Fr\'echet Inception Distance (FID) \citep{heusel2017gans} and a simplified version of the Descriptive Distribution Distance (DDD) \citep{imran2017optimization}. To measure the Fr\'echet distance between two multivariate Gaussians, the generated samples and real data samples are compared through their distribution statistics: \begin{equation} \label{eqn:fid} \text{FID} = ||\mu_\text{data} - \mu_\text{fake}||^2 + Tr(\Sigma_\text{data} + \Sigma_\text{fake} - 2\sqrt{\Sigma_\text{data}\Sigma_\text{fake}}). \end{equation} Two distribution samples are calculated from the 2048-dimensional activations of the pool3 layer of Inception-v3~\citep{salimans2016improvedT}. DDD measures the closeness of a synthetic data distribution to a real data distribution by comparing descriptive parameters from the two distributions. We propose a simplified version based on the first four moments of the distributions, computed as the weighted sum of normalized differences of moments, as follows: \begin{equation} \label{eqn:ddd} \text{DDD} = - \sum_{i=1}^{i=4} \log{w_i}|\mu_{\text{data}_i} - \mu_{\text{fake}_i}|. \end{equation} The higher-order moments are weighted more, as the stability of a distribution can be better represented by them. For both FID and DDD, lower scores are better. \paragraph{Image Classification Performance:} To evaluate model performance in classification, we used two measures: image-level classification accuracy and class-wise F1 scoring. The F1 score is \begin{equation} \label{eqn:f1-score} \text{F1} = \frac{2\times \text{precision} \times \text{recall}}{\text{precision} + \text{recall}}, \end{equation} with \begin{equation} \text{precision} = \frac{\text{TP}}{\text{TP} + \text{FP}} \textrm{\qquad and \qquad} \text{recall} = \frac{\text{TP}}{\text{TP} + \text{FN}}, \end{equation} where TP, FP, and FN are the number of true positives, false positives, and false negatives, respectively. \subsection{Results} \subsubsection{SVHN} For the SVHN dataset, we trained the network on $32\times32$ pixel images. From the training set, we randomly picked 7,326 labeled images and the remaining unlabeled images were passed to the network. All the models were trained for 150 epochs and then evaluated. We generated an equal number of new images as the training set size. Fig.~\ref{fig:svhn_images} presents a qualitative comparison of the generated digit images from the DC-GAN, VAE-GAN, and ALEAN models relative to the real training images, suggesting that our MAVEN-generated images are more realistic. This was further confirmed by the FID and DDD scoring. FID and DDD measurement was performed by drawing 10,000 samples from the generated images and 10,000 samples from the real training images. The generated image quality measurement was performed for eight different models, and the resultant FID and DDD scores are reported in Table~\ref{table:fid-ddd}. For FID score calculation, the FID score is reported after running the pre-trained Inception-v3 network for 20 epochs for each model. Per the scores, the MAVEN-rand model with 3 discriminators achieved the best FID and the best DDD was achieved for the MAVEN-mean model with 5 discriminators. For the semi-supervised classification, both image-level accuracy and class-wise F1 scores were calculated. Table~\ref{table:svhn-accuracy} compares the classification performance of all the models for the SVHN dataset. The MAVEN model consistently outperformed the DC-GAN and VAE-GAN classifiers both in classification accuracy and class-wise F1 scores. Among all the models, our MAVEN-mean model with 2 and 3 discriminators were found to be the most accurate. \begin{table}[t] \setlength{\tabcolsep}{4pt} \centering \caption{Minimum FID and DDD scores achieved by the DC-GAN, VAE-GAN, and MAVEN models for the CIFAR-10, SVHN, and CXR datasets.} \label{table:fid-ddd} \medskip \resizebox{\linewidth}{!}{ \begin{tabular}{|c|c|c?c|c|c?c|c|c|} \hline \multicolumn{3}{|c?}{CIFAR-10} & \multicolumn{3}{|c?}{SVHN} & \multicolumn{3}{|c|}{CXR} \\ \hline Model & FID & DDD & Model & FID & DDD & Model & FID & DDD\\ \cline{1-3} \hline DC-GAN & 61.293$\pm$0.209 & 0.265 & DC-GAN & 16.789$\pm$0.303 & 0.343 & DC-GAN & 152.511$\pm$0.370 & 0.145 \\ VAE-GAN & 15.511$\pm$0.125 & 0.224 & VAE-GAN & 13.252$\pm$0.001 & 0.329 & VAE-GAN & 141.422$\pm$0.580 & 0.107 \\ MAVEN-mean2D & 12.743$\pm$0.242 & 0.223 & MAVEN-mean2D & 11.675$\pm$0.001 & 0.309 & MAVEN-mean2D & 141.339$\pm$0.420 & 0.138\\ MAVEN-mean3D & \textbf{11.316$\pm$0.808} & \textbf{0.190} & MAVEN-mean3D & 11.515$\pm$0.065 & 0.300 & MAVEN-mean3D & \textbf{140.865$\pm$0.983} &\textbf{0.018}\\ MAVEN-mean5D & 12.123$\pm$0.140 & 0.207 & MAVEN-mean5D & 10.909$\pm$0.001 & \textbf{0.294} & MAVEN-mean5D & 147.316$\pm$1.169 & 0.100\\ MAVEN-rand2D & 12.820$\pm$0.584& 0.194 & MAVEN-rand2D & 11.384$\pm$0.001 & 0.316 & MAVEN-rand2D & 154.501$\pm$0.345 & 0.038\\ MAVEN-rand3D & 12.620$\pm$0.001 & 0.202 & MAVEN-rand3D & \textbf{10.791$\pm$0.029} & 0.357 & MAVEN-rand3D & 158.749$\pm$0.297 & 0.179\\ MAVEN-rand5D & 18.509$\pm$0.001 & 0.215 & MAVEN-rand5D & 11.052$\pm$0.751 & 0.323 & MAVEN-rand5D & 152.778$\pm$1.254 & 0.180\\ \cline{4-9} Dropout-GAN\citep{mordido2018dropout} & 88.60$\pm$ 0.08 & - \\ TTUR\citep{heusel2017gans} & 36.9 & - \\ Coulomb GANs\citep{unterthiner2017coulomb} & 27.300 &- \\ AIQN\citep{ostrovski2018autoregressive} & 49.500 & - \\ SN-GAN\citep{miyato2018spectral} & 21.700 & - \\ Learned Moments\citep{ravuri2018learning} & 18.9 & - \\ \cline{1-3} \end{tabular} } \end{table} \begin{table}[t] \setlength{\tabcolsep}{4pt} \centering \caption{Average cross-validation accuracy and class-wise F1 scores for the semi-supervised classification performance comparison of the DC-GAN, VAE-GAN, and MAVEN models using the SVHN dataset.} \label{table:svhn-accuracy} \medskip \resizebox{\linewidth}{!}{ \begin{tabular}{|c|c|c|c|c|c|c|c|c|c|c|c|} \cline{1-12} Model & Accuracy & \multicolumn{10}{|c|}{F1 scores}\\ \cline{3-12} && 0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 \\ \hline DC-GAN & 0.876 & 0.860 & 0.920 & 0.890 & 0.840 & 0.890 & 0.870 & 0.830 & 0.890 & 0.820 & 0.840 \\ VAE-GAN & 0.901 & 0.900 & 0.940 & 0.930 & 0.860 & 0.920 & 0.900 & 0.860 & 0.910 & 0.840 & 0.850 \\ MAVEN-mean2D & \textbf{0.909} & 0.890 & 0.930 & 0.940 & 0.890 & 0.930 & 0.900 & 0.870 & 0.910 & 0.870 & 0.890 \\ MAVEN-mean3D & \textbf{0.909} & 0.910 & 0.940 & 0.940 & 0.870 & 0.920 & 0.890 & 0.870 & 0.920 & 0.870 & 0.860 \\ MAVEN-mean5D & 0.905 & 0.910 & 0.930 & 0.930 & 0.870 & 0.930 & 0.900 & 0.860 & 0.910 & 0.860 & 0.870 \\ MAVEN-rand2D & 0.905 & 0.910 & 0.930 & 0.940 & 0.870 & 0.930 & 0.890 & 0.860 & 0.920 & 0.850 & 0.860 \\ MAVEN-rand3D & 0.907 & 0.890 & 0.910 & 0.920 & 0.870 & 0.900 & 0.870 & 0.860 & 0.900 & 0.870 & 0.890 \\ MAVEN-rand5D & 0.903 & 0.910 & 0.930 & 0.940 & 0.860 & 0.910 & 0.890 & 0.870 & 0.920 & 0.850 & 0.870 \\ \hline \end{tabular} } \end{table} \begin{table}[t] \setlength{\tabcolsep}{4pt} \centering \caption{Average cross-validation accuracy and class-wise F1 scores for the semi-supervised classification performance comparison of the DC-GAN, VAE-GAN, and MAVEN models using the CIFAR-10 dataset.} \label{table:cifar10-accuracy} \medskip \resizebox{\linewidth}{!}{ \begin{tabular}{|c|c|c|c|c|c|c|c|c|c|c|c|} \cline{1-12} Model & Accuracy & \multicolumn{10}{|c|}{F1 scores}\\ \cline{3-12} && airplane & automobile & bird & cat & deer & dog & frog & horse & ship & truck\\ \hline DC-GAN & 0.713 & 0.760 & 0.840 & 0.560 & 0.510 & 0.660 & 0.590 & 0.780 & 0.780 & 0.810 & 0.810 \\ VAE-GAN & 0.743 & 0.770 & 0.850 & 0.640 & 0.560 & 0.690 & 0.620 & 0.820 & 0.770 & 0.860 & 0.830 \\ MAVEN-mean2D & 0.761 & 0.800 & 0.860 & 0.650 & 0.590 & 0.750 & 0.680 & 0.810 & 0.780 & 0.850 & 0.850 \\ MAVEN-mean3D & 0.759 & 0.770 & 0.860 & 0.670 & 0.580 & 0.700 & 0.690 & 0.800 & 0.810 & 0.870 & 0.830 \\ MAVEN-mean5D & \textbf{0.771} & 0.800 & 0.860 & 0.650 & 0.610 & 0.710 & 0.640 & 0.810 & 0.790 & 0.880 & 0.820 \\ MAVEN-rand2D & 0.757 & 0.780 & 0.860 & 0.650 & 0.530 & 0.720 & 0.650 & 0.810 & 0.800 & 0.870 & 0.860 \\ MAVEN-rand3D & 0.756 & 0.780 & 0.860 & 0.640 & 0.580 & 0.720 & 0.650 & 0.830 & 0.800 & 0.870 & 0.830 \\ MAVEN-rand5D & 0.762 & 0.810 & 0.850 & 0.680 & 0.600 & 0.720 & 0.660 & 0.840 & 0.800 & 0.850 & 0.820 \\ \hline \end{tabular} } \end{table} \begin{table} \setlength{\tabcolsep}{4pt} \centering \caption{Average cross-validation accuracy and class-wise F1 scores for the semi-supervised classification performance comparison of the DC-GAN, VAE-GAN, and MAVEN models using the CXR dataset.} \label{table:chex-accuracy} \medskip \resizebox{0.6\linewidth}{!}{ \begin{tabular}{|c|c|c|c|c|} \cline{1-5} Model & Accuracy & \multicolumn{3}{|c|}{F1 scores}\\ \cline{3-5} && Normal & B-Pneumonia & V-Pneumonia\\ \hline DC-GAN & 0.461 & 0.300 & 0.520 & 0.480\\ VAE-GAN & 0.467 & 0.220 & 0.640 & 0.300\\ MAVEN-mean2D & 0.469 & 0.310 & 0.620 & 0.260\\ MAVEN-mean3D & {\bf 0.525} & 0.640 & 0.480 & 0.480\\ MAVEN-mean5D & 0.477 & 0.380 & 0.480 & 0.540\\ MAVEN-rand2D & 0.478 & 0.280 & 0.630 & 0.310\\ MAVEN-rand3D & 0.506 & 0.440 & 0.630 & 0.220\\ MAVEN-rand5D & 0.483 & 0.170 & 0.640 & 0.240\\ \hline \end{tabular} } \end{table} \subsubsection{CIFAR-10} For the CIFAR-10 dataset, all the models were trained for 300 epochs and then evaluated. We generated an equal number of new images as the training set size. Fig.~\ref{fig:cifar_images} visually compares the generated images from the GAN, VAE-GAN, and ALEAN models relative to the real training images. The FID and DDD measurements were performed with the distribution of 10,000 samples drawn from the generated images and 10,000 samples from the real training images. For the FID score calculation, the pre-trained Inception-v3 network was run for 20 epochs and the FID score was recorded. The FID and DDD scores are reported in Table~\ref{table:fid-ddd}. As the tabulated results suggest, our proposed MAVEN models achieved better FID scores than some of the recently published models. Note that, those models were implemented in a different settings. As for the visual comparison, the FID and DDD scores confirmed more realistic image generation with our ALELAN models than the DC-GAN and VAE-GAN models. Except for MAVEN-mean with 2 discriminators, all other MAVEN models have smaller FID scores; MAVEN-rand with 3 discriminators has the smallest FID score among all the models. For the semi-supervised classification, both image-level accuracy and class-wise F1 scores were calculated. Table~\ref{table:cifar10-accuracy} compares the performance of all the models for the CIFAR-10 dataset. \subsubsection{CXR} For the CXR dataset, all the models were trained for 150 epochs and then evaluated. We generated an equal number of new images as the training set size. Fig.~\ref{fig:chex_images} presents a visual comparison of synthesized and real image samples. The FID and DDD measurements were performed for distribution of generated and real training samples, indicating that more realistic images were generated by the MAVEN models than by the GAN and VAE-GAN models. The FID and DDD scores presented in Table~\ref{table:fid-ddd} show that the mean MAVEN model with 3 discriminators (MAVEN-mean3D) has the smallest FID and DDD scores. The classification performance reported in Table~\ref{table:chex-accuracy} suggests our proposed MAVEN model-based classifers are more accurate than the basline GAN and VAE-GAN classifiers. Among all the models, MAVEN-mean classifier with 3 discriminators found to be the most accurate in classifying the B-pneumonia and V-pneumonia from normal. However, the overall performance is not so good for the CXR dataset compared to the natural image datasets. A possible reason could be the shortage of data and the omission of a larger portion of the labels. The main issue in the medical image dataset is that, unlike natural images, every case is different than others, even though they are labeled as the same class. It may be possible to resolve this by augmenting the training set with the generated images from each of the models. However, the goal of our present work was to devise a generative model architecture that could be equally competitive as a generator and a classifier. Even with the relatively smaller dataset, the proposed MAVEN models perform better than the baseline models. \section{Conclusions} We have demonstrated the advantages of an ensemble of discriminators in the adversarial learning of variational autoencoders and the application of this idea to semi-supervised classification from limited labeled data. Training our new MAVEN models on a small, labeled dataset and leveraging a large number of unlabeled examples, we have shown superior performance relative to prior GAN and VAE-GAN based classifiers, suggesting that our MAVEN models can be very effective in concurrently generating high-quality realistic images and improving multi-class classification performance. However, it remains an open problem to find the optimal number of discriminators that can perform consistently. Our future work will consider more complex image analysis tasks beyond classification and include more extensive experimentation spanning additional domains.
{'timestamp': '2019-06-18T02:03:12', 'yymm': '1906', 'arxiv_id': '1906.06430', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06430'}
arxiv
\section{Introduction} We generate, capture, and manage more data everyday. However, the real value of data is in further processing and analyzing it to gain insights. Data analytics software applications are class of software systems that are commonly used to explore and extract insights from multiple data sources. As local information is quite important, a popular subset of these systems cater geospatial data analytics for supporting spatial features of data records, along with other features, and commonly visualizing data and insights as maps. Since datasets from different sources may have different levels of abstraction, accuracy, and completeness the process of aggregating heterogeneous datasets can be challenging. In addition, some data sources may change frequently which out-dates the previous versions of the recorded data. The situation is even worse in case of geospatial data analytics, as identical geospatial entities from multiple sources can be captured and modeled differently. As managing and organizing large number of geospatial datasets can be challenging, there are companies that offer Maps as a Service. The core offering of these companies is to gather data from multiple sources, clean, organize, manage, and update these datasets to provide their customers with up interactive maps that can represent several perspectives on-demand. As these service providers work with large number of datasets from multiple sources they inevitably encounter many conflicts while integrating new datasets or even when updating from an existing dataset. This is a significant scalability problem for companies in this domain, since the manual validation of frequent and large data integration phases are quite expensive. Therefore, in this study, we propose a systematic validation approach, which semi-automatically aggregates geo-spatial datasets from heterogeneous sources, while keeping the system consistent after each merge. The idea is to reduce the number of potential conflicts that need a domain expert to validate the merge. Our approach consists of two phases: \begin{itemize} \item Phase 1 -- \emph{Conflict Identification}: We propose a fully automated solution based on the similarity of spatial and non-spatial features of the merging data records. The spatial similarity functions are borrowed from Geographic Information System (GIS) research domain and non-spatial similarities are taken from Information Retrieval (IR) domain. The novelty of this paper is combining these two similarities and evaluating them in an industrial context. \item Phase 2 -- \emph{Conflict Resolution}: This semi-automated phase is our future work. We introduce its basic components in this paper, to show the full picture of the solution, but we do not report any results for phase 2. \end{itemize} The phase 1 results, based on our industrial case study, showed that we can identify the conflicts automatically, with over $95\%$ $Precision$ and $Recall$ values. \section{ Motivational Example } \label{ Localintel Case study } Localintel is a software as a service company that provides market intelligence solutions to businesses that require such information to make informed decisions. Localintel aggregates data from various sources, including municipal, proprietary, and open-data to feed its web-based tools. These tools are basically web services that utilize map and dashboards to present local information and insights relevant to specific industries and their operating environment. \begin{figure}[!t] \includegraphics[width=8.5cm]{Fig1.eps} \caption{Conflict - different colors represent different datasets.} \label{ConflictsExamples} \end{figure} Most of Localintel tools contain multiple geospatial datasets from different sources. Each dataset has distinct properties, and quality of datasets varies. Depending on the data source, datasets are updated at different rates, on a regular basis or as needed. For example, to be able to build a layer which represents ``restaurants'' information as points on a map for downtown Calgary, Localintel receives datasets containing information about changes in restaurant and coffee shop businesses on a monthly basis. Given that input datasets are usually from different sources they can have different levels of accuracy in their spatial and non-spatial features. For example, Figure~\ref{ConflictsExamples} shows a sample case of integrating data from three different sources with inconsistent data about some points of interests. In this case, each dataset is showing a different location for an object called ``Laurier''. We also can not say if it is called a lounge or a restaurant. Such inconsistencies cause conflicts in the system and they need to be resolved before every merge of a new dataset to make sure that the system is always in a consistent state. Identifying and resolving these conflicts, manually, is only possible for few clients and small datasets. But it is definitely not scalable as the number of clients grows (with several layers being visualized for each) and datasets that are frequently being updated and merged into the system. Therefore, it is critical for the company to use an automated approach for data integration of geospatial datasets. \section{The Semi-Automated Validation Approach}\label{The Semi-Automated Validation Approach} In our proposed approach, we aim to reduce the manual validation effort during data integration phase, either when merging new datasets or updating existing ones. Figure~\ref{BigPicture} summarizes the solution, which can be considered as a validation step before merging or updating data objects. As illustrated in Figure~\ref{BigPicture}, the first step is to identify conflicting objects which introduce inconsistencies in the system. In the second step, we must decide on the resolving actions to remove the conflicts. For ease of reference, we denote the objects in the new dataset, which can be completely new or an updated version of an existing object, as $O_N$ and the existing objects of the system as $O_S$. \subsection{Conflict Identification} The sample case of Figure~\ref{ConflictsExamples} was an example of a case in which a data conflict is caused by objects corresponding to the same entity in the real world. At the first glance, it may seem that conflicting objects can be identified by getting the difference (``\textit{diff}'') of $O_N$ records and $O_S$ records. However, a simple \textit{diff} function is very sensitive and can only eliminate those $O_N$ records which there is an exact same $O_S$ for them and fails to detect the same objects with slight alterations. Therefore, to make sure that all the conflicts are resolved before a merge, we need a better solution than a simple \textit{diff} function. Assuming that there is no conflict between any two $O_N$ from one new dataset and all new datasets are internally consistent, and the current system is in a consistent state (there is no conflict between any two $O_S$) then each $O_N$ can potentially have conflicts with at most one $O_S$ in the system. Hence, the conflict identification problem can be reformulated as \emph{searching for the most similar $O_S$ record per $O_N$}. Now, in order to find out the similarity of a pair of objects ($<O_N,O_S>$), we need a similarity measure that takes both spatial and non-spatial features into account. Since these two types are completely different, we use two separate functions per feature type (spatial and non-spatial) and then combine the two measures to return one single similarity value, which can be considered as a ``conflict probability'' of the $<O_N,O_S>$ pair. \begin{figure}[!t] \includegraphics[width=8.5cm]{Fig2.eps} \caption{The big picture of our semi-automated approach.} \label{BigPicture} \end{figure} The two similarity measures are defined as follow: \begin{itemize} \item \emph{Spatial Similarity Measure}: Geospatial objects are representations of entities abstracted as points, lines or polygons and stored as vectorized data. Therefore, to have a spatial similarity measure, we should be able to compare points, lines and polygons with each other. \item \emph{Non-Spatial (IR-based) Similarity Measure}: Non-spatial features can store a wide range of information about objects. They are usually textual or numerical attributes describing an object (e.g. name, address, telephone number, number of employees). So for non-spatial similarity, we adopt suitable textual or numerical similarity measures, from the IR domain, based on the context. \end{itemize} \subsubsection{Spatial Similarity Measure} Different datasets can model the real world in different ways. For example, a dataset may abstract a river as a line while another dataset representing the same river as a polygon, or a building can be represented as a point or a polygon in different datasets. In addition to modeling/abstraction differences, there can also be differences between datasets caused by errors, such as slight alteration of a point location in two different datasets. Therefore, to capture all these different types of conflicting objects, we need to automate the following two class of comparisons: \begin{itemize} \item CalssI: point2point; point2line; point2polygon \item CalssII: line2line; line2polygon; polygon2polygon \end{itemize} These two categories are based on the complexity of the involved objects and the similarity functions that we use for them. Basically, the first class includes point objects and the second class involves more complicated shapes such as lines and polygons. \\ \textbf{Class I Comparison: } In Class I comparisons, we are dealing with two objects, which at least one of them is a point. In such comparisons, we must measure the similarity of a point to other objects which are points or approximated as points. Note that for simplification purposes, when a point is being compared to a line or polygon, we compare the point with the centroid of the line or polygon. The similarity measure is symmetric, and we do not differentiate between point2line and line2point or point2polygon and polygon2point comparisons. Searching among all objects in $O_S$ records to find similar cases to $O_N$ is quite expensive and does not pay off. Therefore, in order to make the search space smaller, for each $O_N$, we search the adjacent objects by querying the database to retrieve the $O_S$ records located in (or overlapping with) a maximum distance of $\mathcal{E}$ from the reference object. This is a reasonable assumption, as conflicting objects are expected to be in close proximity. The next step is to assign a weight to all adjacent objects, which is achieved by the inverse of their (e.g., Euclidean) distance from the reference point. Finally, the normalized weights define the spatial conflict probabilities. \\ \textbf{Class II Comparison: } In Class II comparisons, we are dealing with more complex shapes such as lines and polygons. Lines in vectorized data, are presented using a set of points with one start and one end point, while the start point $\neq$ the end point. Similarly, polygons are rendered on map using a set of points which define the border of that object. But unlike lines, the start point in a polygon must be equal to the end point, since polygons are closed shapes. But since both lines and polygons are demonstrated as set of points (edges), we do not differentiate between these two when adopting a similarity metric in class II comparisons. For scalability concerns, as Class I, we reduce our search to only the adjacent objects. So to find the search (neighboring) area for lines and polygons, again we consider circles with ratio of $\mathcal{E}$ around the vertices of their shapes. Then all the objects which are located within (or overlap with) this area are considered as adjacent objects. When we are dealing with points, defining a distance function is more obvious since there exist already many simple point2point distance functions such as Manhattan and Euclidean which we can adopt. But when we are dealing with more complex shapes such as lines and polygons, a suitable distance function might not be very intuitive. There exist several distance metrics for lines/polygons, which are mostly based on distance of vertices in two shapes \cite{shapeDistance}. Different measurements have been proposed to calculate the distance of two polygons/lines such as Hausdorff \cite{ModifiedHausdorff} and Chamfer, in which a distance is calculated using maximum and summation of distances of points in two shapes, respectively. Although Hausdorff and Chamfer can give us a good sense about the distance of two polygons/lines, but they are not the best in our context since they are very sensitive to addition or removal of edges/vertices. However, such a non-monotonic response to slight alterations is not desirable in our approach. On the other hand, the PoLiS \cite{Polic} metric, proposed by Avbelj et. al., is an alternative distance function, which is more promising and seems to be a better fit. So appropriate distance functions should be selected carefully base on the context of the features. \subsubsection{Non-Spatial Similarity Measure (IR-based)} \label{TextualSim} In the next step, we define a non-spatial conflict probability by calculating the textual/numerical distances between the two objects, using standard IR-based similarity functions. Since there are many different algorithms for textual similarity both for short textual segments \cite{shortTextSimilarity1,shortTextSimilarity2} and long textual documents \cite{longTextSimilarity}, we must make sure to adopt the best fit for each non-spatial feature. Therefore, we do not suggest a ``best'' similarity function for all features and rather recommend carefully experimenting to find and tune the best fit, per context. In our study, to calculate the non-spatial similarity, we adopt Okapi BM25\cite{BM25} (which is implemented in Solr \cite{Solr}) to calculate the similarity score of documents. BM25 (BM stands for Best Matching) is a ranking function based on the probabilistic retrieval framework. BM25 and its variants can be considered as state-of-the-art TF-IDF-based functions, which are used in search engines as scoring algorithm to rank documents according to their relevance to a given search query. So each $O_S$($d$) is ranked based on the similarity score of its spatial and non-spatial fields to an $O_N$($q$), which is calculated as follows: \begin{equation} \label{eqn:01} \fontsize{1}{10}\selectfont{ Score(q,d)=\sum_{t\in q}^{} {(tfNorm(t\in d).idf(t))}+DistBoost(q,d)} $$\vspace{1mm} \fontsize{9}{10}\selectfont{ $tfNorm = \frac{(freq * (k1 + 1))}{(freq + k1 * (1 - b + b * \frac{fieldLength)}{ avgFieldLength})}$\\ \vspace{2mm} $idf(t)=\log(1 + \frac{(docCount - docFreq + 0.5)}{(docFreq + 0.5)}) $\\ \vspace{1mm} $docCount$= Number of whole documents in the corpus\\ \vspace{1mm} $docFreq$= Number of documents which include the term\\ \vspace{1mm} $fieldLength$ = Number of terms in document(d) \\ \vspace{1mm} $avgFieldLength$ = Average Number of terms in all documents\\ \vspace{1mm} $K1$ = Term frequency normalization parameter\\ \vspace{1mm} $b$ = Length normalization parameter \\ $DistBoost$: Calculated based on $\frac{1}{distance(q,d)}$, then normalized based on maximum non-spatial score }$$ \end{equation} In equation \ref{eqn:01}, as mentioned, we use BM25 to calculate the non-spatial score of documents with default normalization values of K1=1.2 and b=0.75. Then to ensure that closer objects will eventually get a higher rank, we enhance this score by spatial similarity of objects (using inverse of distance of points) to tune the algorithm performance. One important parameter that we have in this approach is the radius of search space ($\mathcal{E}$). A very large $\mathcal{E}$ can cause delays in the process of merging and makes it a very time consuming task, while choosing a very small $\mathcal{E}$ may result in failure in detection of some conflicts. Furthermore, to make sure that we are not flooding the domain experts with many conflict warnings consisting of many false positives, we define a threshold ($T$) on the conflict probability values to make the results more accurate. Note that ($T$) should be large enough to capture all the conflicts. These parameters must be carefully tuned based on the context and the domain expert's feedback, iteratively, to provide the best results. \section{Empirical Evaluation} \label{CaseStudy} To evaluate our approach, in real-world scenarios, we designed a set of experiments and interviews to assess the efficiency of our solution in different settings. In each experiment, we study a case from Localintel in which a new dataset merges into the existing database in the system. We also conducted a small set of interviews to get a feedback from the company developers on the approach. In the following subsections, we first describe the design of these experiments and interviews, then provide their results, and finally analyze the results to answer our research questions. \subsection{Objectives and Research Questions} The goal of this section is to assess the effectiveness of our proposed automated approach for conflict identification, and compare it to a basic automated alternative. The scope of the study is limited to datasets where each item, i.e. Point of Interest (PoI), is represented by a ``point''. We have broken down the goal into three research questions (RQs), as follows: \begin{itemize} \item RQ1. How accurate is our proposed approach in terms of detecting existing conflicts compared to a baseline? \item RQ2. What is the effect of objects density and PoI type on the effectiveness of the results? \item RQ3. How effective and useful is our automated approach from practitioners point of view? \end{itemize} \subsection{Study design} The context of our study is a scenario at LocalIntel (our industry partner), where a new dataset is added to an existing database of PoIs. To answer our research questions, we have used three datasets that are the sources of data at LocalIntel, we always keep one as the existing database and merge a second one to the system. Unfortunately, due to confidentiality reasons, we can not name the datasets and will call them datasets A, B, and C. As mentioned, in all these experiments objects are stored as points and there is no line or polygon included in these datasets. For each new data point ($O_N$) there can be several possibilities, as follows: \begin{enumerate} \item Category 1: Non-conflicting objects (there is no corresponding $O_S$). \item Category 2: Conflicting objects: \begin{enumerate} \item There is an identical $O_S$. \item There is a corresponding $O_S$, but with practically ignorable differences. \item There is a corresponding $O_S$, but with practically significant differences. \end{enumerate} \end{enumerate} So as a first step toward a fully automated approach, we are seeking for an automated technique that a) can exclude category 1 objects from the others, and b) can detect conflicting objects in all three subgroups of category 2 and furthermore distinguishes between category $1.c$ (the conflicts that need domain expert or machine learning for resolution) and the ones in category $1.a$ and $1.b$ (these are cases where one can automatically keep any of the two objects and delete the other to resolve the conflict). \subsubsection{Implementation Details} To implement our solution, we used Apache Solr\cite{Solr} which is an open-source tool for fast indexing and searching among documents. Using Solr, we indexed the system objects based on their location and textual features. In these experiments, we took ``business names'' as the only common feature to calculate the non-spatial similarity, but the tool can take any number of features to work with. We used StandardTokenizer\cite{Lucene} from Lucene to tokenize both documents and queries and after removing stopwords and transforming the tokens to their lowercase, using Porter stemmer, we unified all different forms that words can take. To combine spatial and non-spatial similarities, we first use the spatial similarity as a filter to narrow down the search space. This is done by taking a circle around each $O_N$, as its neighborhood area. Then for each $O_S$ in the neighborhood area of $O_N$, we calculate their textual similarity using the BM25 formula, which is described in Section\ref{TextualSim} which applies the distance boost to each adjacent objects score and take the $O_S$ with the highest score as the potential conflict for that $O_N$. $O_N$s with no $O_S$ passing the similarity threshold, are reported as non-conflicting objects. To tune the radius value for our experiments, we change the $\mathcal{E}$ value, from a search area of $\mathcal{E}$=100 meters to 250 meters (increments of 50m). We report the results of the tuning phase in the beginning of the results section. \begin{table}[!t] \caption{The details of experiments design} \label{experimentDetails} \centering \resizebox{1\hsize}{!} \renewcommand{\arraystretch}{3} \begin{tabular}{|c|| c | c | c| c | c | c |} \hline \thead{\Large EXP\#}&\thead{\Large City} &\thead{\Large PoI} & \thead{\Large Dataset1} & \thead{\Large Dataset2} & \thead{\Large Area\\ ($m^2$)} & \thead{\Large Density\\ ($\frac{objects}{Km^2}$)}\\ \hline\hline \makecell{EXP\#1} & Montreal & Restaurant & \makecell{B\\ (544 records)} & \makecell{A \\(1985 records)} & 32,834,195 & \makecell{$70-Low$}\\ \hline \makecell{EXP\#2} & Seattle & Restaurant & \makecell{B \\(138 records)} & \makecell{C\\ (1442 records)} & 8,238,390 & \makecell{$190-Medium$}\\ \hline \makecell{EXP\#3} & Calgary & Restaurant & \makecell{A\\(362 records)} & \makecell{C\\(616 records)} & 3,422,222 & \makecell{$280-High$}\\ \hline \makecell{EXP\#4} & Calgary & Real Estate & \makecell{A\\(179 records)}& \makecell{C\\(274 records)} & 3,422,222 & \makecell{$130$}\\ \hline \end{tabular}% \renewcommand{\arraystretch}{1} } \end{table} \subsubsection{RQ1 design} To answer RQ1, we designed an experiment (Exp1), where we measure the effectiveness of our approach in detecting conflicts when merging two datasets (B is merged with A) of restaurants in downtown Montreal. The goal is to compare the results of our technique with a simpler alternative. The only related work that uses both spatial and non-spatial features during integration is the work by Seghal et. el., \cite{sehgal}. However, their textual similarity function is very naive (edit distance on the ``characters'' of textual features. So we improved this function and use a ``containment relation'' to serve as a baseline non-spatial similarity function. Therefore, In terms of implementation, both baseline and our proposed approach, follow the same routine: for each $O_N$, we search for the adjacent $O_S$ objects in the searching area and then for each pair we go through their common non-spatial features (which are previously converted to lowercase). However, with respect to non-spatial data, the similarity functions are different in baseline vs. our SDI approach. The baseline only checks for the ``containment relation'' between two texts, bidirectionally. If the containment relation is satisfied in all the common non-spatial features (the business name feature, in this study) in at least one direction, then the pair is reported as a conflict. Our proposed SDI approach, on the other hand, uses the explained TF-IDF-based approach as the non-spatial similarity function. \subsubsection{RQ2 design} To answer RQ2, we designed three new experiments (EXP 2,3 and 4). First, in Exp1 to 3, we analyze the performance of our proposed approach in cities with three different degrees of object density Montreal (``Low''), Seattle (``Medium''), and Calgary (``High''), for the restaurant datasets, and then we compare it to our baseline technique. Note that in these experimenets we always take two datsets out of three (A, B, and C), randomly, as existing vs. new dataset. Finally, in the next step (Exp4), we analyze the effect of PoI change on our solution effectiveness by taking a random city of the three studied ones (Calgary in this case) and change the PoIs from restaurant to Real Estate. Table\ref{experimentDetails} summarizes the features of all four experiments in RQ1 and RQ2. \subsubsection{RQ3 design} In order to validate our approach and assess its usefulness in practice, we arranged a small set of three interviews, in which we asked three software developers from Localintel's technical team, who did not know about this work prior to the interview, to work with our tool to merge a new dataset to Localintel system's database. The sessions took roughly an hour per developer where an interviewer (an author of the paper) helped them throughout the process. At the end of each session, the interviewer asked the developer a set of questions to get their high-level feedback on the approach and its results. The results is reported in the next section. \subsection{Study results} In this section, we provide the results of the experiments and interviews to answer our three RQs. \begin{table}[!t] \caption{Radius Tuning - The effect of $\mathcal{E}$ on the performance of solution in Exp1 (in terms of $Precision$ and $Recall$)} \label{Tuning} \centering \resizebox{1\hsize}{!}{% \begin{tabular}{|c|| c | c | c| c | c | c |} \hline \thead{Radius\\(meters)}&\thead{Total\\Number of\\ conflicts} &\thead{Conflicts\\correctly \\Detected} & \thead{Conflicts\\Wrongly\\Detected} & \thead{Missed\\conflicts} & \thead{Precision\\(\%)} & \thead{Recall\\(\%)}\\ \hline 100 & 254 & 242 & 0 & 12 & 100 & 95.27\\ \hline 150 & 254 & 243 & 0 & 11 & 100 & 95.66\\ \hline \rowcolor{gray!30} 200 & 254 & 245 & 0 & 9 & 100 & 96.45\\ \hline 250 & 254 & 243 & 2 & 11 & 99.18 & 95.66\\ \hline \end{tabular}% } \end{table} \subsubsection{Tuning results} As mentioned before, we first tune the search space radius ($\mathcal{E}$) to find the best search area for our experiments. Table \ref{Tuning} summarizes the result of this analysis in terms of $Precision$ and $Recall$ for Exp1 (Restaurants of Montreal). As we can see, as we increase the $\mathcal{E}$ from 100 to 200 meters, the $Recall$ value increases 1.18 \% while the $Precision$ remains 100\%. However more increase in radius to 250 meters results in decrease in both $Precision$ and $Recall$. Based on these results and after consulting with the domain experts at Localintel, we take the $\mathcal{E} = 200 m$ as a default value for search area radius and we use this value in all the follow up experiments. \subsubsection{RQ1 results} Table \ref{Results} summarizes the performance of our solution for all the four experiments and compares it with the baseline method. To answer RQ1, we analyze Exp1 in which two datasets containing the restaurants of Montreal merge. In this experiment, there are 254 conflicts which are manually detected and labeled. We can observe that Baseline method can detect 184 conflicts, while missing the other 70 conflicts without producing any false positive. Although this is good in terms of $Precision$, but since this method fails to detect a big portion of conflicts, it is not very good in terms of $Recall$. However, our solution can detect 245 conflicts without generating any false positive, which increases the $Recall$ value from 72\% to 96\% (almost 24\% improvement) while keeping the $Precision$ 100\%. Observing the results from Exp1, we can now answer RQ1 as: `` With a substantial improvement to baseline method, our approach can detect conflicts with a relatively high precision and recall.'' \subsubsection{RQ2 results} For Exp2 (restaurants of Seattle), with object density ``Medium'', again the baseline method performs well in terms of $Precision$, but misses 19 conflicts out of 89 labeled conflicts. On the other hand our solution, with missing only 4 conflicts, improves the $Recall$ from 78\% to 95\% (17\% improvement) while keeping the $Precision$ still very high (with only 2\% loss). Increasing the density to ``High'' in Exp3, the baseline method fails to detect 14 conflicts out of 340, however, our solution with missing only one conflict, can detect almost all the conflicts and improves the $Recall$ value from 95\% to 99\% (4\% improvement), with a loss of 1.5\% in $Precision$. Finally, with changing the PoI type in Exp4 to ``real estate agencies'', we again observe the same pattern. Among 124 conflicts that have been manually labeled in this merge, baseline method can detect 111 of them, while missing the other 13. However, our solution can detect 119 conflicts and improve the $Recall$ from 89.5\% to 96\% (6.5\% improvement) while losing 2.5\% $Precision$ (misidentifying 3 conflicts). Based on the above results, we can answer RQ2 as: `` PoI type and Object density do not have a significant impact on the effectiveness of the approach and our approach consistently dominates the baseline results.'' \begin{table}[!t] \caption{Results of Exp1 to 4 for RQ1 and RQ2.} \label{Results} \centering \resizebox{1\hsize}{!}{ \rowcolors{2}{gray!30}{gray!10} \begin{tabular}{|c|| c | c | c | c| c | c | c |} \hline \thead{\large EXP\#}&\thead{\Large{Method}}&\thead{\large Total\\\large Number of\\\large conflicts} &\thead{\large Conflicts\\\large correctly \\\large Detected} & \thead{\large Conflicts\\\large Wrongly\\\large Detected} & \thead{\large Missed\\\large conflicts} & \thead{\large Precision\\(\%)} & \thead{\large Recall\\(\%)}\\\hline \cellcolor{white}& Our Approach &254 & 245 & 0 & 9 & 100 & 96.45\\ \multirow{-2}{*}{\cellcolor{white}EXP1}&Baseline &254 & 184 & 0 & 70 & 100 & 72.44\\\hline \cellcolor{white}& Our Approach & 124 & 119 & 3 & 5 & 97.54 & 95.96\\ \multirow{-2}{*}{\cellcolor{white}EXP2}& Baseline & 124 & 111 & 0 & 13 & 100 & 89.51\\\hline \cellcolor{white}& Our Approach & 340 & 339 & 5 & 1 & 98.54 & 99.7\\ \multirow{-2}{*}{\cellcolor{white}EXP3}& Baseline& 340 & 326 & 0 & 14 & 100 & 95.88\\\hline \cellcolor{white}& Our Approach & 124 & 119 & 3 & 5 & 97.54 & 95.96\\ \multirow{-2}{*}{\cellcolor{white}EXP4}& Baseline & 124 & 111 & 0 & 13 & 100 & 89.51\\\hline \end{tabular} } \end{table} \subsubsection{RQ3 results} Table \ref{Interview} summarizes the interview questions, and the complete interview can be found in appendix \ref{AppandixInterview}. Here to answer RQ3, we report a brief highlight of answers and summarize the comments in each question. We use DEV1-3 to anonymize the interviewee identities. \textbf{Discussion on the interview answers:} In the first question, the goal is to validate our solution once again to ensure that we are approaching the problem from the right angle. Answers show that all developers agree that not only the tool works fine for now, with the point objects, but also they think that this systematic approach has the potential to grow bigger to solve the Spatial Data Integration (SDI) problem as a whole. These developers are people who are specialized in computer science and specially geo-spatial software systems and they have been working with such datasets for a long time. So in question 2 and 3, in order to understand their perspective, we asked them what would they do if they were supposed to make a solution for SDI, or improve/extend the current solution. From their answers, first we learn that our solution is approaching the problem from a right angel and we are on the right track. Although DEV1 mentioned that having a structured schema in the first place can be investigated as a possible solution, but since our tool is aimed to work with any kind of spatial dataset schema-independently, we do not consider schema conversion complexities to be able to come up with a fast solution that is compatible with all kinds of spatial data. Also, as depicted in Fig \ref{BigPicture}, this tool can be considered as a preprocessing or a validation step for any next level processing such as schema-unification. Additionally, we collected some valuable ideas such as application of machine learning and fine tuning in identification and resolution steps to make the solution fully automated and more accurate. Finally, as the best jury, we asked them to give us their general feedback about this approach. As we can infer from their answers, they all think this systematic approach can be a valuable solution in SDI in companies that need to grow fast and scale up their database, and can be a good starting point toward a more accurate and inclusive solution. \subsection{Discussion on Conflict Resolution} \label{confres} As mentioned in Fig\ref{BigPicture}, our solution consists of two steps, and after detecting the conflicts, we need an automated mechanism to resolve them before merging with the system. Although in some cases we may be able to automatically resolve conflicts, but in many other cases we need the intervention of a domain expert to take the resolving decisions based on the origin of the conflicting objects and the semantics of the overlaps. Although we do not implement this part of the solution in our study, but we illustrate our vision by breaking down the problem and describing the structure of our data driven solution. To this end, first we categorize the conflicts based on their causes: \begin{table}[!t] \caption{Interview Questions} \label{Interview} \resizebox{\linewidth}{!}{% \begin{tabular}{|c|c|} \hline Q1 & \begin{tabular}[c]{@{}c@{}}Do you think the solution can work for Localintel\\ integration problem? How accurate you think the tool is?\end{tabular} \\ \hline Q2 & \begin{tabular}[c]{@{}c@{}}What would you do if you were supposed \\ to design a tool to do the merging?\end{tabular} \\ \hline Q3 & Do you have any suggestion to extend/improve the tool? \\ \hline Q4 & Please provide any other feedbacks (free format). \\ \hline \end{tabular}% } \end{table} \begin{itemize} \item \textit{Errors}: Conflicts that are caused by error-full data. \item \textit{Updates}: Conflicts that are caused by the outdated data. \item \textit{Abstraction}: Conflicts that are caused by objects with different levels of abstractions. \item \textit{Completeness}: Conflicts that are caused by objects with different levels of completeness. \item \textit{False Positives}: Wrongly detected conflicts. \end{itemize} Based on the cause of detected conflicts, there might be different resolving decisions taken by domain experts, i.e., a) keeping both of the objects, b) keeping one of them and deleting the other one, and c) making a new combined object. For example, conflicts due to Errors and Updates will be simply resolved by deleting the wrong or outdated object, or in conflicts which are due to completeness, we can combine two objects to make a new object that represents both, or in case of the abstraction conflicts, if one object can replace the other completely (it is more comprehensive and detailed) then the resolution is similar to the Update conflict case. Although in some cases we cannot resolve conflicts fully automated, and need for an expert supervision is inevitable, but in some other cases, with adoption of a suitable heuristic and machine learning algorithm, we can make the resolution process automated. The high-level idea here is that we keep recording the conflict resolution actions taken by the domain experts, per objects and datasets. Then when the training set is rich enough for classification, we can predict a resolving action automatically for a new identified conflict. Note that the machine-learning-based resolution is in our future work and has not been implemented/evaluated in this study. \section{Limitations and threats to validity} In terms of the limitation of the current work, although our approach is showing promising results for the analyzed cases, but we still can not generalize it to all objects including lines and polygons. So for lines and polygons a suitable similarity metric should be carefully analyzed and defined in order to cover all class I and class II comparisons. Also, in these experiments, to calculate non-spatial similarity, we only used business name, however we can take more features into account depending on the involved datasets to improve the results. In terms of the validity threats, we had a limited set of experiments and not exhaustively examined all combinations of the densities, PoI types, datasets, etc. Our interview study was also very small scale, more to get feedbacks rather than providing solid evidence of feasibilty or correctness. Therefore, we can not make any claims about the generalizabity of the study, before replicating this on more datasets and configurations. We have done a simple tuning of radius on Exp1 and reused that for all experiments which might not be the optimal configurations, and thus a threat to the conclusion validity. There are also several other parameters in our algorithm that we have not tuned. However, a better tuning would potentially improve the result even more. To get a stronger conclusion we should also retry the experiments with several random datasets and PoIs and perform a proper set of statistical significant tests, which is in our future plan for replication. \section{Related Works}\label{Related Works} Although SDI is not a new research topic and it is investigated by other researchers before, but it still lacks a robust, fast and scalable solution that can be applied in practice. While the spatial datasets are being gathered from heterogeneous sources continuously, the goal of SDI solutions is to make a united, integrated and single point access system that reflects the real world thoroughly and accurately \cite{related1,related2,related3}. While some papers propose an integrated system for different use cases such as river\cite{rivers} systems or bank's ATMs\cite{ATMs} datasets, geo-spatial datasets still require a multipurpose integrated system which can accurately represent reality from different aspects. Although having a general united data model \cite{DataModeling} can help us in having an integrated system, but with the emerge of noSQL databases, which offer more scalability and flexibility \cite{sqlVsNoSQL}, the urge for united data models is dimmer. But this does not imply that SDI challenges are solved. Therefore, in this study, instead of focusing on an integrated model for geo-spatial datasets, we leverage IR to propose a solution which can integrate heterogeneous datasets. In this line of research, Beeri et al. \cite{beeri} have proposed two joint approaches, namely, the sequential and the holistic approaches for merging two or more datasets. In another work, Safra et.al., \cite{POint2Point} propose an approach to find a location-based similarity of objects, which is based on one-sided nearest-neighbor join \cite{one-sided} of point objects. However these two solutions do not consider non-spatial features of data and just take the spatial features into account. In another study, Sehgal proposes an ``entity resolution'' \cite{sehgal} method in which entities are matched using their non-spatial features and coordinates. However this solution is very naive when it comes to text similarity, since they use an edit distance function on the ``characters'' of each textual feature. Therefore, lack of a thorough and systematic approach which covers the whole problem entirely, inspired us to conduct this study in which we carefully investigate details of such systems and propose a systematic solution for SDI. \section{Conclusion and Future Work}\label{conclusion} Every day, terabytes of geo-spatial data are gathered from different sources and stored digitally as different datasets. A major challenge of aggregating heterogeneous datasets in one integrated system is that with each merge, we should make sure that the system remains in a consistent state. However, corresponding objects can sometimes cause conflicts in a system and entangle the process of merging. The current practice of identifying and resolving conflicts is very manual and thus expensive and not scalable. In this study, which is a joint project in collaboration with industry, we introduce a new concept in SDI in which datasets can be continuously merged with the system database without requiring their schema to be converted to a unified model. With this concept a big portion of SDI effort which is related to schema uniforming is reduced to only data validation before inserting new records. In this paper, we tried to structure the problem and break it down to two steps of conflicts identification and resolution. Our initial evaluations showed a promising results both in terms of high accuracy of identification and consistency. As our future work, we plan to conduct larger experiments with cities and datasets of different sizes to certify the efficiency of the solution, involve more complex objects (lines and polygons), and investigate machine-learning-based solution for the ``conflict resolution'' phase.
{'timestamp': '2019-06-28T02:20:51', 'yymm': '1906', 'arxiv_id': '1906.06331', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06331'}
arxiv
\section{Introduction} \subsection{Motivation} Information Theory originates from \cite{shan2}. Today, its scope extends to a variety of scientific disciplines, including communications engineering, physics, statistics, economics, neuroscience, and bioengineering (see \cite{cover}).\\ \noindent At the heart of many information theoretic problems are \textit{joint entropy} and \textit{mutual information}. \noindent The former is interpreted, in information theory, as a measure of the randomness of a pair of random variables or as the uncertainty about the outcome of an experiment of two random variables taken together. It is related to statistical mechanics, topological dynamics and ergodic theory. \\ \noindent Mutual information characterizes the shared information between a pair of random variables. It is a fundamental quantity of interest in machine learning. \\ \noindent The importance of both \textit{joint entropy} and \textit{mutual information} can be seen through their appearance in several important theorems of information theory, although their applications extend to other fields. \\ \bigskip \noindent (\cite{shan2}) has introduced the notion of entropy $\mathcal{E}_{Sh}(\textbf{p}_X)$ of a random variable $X$, to quantify the \textit{expected information} gained from observing a value of the random variable $X$. The \textit{expected information} of observing two random variables X and Y is the \textit{joint entropy} $\mathcal{E}(\textbf{p}_{(X,Y)})$ of the pair $(X,Y)$. \textit{(Shannon) Mutual Information} (\textit{S.m.i.}) quantifies the \textit{amount of information} that is shared or redundant between the two variables. It is defined as \begin{equation}\label{sjent} \mathcal{E}_{S.m.i.}(\textbf{p}_{(X,Y)})=\mathcal{E}_{Sh}(\textbf{p}_X)+\mathcal{E}_{Sh}(\textbf{p}_Y)-\mathcal{E}(\textbf{p}_{(X,Y)}). \end{equation} With the definition of entropy for discrete variables (see \cite{cover}), the joint entropy and \textit{S.m.i.} of the pair of discrete random variables $(X,Y)$ are respectively \begin{eqnarray}\label{jrs} \mathcal{E}(\textbf{p}_{(X,Y)})&=&-\sum_{(i,j)\in I\times J}p_{i,j}\log p_{i,j},\\ \label{jrs3} \mathcal{E}_{S.m.i.}(\textbf{p}_{(X,Y)})&=&\sum_{(i,j)\in I\times J}p_{i,j}\log \frac{p_{i,j}}{p_{X,i}\, p_{Y,j}}, \end{eqnarray} where $p_{X,i}$, $p_{Y,j}$ and $p_{i,j}$ are the marginal and joint probability mass functions (p.m.f.'s) of $X$ and $Y$. \\ \noindent This definition can be easily extended to other types of random variables that may not have p.m.f.'s. The type of logarithm used determines the unit of measurement. In this work we use the natural logarithm. This means that the preceeding entropies are measured in the \textit{natural unit of information} (nat).\\ \bigskip \noindent Let give some properties :\\ \bigskip \noindent (a) The pair $(X,Y)$ can never have more entropy than the sum of the entropy in each of them i.e. \begin{eqnarray}\label{ineg1} &&\mathcal{E}(\textbf{p}_{(X,Y)})\leq \mathcal{E}_{Sh}(\textbf{p}_X)+ \mathcal{E}_{Sh}(\textbf{p}_Y).\end{eqnarray} In particular if $X$ and $Y$ are independent then $$ \mathcal{E}(\textbf{p}_{(X,Y)})= \mathcal{E}_{Sh}(\textbf{p}_X)+ \mathcal{E}_{Sh}(\textbf{p}_Y).$$ \bigskip \noindent Therefore $\mathcal{E}_{S.m.i.}(\textbf{p}_{(X,Y)})\geq 0$ where the \textit{S.m.i.} is zero if and only if $X$ are statistically independent. Hence, the \textit{S.m.i.} between $X$ and $Y$ can be regarded as a measure of dependence between these variables, or even better, a measure of the statistical correlation between $X$ and $Y$. As noted by many authors, \textit{S.m.i.} satisfies some of the desirable properties of a good measure of dependence [Granger and Lin (1994)]. \\ \noindent This idea is applied in statistical tests and makes the \textit{S.m.i.} an important tool for measuring dependence between random variables which is an interesting and fundamental problem in statistics and very useful in times analysis. \\ \bigskip \noindent (b) In the bivariate case, \textit{S.m.i} can be treated as a special case of \textit{Kullback Leibler divergence measure} : it is the \textit{Kullback Leibler divergence measure} between the joint distribution $\textbf{p}_{(X,Y)}$ and the product of marginal distributions $\textbf{p}_{X}\,\textbf{p}_{Y}$, i.e. $$ \mathcal{E}_{S.m.i.}(\textbf{p}_{(X,Y)})=\mathcal{D}_{K.L}(\textbf{p}_{(X,Y)},\textbf{p}_{X}\,\textbf{p}_{Y}).$$ \noindent See \cite{cover} and the references therein.\\ \bigskip \noindent The basic construction of the proposed plug-in estimator is as follows (see \textsc{Section} \ref{maincontrib} for a precise definition). First, given a pair $(X,Y)$ of discrete random variables with $(p_{i,j})_{(i,j)\in [1:r]\times [1:s]},$ the p.m.f.'s of all the possibles values $(x_i,y_j)$ of $(X,Y)$, we associate the single random variable $Z$ with p.m.f.'s $(p_{Z,k})_{k\in [1:rs]}$ and possible values $(z_{k})_{k\in [1:rs]}$ that such $$p_{i,j}=p_{Z,s(i-1)+j}.$$ \noindent Second for a fixed $(i,j)\in [1:r]\times [1:s]$, and from a sample of i.i.d. random variables from $Z$ , we give a strongly consistent and asymptoticaly normal estimate of $p_{Z,s(i-1)+j}.$ Finally Joint entropy $\mathcal{E}(\textbf{p}_{(X,Y)})$ and the \textit{S.m.i.} $\mathcal{E}_{S.m.i.}(\textbf{p}_{(X,Y)})$ is then estimated by plugging the estimate of $p_{Z,s(i-1)+j}$ into \eqref{jrs} and \eqref{jrs3}. \\ \noindent Results on consistency and asymptotic normality of the estimators for both Joint entropy and S.m.i of the pair $(X,Y)$ are given. The latter result is applied to statistic tests. \subsection{Bibliography and application } \noindent Before coming back to \textit{Joint entropy} and \textit{Shannon mutual information} estimation, we want to highlight some important applications of them. Indeed, both has proven to be useful in applications. Let us cite a few of them :\\ \noindent (a) The concept of joint entropy of a pair of random variables was proposed by \cite{phil} in investment in two securities whose returns $X$ and $Y$ are discrete random variables taking values $x_i,\,i=1,2,\cdots,r$ with p.m.f.'s $P_{X,i}$ and $y_j,\,j=1,2,\cdots,s$ with p.m.f.'s $P_{Y,j}$. Their theory has been proved useful by their empirical results.\\ \noindent (b) \textit{S.m.i} heavily intervenes in communications engineering, physical and biological sciences (see \cite{timm}), and in several graphical model inference problems (e.g., the Chow-Liu tree (see \cite{chow}), conditional independence testing (see \cite{chri}), sociology (see \cite{dave}), computational biology (see \cite{krishn}), and computational neuroscience (see \cite{fred}), in pattern recognition, feature selection problems. \\ \noindent (c) S.m.i. has interesting properties such as data-processing inequality, invariance under one-to-one transformations and the chain rule (see \cite{cover}) \noindent In the next subsection, we describe the different methods for estimation the S.m.i. and somes results in the literature \subsection{Previous work \noinden The estimation of the \textit{Shannon} mutual information from samples remains an active research problem. Lately, in theoretical as well as practical fronts, there has a resurgence of interest in entropy and mutual information estimators (see \cite{sric}, \cite{jian}, \cite{shas2}, \cite{shas}, \cite{moon2}, \cite{yanj}, \cite{gao2}, \cite{gao3}, \cite{gao4}, \cite{gao5}, \cite{papa}, \cite{walt}, and some offer good results even for small samples (\cite{khan}).\\ \noindent \textit{S.m.i} estimation has many applications including structure learning (see \cite{moon2}, independent subspace analysis (see \cite{pal}), forest density estimation (see \cite{liu}), clustering (see \cite{lewi}), and neuron classification (see \cite{schne}). \\ \noindent Before talking about estimation, let light up different methods for estimating \textit{S.m.i}. In the literature, the estimation of S.m.i. is divided in three groups :\\ \noindent The first group is the “\textit{bins}” method that discretizes the continuous data into different bins and estimates \textit{S.m.i.} from the discretized data (see \cite{bial}, \cite{stro}). \\ \noindent The second group is based on estimates of probability density functions, for example, the histogram estimator of \cite{fras}, the kernel density estimator (KDE) of \cite{moon}, the B-spline estimator of \cite{daub}, and the wavelet estimator of \cite{pete}. \\ \noindent The third group operate by using the $3$H-principe, i.e., by calculating the three (differential) entropies of $X$, $Y$ and the pair (X,Y) and by adding them up using \eqref{sjent}. One of the most popular estimations in this group is the \textit{k-nearest neighbors} (kNN) estimator introduced in \cite{sing}, which was extended to the \textit{Kraskov–Stogbauer–Grassberger} (KSG) estimator (see \cite{kras}. This estimator is further discussed in \cite{pal}, \cite{gao}, and recently in \cite{weih}.\\ \noindent Another point is that many estimators for \textit{S.m.i.} proposed in the literature were specifically designed for discrete variables or for continuous variables. However, most real problems are composed by a \textit{mixture} of both.\\ \bigskip \noindent \cite{antos} defined estimator for \textit{S.m.i.} of discrete random variables $X$ and $Y$ and showed that, \begin{eqnarray*} &&\lim_{n\rightarrow +\infty}\mathcal{E}_{S.m.i.}(\widehat{ \textbf{p}}_{(X,Y)}^{(n)})= \mathcal{E}_{S.m.i.}(\textbf{p}_{(X,Y)})\ \ \text{a.s.}\\ \text{ and}\ \ &&\lim_{n\rightarrow +\infty}\mathbb{E}\left( \mathcal{E}_{S.m.i.}(\widehat{ \textbf{p}}_{(X,Y)}^{(n)})- \mathcal{E}_{S.m.i.}(\textbf{p}_{(X,Y)})\right)^2=0 \end{eqnarray*} provided that $\mathcal{E}(\textbf{p}_{(X,Y)})<\infty$.\\ \noindent \cite{deem}, using the histogram method and under appropriate assumptions on the tail behavior of the random variables, showed that the \textit{S.m.i.} estimate is consistent in probability, that is, for any $\varepsilon>0$, \begin{equation}\label{cvpro} \lim_{n\rightarrow +\infty}\mathbb{P}\left(\left\vert \mathcal{E}_{S.m.i.}(\widehat{ \textbf{p}}_{(X,Y)}^{(n)})-\mathcal{E}_{S.m.i.}(\textbf{p}_{(X,Y)})\right\vert>\varepsilon \right)=0. \end{equation} \noindent This result will also be established by \cite{gaow} using the \textit{Kraskov–Stogbauer –Grassberger} (KSG) method and with some regular and smoothness conditions on respectively the Radon-Nikodym derivatives of $X$ and $Y$ and on the joint p.d.f. $ \textbf{p}_{(X,Y)}$ and with assumptions on the joint differential entropy $\mathcal{E}(\textbf{p}_{(X,Y)})$.\\ \bigskip \noindent \cite{gao}, using the \textit{Local Gaussian Density Estimation} method, proved that the \textit{S.m.i.} estimate is asymptotically unbiaised that is $$\lim_{n\rightarrow+\infty}\mathbb{E}\left(\mathcal{E}_{S.m.i.}(\widehat{ \textbf{p}}_{(X,Y)}^{(n)}) \right)=\mathcal{E}_{S.m.i.}(\textbf{p}_{(X,Y)}).$$ \bigskip \noindent \cite{xian} used the \textit{Jackknife} approach of the kernel with equalized bandwidth to estimate the \textit{S.m.i} for a pair of discrete random variables and mixed random variables (with neither purely continuous distributions nor purely discrete distributions). \\ \noindent By the \textit{$k-$nearest neighbors} (K-NN) method, \cite{weih} defined novel estimator for \textit{S.m.i.} of mixture of random variables $(X,Y)$. They proved that the proposed estimator is asymptotically unbiaised : \begin{eqnarray*} && \lim_{n\rightarrow+\infty}\mathbb{E}\left(\mathcal{E}_{S.m.i.}(\widehat{ \textbf{p}}_{(X,Y)}^{(n)}) \right)=\mathcal{E}_{S.m.i.}(\textbf{p}_{(X,Y)}), \end{eqnarray*} provided that $k=k(n)\rightarrow+\infty$ and $(k(n)\log n)/n\rightarrow 0 $ as $n\rightarrow \infty.$\\ \noindent Furthermore, they proved that, if in addition $ (k(n)\log n)^2/n\rightarrow 0 $ as $n\rightarrow \infty$, then $$ \lim_{n\rightarrow+\infty}\text{Var}\left(\mathcal{E}_{S.m.i.}(\widehat{ \textbf{p}}_{(X,Y)}^{(n)}) \right)=0.$$ \bigskip \noindent \cite{bekn} studied the mutual information estimation for mixed pair random variables. They developpped a kernel method to estimate the mutual information between the two random variables. The estimates enjoyed a central limit theorem under some regular conditions on the distributions.\\ \noindent Our method falls down in the secong group and uses S.m.i. estimation of a pair of discrete random variables. \subsection{ Overview of the paper} The article is organized as follows. In section \ref{maincontrib}, we define the \textit{associated random variable} $Z$ of the pair of randoms variables $(X,Y)$. \\ \noindent In section \ref{estimation}, we construct the empirical estimator of the \textit{associated random variable} $Z$ and go on in section \ref{mainresults} to establish consistency and asymptotic normality results of the plug-in \textit{joint entropy} and \textit{S.m.i.} estimator. Section \ref{testindep} is devoted to the statistic tests of independence using S.m.i.\\ \noindent In section \ref{simulat} we provide a simulation study to assess the performence of our estimators and we finish by a conclusion in section \ref{conclus}. \section{Main contribution} \label{maincontrib} We begin by introducing our procedure over which our results will hold. \\ Let $X$ and $Y$ two discrete random variables taking values in the finite countable set $\mathcal{X}=\{x_i,i\in [1:r]\}$ and $\mathcal{Y}= \{y_j,j\in [1:s]\}$ both defined on $(\Omega,\mathcal{A},\mathbb{P})$. \\ \noindent In addition let $Z$ a random variable taking values in $\mathcal{Z}= \{z_k,\,k\in [1:rs]\}$.\\ \noindent Here simple computations show that \begin{eqnarray*} &&\text{if}\ \ (i,j)\in [1:r]\times [1:s]\ \ \ \ \ \text{then}\ \ \ \ \ s(i-1)+j\in [1:rs] . \end{eqnarray*} \bigskip \noindent We know that studying the joint distribution $\textbf{p}_{(X,Y)}$, of $X$ and $Y$ is tantamount to studying the distribution of the $rs$ mutually exclusive values $(x_i,y_j)$ of the pair $(X,Y)$. \\ \noindent For that, we associate, to the pair $(X,Y)$, the single random variable $Z$ such that for any possible joint values $(x_i,y_j)$ of the pair $(X,Y)$, we assign the single value $z_{s(i-1)+j} $ such that \begin{equation}\label{pijzk} \mathbb{P}(X=x_i,Y=y_j)=\mathbb{P}\left(Z=z_{s(i-1)+j}\right),\ \ (i,j)\in [1:r]\times [1:s]. \end{equation} \bigskip \noindent Conversely, by simple computions, we have that for any $k\in [1:rs]$, \begin{equation}\label{zkpij} \mathbb{P}(Z=z_k)=\mathbb{P}(X=x_i,Y=y_{k-s(i-1)}), \end{equation} where $i= \lfloor\frac{k+s-1}{s}\rfloor$ and $j=k-s(i-1)$.\\ \noindent Here $\lfloor x\rfloor$ denote the largest integer smaller than $x$.\\ \bigskip \noindent Denote in the sequel \begin{eqnarray*}I&=&[1:r],\ \ J=[1:s],\ \ \ \ \ K=[1:rs],\\ p_{i,j}&=&\mathbb{P}(X=x_i,Y=y_j),\ \ (i,j)\in I\times J\\ \text{and}\ \ p_{Z,k}&=&\mathbb{P}(Z=z_k),\ \ k\in K. \end{eqnarray*} \bigskip \noindent Now from p.m.f.'s $p_{Z,\delta_i^j},\,(i,j)\in I\times J$ we deduce those of the joint p.m.f.'s $p_{i,j}$ and marginals p.m.f.'s $p_{X,i}$ and $p_{Y,j}$.\\ \bigskip \noindent Then \eqref{pijzk} and \eqref{zkpij} mean that \begin{eqnarray}\label{pij3} p_{i,j}&=& p_{Z,\delta_i^j},\ \ \text{with}\ \ \delta_i^j=s(i-1)+j ,\\ \text{and} \ \ \ \label{pzk2} p_{Z,k}&=&p_{i,k-s(i-1)},\ \ i\in I. \end{eqnarray} \bigskip \noindent \textsc{Table} \ref{tabjpd} summarizes all the possible values of $(x_i,y_j)$ of the pair $(X,Y)$ in the first column and in the last column, their joint p.m.f.'s $p_{i,j},$ that we have denoted $p_{Z,s(i-1)+j}$, with $(i,j)\in I\times J$. \noindent Because the rows cover every possible joint assignment of values, the sum of their probabilities is equal to 1.\\ This Table illustrates the main findings of this study. \\ \noindent From there, the marginals \textit{p.m.f.'}s $p_{X,i}=\mathbb{P}(X=x_i)$ and $p_{Y,j}=\mathbb{P}(Y=y_j)$ and the conditionals \textit{p.m.f.'}s $p_{x_i|y_j}=\mathbb{P}(X=x_i|Y=y_j)$ and $p_{y_j|x_i}=\mathbb{P}(Y=y_j|X=x_i)$ are expressed from \textit{p.m.f.}'s of the random variable $Z$ by \begin{eqnarray} \label{pij2}&& p_{X,i}=\sum_{j=1}^sp_{Z,\delta_i^j},\ \ \ p_{Y,j}=\sum_{i=1}^rp_{Z,\delta_i^j},\\ && \label{cpij2} p_{x_i|y_j}=\frac{p_{Z,\delta_i^j}}{p_{Y,j}}=\frac{p_{Z,\delta_i^j}}{\sum_{i=1}^rp_{Z,\delta_i^j}},\ \ \ \text{and}\ \ \ p_{y_j|x_i}=\frac{p_{Z,\delta_i^j}}{p_{X,i}}=\frac{ p_{Z,\delta_i^j}}{\sum_{j=1}^sp_{Z,\delta_i^j}} . \end{eqnarray} \noindent Finally, entropies may be expressed in terms of $\textbf{p}_Z=(p_{Z,k})_{k\in K}$. Therefore using (\ref{pij3}), we can express the joint entropy and \textit{S.m.i} of the pair $(X,Y)$ in terms of the random variable $Z$ as \begin{eqnarray*} \label{jentent} \mathcal{E}(\textbf{p}_{(X,Y)})&:=&\mathcal{E}(\textbf{p}_{Z})=-\sum_{(i,j)\in I\times J}p_{Z,\delta_i^j}\log (p_{Z,\delta_i^j}), \\ \mathcal{E}_{S.m.i.}(\textbf{p}_{(X,Y)})&:=&\mathcal{E}_{S.m.i.}(\textbf{p}_{Z})=\sum_{(i,j)\in I\times J}p_{Z,\delta_i^j}\log \frac{p_{Z,\delta_i^j}}{p_{X,i}\, p_{Y,j}}.\label{S.m.i.} \end{eqnarray*} \begin{center} \vspace{9ex} \begin{table} \centering \begin{tabular}{|c|c|c|} \hline $(X,Y)$&$Z$&Joint p.m.f.\\ \hline $(x_1,y_1)$&$z_1$&$p_{Z,1}=p_{1,1}$\\ $(x_1,y_2)$&$z_2$&$p_{Z,2}=p_{1,2}$\\ $\vdots$&$\vdots$&$\vdots$\\ $(x_{1},y_{s})$&$z_s$&$p_{Z,s}=p_{1,s}$\\ \hline $(x_2,y_{1})$&$z_{s+1}$&$p_{Z,s+1}=p_{2,1}$\\ $(x_2,y_{2})$&$z_{s+2}$&$p_{Z,s+2}=p_{2,2}$\\ $\vdots$&&\\ $(x_{2},y_{s})$&$z_{2s}$&$p_{Z,2s}=p_{2,s}$\\ \hline $\vdots$&$\vdots$&$\vdots$\\ \hline $(x_r,y_{1})$&$z_{s(r-1)+1}$&$p_{Z,s(r-1)+1}=p_{r,1}$\\ $(x_r,y_{2})$& $z_{s(r-1)+2}$ &$p_{Z,s(r-1)+2}=p_{r,2}$\\ $\vdots$&$\vdots$&$\vdots$\\ $(x_r,y_{s})$&$z_{rs}$&$p_{Z,rs}=p_{r,s}$\\ \hline \end{tabular} \vspace{3ex} \caption{Illustration of the correspondance between $\textbf{p}_{(X,Y)}$ and $\textbf{p}_Z$. For each possible values of $(X,Y)$, we display the relationship between p.m.f.'s $p_{i,j}$ and $p_{Z,\delta_i^j}$, with $(i,j)\in [1:r]\times [1:s].$ }\label{tabjpd} \end{table} \end{center} \noindent We may give now the following remarks : \\ \noindent \textbf{(a)} For the special case where $s=r$ and $i=j\in \{1,\cdots,s\}$, data are of the form $(x_i,y_i)_{1\leq i \leq s}$ and $$p_{i,i}=p_{Z,\delta_i},\ \ \text{where}\ \ \delta_i=1+(i-1)(s+1),\ \ i\in I$$ the preceeding results hold also. \begin{center} \begin{table} \begin{tabular}{cc ccc cc} \hline $p_{1,1}$&$p_{2,2}$&$p_{3,3}$& $\cdots$ & $p_{i,i}$&$\cdots$&$p_{s,s}$\\ \hline $p_{Z,1}$&$p_{Z,s+2}$&$p_{Z,2s+3}$&$\cdots$ &$p_{Z,(i-1)s+i}$&$\cdots$&$p_{Z,s^2}$\\ \hline \end{tabular} \vspace{3ex} \caption{Illustration of the case $s=r$ and $i=j$. }\label{tb} \end{table} \end{center} \bigskip \noindent \textbf{(b)} For most of univariate or multivariate entropies, we may have computation problems. So without loss of generality, suppose \begin{equation} \ \ \ p_{Z,k}>0,\ \ \ \forall k\in K \ \ \ \ \ (\textbf{BD}). \label{BD} \end{equation} \bigskip \noindent If Assumption (\ref{BD}) holds, we do not have to worry about summation problems. This explain why Assumption \ref{BD} is systematically used in a great number of works in that topics, for example, in \cite{hall}, \cite{singh}, \cite{kris}, and recently \cite{ba6}, to cite a few.\\ \noindent In the sequel, we denote the following notations for the \textit{p.m.f.}'s : \begin{eqnarray*} &&\textbf{p}_X=(p_{X,i})_{i\in I},\ \ \ \textbf{p}_Y=(p_{Y,j})_{j\in J},\ \\ &&\textbf{p}_{(X,Y)}=(p_{i,j})_{(i,j)\in I\times J},\ \ \text{and}\ \ \ \textbf{p}_Z=(p_{Z,k})_{k\in K}. \end{eqnarray*} \section{Estimation} \label{estimation} \noindent We start by contructing an estimate of the \textit{p.m.f}, $\textbf{p}_Z,$ from an i.i.d. copies of the random variable $Z$ and from there we deduce that of $\textbf{p}_{(X,Y)}$, that of $\textbf{p}_X$, and $\textbf{p}_Y$.\\ \noindent $\textbf{p}_Z$ is not known. Consequently, $\mathcal{E}_{S.m.i}(\textbf{P}_{(X,Y)})$ can not be calculated directly; instead, it needs to be estimated. Let $Z_1,\cdots,Z_n$ be $n$ i.i.d. random variables from $Z$ and according to $\textbf{p}_Z$. \\ \noindent For a given $k\in K$, define the easiest and most objective estimator of $p_{Z,k}$, based on the i.i.d sample $ Z_1,\cdots,Z_n,$ by \begin{eqnarray}\label{pn} \widehat{p}_{Z,k}^{(n)}&=&\frac{1}{n}\sum_{\ell=1}^n1_{z_k}(Z_\ell \end{eqnarray}where $1_{z_k}(Z_\ell)=\begin{cases} 1\ \ \text{if}\ \ Z_\ell=z_k\\ 0\ \ \text{otherwise} \end{cases} $ for any $k\in K$. \\ \noindent Now for a given $(i,j)\in I\times J$, we deduce that an estimate of $\textbf{p}_{(X,Y)}$ based on the i.i.d sample $ Z_1,\cdots,Z_n,$ according to $\textbf{p}_Z$ is given by \begin{equation}\label{pn} \widehat{p}_{i,j}^{(n)}= \widehat{p}_{Z,\delta_{i}^j}^{(n)}=\frac{1}{n}\sum_{\ell=1}^n1_{z_{\delta_i^j}}(Z_\ell) \end{equation} where $1_{z_{\delta_i^j}}(Z_\ell)=\begin{cases} 1\ \ \text{if}\ \ Z_\ell=z_{\delta_i^j}\\ 0\ \ \text{otherwise} \end{cases}$ for any $(i,j)\in I\times J$.\\ \noindent And for fixed $i\in I$ and $j\in J$, estimates of the \textit{m.p.m.f.}'s $p_{X,i}$ and $p_{Y,j}$ from a sample $Z_1,Z_2,\cdots,Z_n$ of i.i.d. random variables of size n according to $p_{Z}$ are also construct by \begin{eqnarray}\label{pxyest} \widehat{p}_{X,i}^{(n)}&= \sum_{j=1}^s\widehat{p}_{Z,\delta_{i}^j}^{(n)}\ \ \ \text{and}\ \ \ \widehat{p}_{Y,j}^{(n)} \sum_{i=1}^r\widehat{p}_{Z,\delta_{i}^j}^{(n)}. \end{eqnarray} \noindent Before we state our main results we recal some results and introduce notations useful in the sequel. \\ \noindent Recall that, since for a fixed $k\in K,$ $n\widehat{p}_{Z,k}^{(n)}$ has a binomial distribution with parameters $n$ and success probability $p_{Z,k}$, we have \begin{equation*} \mathbb{E}\left[ \widehat{p}_{Z,k}^{(n)}\right]=p_{Z,k} \ \ \text{and}\ \ \mathbb{V}(\widehat{p}_{Z,k}^{(n)})=\frac{p_{Z,k} (1-p_{Z,k} )}{n}. \end{equation*} \noindent Denote \begin{eqnarray*} \Delta_{p_{Z,k}}^{(n)} =\widehat{p}_{Z,k}^{(n)}- p_{Z,k} ,\ \ \rho_n(p_{Z,k})=\sqrt{n/p_{Z,k}}\Delta_{p_{Z,k}}^{(n)} , \end{eqnarray*} and $ a_{Z,n}=\sup_{k\in K}\left\vert \Delta_{p_{Z,k}}^{(n)} \right\vert.$\\ \noindent For a given $k\in K$, this empirical estimator $\widehat{p}_{Z,k}^{(n)}$ of $ p_{Z,k} $ is strongly consistent that is \begin{equation}\label{pzn} \Delta_{p_{Z,k}}^{(n)}=\widehat{p}_{Z,k}^{(n)}- p_{Z,k} \stackrel{a.s.}{\longrightarrow} 0,\ \ \text{as}\ \ n\rightarrow +\infty. \end{equation} \noindent And finally, by the asymptotic Gaussian limit of the multinomial law (see for example \cite{ips-wcia-ang}, Chapter 1, Section 4), we have \begin{eqnarray} \label{pnj}&& \biggr( \rho_n(p_{Z,k}), \ k\in K\biggr) \stackrel{\mathcal{D}}{\rightsquigarrow }G(\textbf{p}_Z),\ \ \ \ \text{as}\ \ n\rightarrow +\infty, \end{eqnarray}where $G(\textbf{p}_Z)= (G_{p_{Z,k}},k\in K)^t\stackrel{d }{\sim}\mathcal{N}(0,\Sigma_{\textbf{p}_Z}),$ and $\Sigma_{\textbf{p}_Z}$ is the covariance matrix which elements are : \begin{eqnarray}\label{vars} &&\sigma_{(k,k')}=(1-p_{Z,k} )1_{(k=k')}-\sqrt{ p_{Z,k}p_{Z,k'} } 1_{(k\neq k')}, \ \ (k,k') \in K^2. \end{eqnarray} \bigskip \noindent Meaning that \begin{equation}\label{npzn} \sqrt{n}(\widehat{p}_{Z,k}^{(n)}- p_{Z,k})\stackrel{\mathcal{D} }{\rightsquigarrow}\mathcal{N}\left( 0, \sigma_{\textbf{p}_{Z}}^2\right), \ \ \text{as}\ \ n\rightarrow+\infty \end{equation}where \begin{eqnarray*}\sigma_{\textbf{p}_Z}^2= \sum_{k\in K} p_{Z,k}(1-p_{Z,k}) -2 \sum_{(k,k')\in K^2}\left(p_{Z,k}p_{Z,k'}\right)^{3/2}. \end{eqnarray*} \bigskip \noindent We denote by $\stackrel{a.s.}{ \longrightarrow}$ the \textit{almost sure convergence} and $\stackrel{\mathcal{D}}{ \rightsquigarrow} $ the \textit{convergence in distribution}. The notation $\stackrel{d }{\sim}$ denote the \textit{equality in distribution}. \\ \noindent Let state two Lemmaes that will be useful in the sequel. \\ For fixed $(i,j)\in I\times J$, denote \begin{eqnarray*} &&\Delta_{p_{X,i}}^{(n)}=\widehat{p}_{X,i}^{(n)}-p_{X,i},\ \ \ \Delta_{p_{Y,j}}^{(n)}=\widehat{p}_{Y,j}^{(n)}-p_{Y,j},\\ &&a_{X,n}=\sup_{i\in I}\left\vert \Delta_{p_{X,i}}^{(n)} \right\vert,\ \ \text{and}\ \ \ a_{Y,n}=\sup_{j\in J}\left\vert \Delta_{p_{Y,j}}^{(n)} \right\vert \end{eqnarray*}and \begin{eqnarray*} \label{sg1i}\sigma_{X,i}^2&=&\sum_{j=1}^sp_{Z,\delta_{i}^j} (1- p_{Z,\delta_{i}^j} )-2\sum_{(j,j')\in J^2,\,j\neq j'}\left(p_{Z,\delta_{i}^j}p_{Z,\delta_{i}^{j'}}\right)^{3/2},\\ \label{sg2i}\text{and}\ \ \sigma_{Y,j}^2&=&\sum_{i=1}^rp_{Z,\delta_{i}^j} (1- p_{Z,\delta_{i}^j} )-2\sum_{(i,i')\in I^2,\,i\neq i'}\left(p_{Z,\delta_{i}^j}p_{Z,\delta_{i'}^{j}}\right)^{3/2}. \end{eqnarray*} \begin{lemma}For fixed $(i,j)\in I\times J$, we have \begin{eqnarray} &&\Delta_{p_{X,i}}^{(n)} \stackrel{a.s.}{\longrightarrow} 0,\ \ \ \label{pyn2} \Delta_{p_{Y,j}}^{(n)} \stackrel{a.s.}{\longrightarrow} 0,\\ &&\label{pxn2}\sqrt{n}\Delta_{p_{X,i}}^{(n)}\stackrel{\mathcal{D}}{\rightsquigarrow}\mathcal{N}(0,\sigma_{X,i}^2 ),\ \ \text{and}\ \ \sqrt{n}\Delta_{p_{Y,j}}^{(n)}\stackrel{\mathcal{D}}{\rightsquigarrow}\mathcal{N}(0,\sigma_{Y,j}^2 ). \end{eqnarray} \end{lemma} \noindent \eqref{pyn2} is a direct application of \eqref{pzn} since we have \begin{equation}\label{axzyn} a_{X,n}\leq a_{Z,n}\ \ \text{and}\ \ a_{Y,n}\leq a_{Z,n},\ \ \forall n\in \mathbb{N}^{\ast}, \end{equation} whereas \eqref{pxn2} follows from \eqref{pnj}.\\ \bigskip \noindent From \eqref{pnj}, we have the following Lemma.\\ Denote \begin{eqnarray*} \sigma_{\textbf{p}}^2= \sum_{(i,j)\in I\times J} p_{Z,\delta_i^j}(1-p_{Z,\delta_i^j}) -2\ \sum_{\begin{tabular}{c} $((i,j),(i',j'))\in (I\times J)^2$\\ $ (i,j)\neq (i',j')$ \end{tabular} }\left(p_{Z,\delta_i^j}p_{Z,\delta_{i'}^{j'}}\right)^{3/2}. \end{eqnarray*} \begin{lemma} \begin{eqnarray}\label{npzn} \sqrt{n}( \widehat{p}_{Z}^{(n)}-p_{Z}) \stackrel{\mathcal{D} }{\rightsquigarrow} \mathcal{N}\left( 0, \sigma_{\textbf{p}}^2\right) ,\ \ \text{as}\ \ n\rightarrow+\infty. \end{eqnarray} \end{lemma} \bigskip \bigskip \noindent Now a simple way to estimate joint entropy $\mathcal{E}(\textbf{p}_{(X,Y)})$ and \textit{S.m.i.} $\mathcal{E}_{S.m.i.}(\textbf{p}_{(X,Y)})$ of the pair $(X,Y)$, is to use the plug-in method meaning that we replace the \textit{p.m.f.}, $p_{Z,\delta_i^j}$, of the random variable $Z$ by $ \widehat{p}_{Z,\delta_i^j}^{(n)}$ in their expressions.\\ \noindent Then given an i.i.d. sample $Z_1,Z_2,\cdots, Z_n$ from $\textbf{p}_Z$, the plug-in estimates of the joint entropy and of the \textit{S.m.i.} of the pair $(X,Y)$ are respectively : \begin{eqnarray*} && \mathcal{E}(\widehat{\textbf{p}}_{(X,Y)}^{(n)} =-\sum_{(i,j)\in I\times J}\widehat{p}_{Z,\delta_i^j}^{(n)}\log \left(\widehat{p}_{Z,\delta_i^j}^{(n)}\right),\\ && \mathcal{E}_{S.m.i.}(\widehat{\textbf{p}}_{(X,Y)}^{(n)} =\sum_{(i,j)\in I\times J}\widehat{p}_{Z,\delta_i^j}^{(n)}\log \frac{ \widehat{p}_{Z,\delta_i^j}^{(n)}}{\widehat{p}_{X,i}^{(n)}\, \widehat{p}_{Y,j}^{(n)}} \end{eqnarray*} \section{Mains results}\label{mainresults} \noindent We are now ready to present asymptotic limit for the joint entropy and \textit{S.m.i.} estimators of the pair ($X,Y)$ and based on an i.i.d sample $Z_1,Z_2,\cdots,Z_n$ sized $n$ according to $p_{Z}$.\\ \bigskip \noindent Theorem \ref{jent} and Theorem \ref{thmut} are about estimators of $\mathcal{E}(\widehat{\textbf{p}}_{Z,n} )$ and $\mathcal{E}_{S.m.i.}( \widehat{\textbf{p}}_{Z,n} )$. They state that these estimators are strongly consistent and asymptotically normal. \\ \noindent Denote \begin{eqnarray*} A(\textbf{p}_Z)&=&\sum_{k\in K}\left\vert 1+ \log ( p_{Z,k} )\right \vert\\ \text{and}\ \ \ \sigma^2(\textbf{p}_Z)&=&\sum_{k\in K} p_{Z,k}(1- p_{Z,k} )(1+ \log ( p_{Z,k} ))^2\\ &&\ \ \ \ \ \ \ \ \ - \ \ 2 \ \sum_{(k,k')\in K^2,k\neq k'}(p_{Z,k}p_{Z,k'})^{3/2}(1+\log (p_{Z,k}))(1+\log (p_{Z,k'})).\end{eqnarray*} \begin{theorem} \label{jent} Let $\textbf{p}_Z=(p_{Z,k})_{k\in K}$ the probability distribution defined in Section \ref{maincontrib} and $\textbf{p}_{Z,n}=(p_{Z,k}^{(n)})_{k\in K}$ be generated by i.i.d. sample $Z_1,\cdots,Z_n$ copies of a random variable $Z$ according to $\textbf{p}_Z$ and given by \eqref{pn}. Then the following hold \begin{eqnarray} \limsup_{n\rightarrow +\infty}\frac{| \mathcal{E}(\widehat{ \textbf{p}}_{(X,Y)}^{(n)})-\mathcal{E}(\textbf{p}_{(X,Y)})|}{ a_{Z,n} }\leq A(\textbf{p}_Z),\ \ \text{a.s.}. \end{eqnarray} \begin{eqnarray} \sqrt{n}\left( \mathcal{E}(\widehat{ \textbf{p}}_{(X,Y)}^{(n)})-\mathcal{E}(\textbf{p}_{(X,Y)}) \right)\stackrel{\mathcal{D}}{ \rightsquigarrow} \mathcal{N}(0,\sigma^2(\textbf{p}_Z)),\ \ \text{as}\ \ n\rightarrow +\infty. \end{eqnarray} \end{theorem} \begin{proof} The proof is similar to that of the Corollaries 2 and 3 in \cite{ba6} and is, therefore, omitted. \end{proof} \bigskip\noindent Denote $$B_{i,j}=\log \frac{ p_{Z,\delta_i^j}}{p_{X,i}\, p_{Y,j}}, \ \ (i,j)\in I\times J$$ and \begin{eqnarray*} \sigma_{\textbf{p}_{(X,Y)}}^2&=&\sum_{(i,j)\in I\times J} p_{Z,\delta_i^j}(1-p_{Z,\delta_i^j})\left(B_{i,j}\right)^2 -2\ \sum_{\begin{tabular}{c} $((i,j),(i',j'))\in (I\times J)^2$\\ $ (i,j)\neq (i',j')$ \end{tabular} } \left(p_{Z,\delta_i^j}p_{Z,\delta_{i'}^{j'}}\right)^{3/2}B_{i,j}B_{i',j'}. \end{eqnarray*} \begin{theorem}\label{thmut} Let $\textbf{p}_Z=(p_{Z,k})_{k\in K}$ the probability distribution defined in Section \ref{maincontrib} and $\textbf{p}_{Z,n}=(p_{Z,k}^{(n)})_{k\in K}$ be generated by i.i.d. sample $Z_1,\cdots,Z_n$ copies of a random variable $Z$ according to $\textbf{p}_Z$ and given by \eqref{pn}. As $n\rightarrow \infty$, the following hold \begin{eqnarray} &&\label{asipz1} \mathcal{E}_{S.m.i.}(\widehat{\textbf{p}}_{(X,Y)}^{(n)})-\mathcal{E}_{S.m.i.}(\textbf{p}_{(X,Y)})\stackrel{a.s.}{\longrightarrow} 0\\ &&\label{nipz} \sqrt{n}(\mathcal{E}_{S.m.i.}(\widehat{\textbf{p}}_{(X,Y)}^{(n)})-\mathcal{E}_{S.m.i.}(\textbf{p}_{(X,Y)}))\stackrel{\mathcal{D} }{\rightsquigarrow}\mathcal{N}\left(0,\sigma_{\textbf{p}_{(X,Y)}}^2\right). \end{eqnarray} \end{theorem} \begin{proof} \noindent Let us start by proving \eqref{asipz1}. \\ \noindent Given $Z_1,Z_2,\cdots,Z_n$ $n$ i.i.d. randoms variables from $Z$ according to $\textbf{p}_Z$, we have \begin{eqnarray}\label{asipz} \notag \mathcal{E}_{S.m.i.}(\widehat{\textbf{p}}_{(X,Y)}^{(n)})-\mathcal{E}_{S.m.i.}(\textbf{p}_{(X,Y)})&=&\sum_{(i,j)\in I\times J}\widehat{p}_{Z,\delta_i^j}^{(n)}\log \frac{ \widehat{p}_{Z,\delta_i^j}^{(n)} }{\widehat{p}_{X,i}^{(n)}\,\widehat{p}_{Y,j}^{(n)}}-\sum_{(i,j)\in I\times J}p_{Z,\delta_i^j}\log \frac{ p_{Z,\delta_i^j}}{p_{X,i}\, p_{Y,j}}\\ \notag &=&\sum_{(i,j)\in I\times J}\biggr( \widehat{p}_{Z,\delta_i^j}^{(n)}\log \frac{ \widehat{p}_{Z,\delta_i^j}^{(n)} }{\widehat{p}_{X,i}^{(n)}\,\widehat{p}_{Y,j}^{(n)}}-\widehat{p}_{Z,\delta_i^j}^{(n)}\log \frac{ p_{Z,\delta_i^j}}{p_{X,i}\, p_{Y,j}} \\ \notag &&\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ +\ \ \ \ \widehat{p}_{Z,\delta_i^j}^{(n)}\log \frac{ p_{Z,\delta_i^j}}{p_{X,i}\, p_{Y,j}} - p_{Z,\delta_i^j}\log \frac{ p_{Z,\delta_i^j}}{p_{X,i}\, p_{Y,j}} \biggr)\\ &=& \sum_{(i,j)\in I\times J}\widehat{p}_{Z,\delta_i^j}^{(n)}A_{i,j}^{(n)}\ \ \ +\ \ \ \sum_{(i,j)\in I\times J}( \widehat{p}_{Z,\delta_i^j}^{(n)}-p_{Z,\delta_i^j})B_{i,j}. \end{eqnarray}where \begin{eqnarray*} A_{i,j}^{(n)}&=&\log \frac{ \widehat{p}_{Z,\delta_i^j}^{(n)} }{\widehat{p}_{X,i}^{(n)}\,\widehat{p}_{Y,j}^{(n)}}-\log \frac{ p_{Z,\delta_i^j}}{p_{X,i}\, p_{Y,j}}\ \ \ \text{and}\ \ \ B_{i,j}=\log \frac{ p_{Z,\delta_i^j}}{p_{X,i}\, p_{Y,j}}, \ \ (i,j)\in I\times J. \end{eqnarray*} \noindent We have \begin{eqnarray*} \left\vert \mathcal{E}_{S.m.i.}(\widehat{\textbf{p}}_{(X,Y)}^{(n)})-\mathcal{E}_{S.m.i.}(\textbf{p}_{(X,Y)})\right\vert &\leq &\sum_{(i,j)\in I\times J}\widehat{p}_{Z,\delta_i^j}^{(n)} \left\vert A_{i,j}^{(n)}\right\vert \ \ \ +\ \ \ a_{Z,n}\sum_{(i,j)\in I\times J}B_{i,j}. \end{eqnarray*} \noindent Using \eqref{pzn} $$a_{Z,n}\sum_{(i,j)\in I\times J}B_{i,j}\stackrel{a.s.}{\longrightarrow}0,\ \ \text{as}\ \ n\rightarrow +\infty.$$ \noindent The following consists of handling each of these two terms.\\ \noindent We have at first \begin{equation}\label{aij} A_{i,j}^{(n)}=\log \frac{ \widehat{p}_{Z,\delta_i^j}^{(n)} }{ p_{Z,\delta_i^j}}-\log \frac{\widehat{p}_{X,i}^{(n)}\,}{p_{X,i}}-\log \frac{ \widehat{p}_{Y,j}^{(n)}}{ p_{Y,j}}. \end{equation} \noindent Second, to give an upper bound of $\left \vert A_{i,j}^{(n)}\right\vert $, we first notice that, for $n$ large enough, we have \begin{eqnarray}\label{inepn} p_{Z,\delta_i^j}-a_{Z,n}\leq \widehat{p}_{Z,\delta_i^j}^{(n)}\leq p_{Z,\delta_i^j}+a_{Z,n}, \end{eqnarray}hence \begin{equation}\label{ineazxy} 1-\frac{a_{Z,n}}{p_{Z,\delta_i^j}}\leq \frac{ \widehat{p}_{Z,\delta_i^j}^{(n)} }{p_{Z,\delta_i^j}}\leq 1+\frac{a_{Z,n}}{p_{Z,\delta_i^j}}, \end{equation}and similarly, we have also \begin{eqnarray} && 1-\frac{a_{Z,n}}{p_{X,i}}\leq \frac{ \widehat{p}_{X,i}^{(n)} }{p_{X,i}}\leq 1+\frac{a_{Z,n}}{p_{X,i}} \ \ \text{and}\ \ \label{ineazxy1} 1-\frac{a_{Z,n}}{p_{Y,j}}\leq \frac{ \widehat{p}_{Y,j}^{(n)} }{p_{Y,j}}\leq 1+\frac{a_{Z,n}}{p_{Y,j}}. \end{eqnarray} Then we upperbound $\left \vert A_{i,j}^{(n)}\right\vert $ by combining \eqref{ineazxy} and \eqref{ineazxy1} and we get for $n$ large enough \begin{eqnarray} \left\vert A_{i,j}^{(n)}\right\vert &\leq & \log \left(1+\frac{a_{Z,n}}{p_{Z,\delta_i^j}}\right) +\log \left(1+\frac{a_{Z,n}}{p_{X,i}}\right)+\log \left(1+\frac{a_{Z,n}}{p_{Y,j}}\right). \end{eqnarray} \noindent Therefore \begin{eqnarray}\label{anij2} \left\vert A_{i,j}^{(n)}\right\vert &\leq & a_{Z,n}\left( \frac{1}{p_{Z,\delta_i^j}}+\frac{1}{p_{X,i}}+\frac{1}{p_{Y,j}} \right), \end{eqnarray}using the approximation $\log (1+x)\approx x$. Hence \begin{equation}\label{aijn} A_{i,j}^{(n)}\stackrel{a.s}{\longrightarrow}0,\ \ \text{as} \ \ n\rightarrow+\infty. \end{equation} Combining this with \eqref{inepn}, we get \begin{equation*} \mathcal{E}_{S.m.i.}(\widehat{\textbf{p}}_{(X,Y)}^{(n)})-\mathcal{E}_{S.m.i.}(\textbf{p}_{(X,Y)}) \stackrel{a.s}{\longrightarrow}0,\ \ \text{as} \ \ n\rightarrow+\infty, \end{equation*} which proves \eqref{asipz1}.\\ \noindent Let prove \eqref{nipz}. By going back to \eqref{asipz}, we have that $$\sqrt{n}(\mathcal{E}_{S.m.i.}(\widehat{\textbf{p}}_{(X,Y)}^{(n)})-\mathcal{E}_{S.m.i.}(\textbf{p}_{(X,Y)}))=\sum_{(i,j)\in I\times J}\widehat{p}_{Z,\delta_i^j}^{(n)}\sqrt{n} A_{i,j}^{(n)}\ \ \ +\ \ \ \sum_{(i,j)\in I\times J}B_{i,j}\sqrt{n}\left( \widehat{p}_{Z,\delta_i^j}^{(n)}-p_{Z,\delta_i^j}\right)$$ \noindent Let show that $\sqrt{n} A_{i,j}^{(n)}$ converges to $0$ in probability as $n$ tends to $+\infty$.\\ \noindent Using \eqref{anij2}, we get, for any $ (i,j)\in I\times J$, \begin{eqnarray*}\label{raii} |\sqrt{n}A_{i,j}^{(n)}|&\leq & \sqrt{n}a_{Z,n}\left( \frac{1}{p_{Z,\delta_i^j}}+\frac{1}{p_{X,i}}+\frac{1}{p_{Y,j}} \right). \end{eqnarray*} \noindent By the Bienaym\'e-Tchebychev inequality, we have, for any fixed $\varepsilon >0$ and for any $(i,j)\in I\times J$ \begin{eqnarray*} \mathbb{P}\left(\sqrt{n}| \widehat{p}_{Z,\delta_i^j}^{(n)}-p_{Z,\delta_i^j} | \geq \varepsilon \right)\leq \frac{p_{Z,\delta_i^j} (1- p_{Z,\delta_i^j} )}{\varepsilon^2 n}. \end{eqnarray*} \noindent Hence $\sqrt{n}a_{Z,n}=o_{\mathbb{P}}(1)$ and $\sqrt{n}A_{i,j}^{(n)}\stackrel{\mathbb{P}}{\longrightarrow}0\ \ \text{as}\ \ n\rightarrow+\infty.$\\ \noindent Therefore $$\sum_{(i,j)\in I\times J}\widehat{p}_{Z,\delta_i^j}^{(n)}\sqrt{n} A_{i,j}^{(n)}\stackrel{\mathbb{P}}{\longrightarrow}0\ \ \text{as}\ \ n\rightarrow+\infty.$$ \bigskip \noindent Now using \eqref{pnj}, we get \begin{eqnarray*} \sum_{(i,j)\in I\times J}B_{i,j}\sqrt{n}( \widehat{p}_{Z,\delta_i^j}^{(n)}-p_{Z,\delta_i^j})&=&\sum_{(i,j)\in I\times J}\sqrt{p_{Z,\delta_i^j}} B_{i,j}\rho_n (p_{Z,\delta_i^j})\\ &&\stackrel{\mathcal{D} }{\rightsquigarrow}\sum_{(i,j)\in I\times J}B_{i,j} \sqrt{p_{Z,\delta_i^j}} G_{p_{Z,\delta_i^j}},\ \ \text{as}\ \ n\rightarrow+\infty, \end{eqnarray*} which follows a centered normal law of variance $\sigma_{\textbf{p}_{(X,Y)}}^2$ since \begin{eqnarray*} \text{Var}\left(\sum_{(i,j)\in I\times J}B_{i,j} \sqrt{p_{Z,\delta_i^j}} G_{p_{Z,\delta_i^j}}\right) &=& \sum_{(i,j)\in I\times J} p_{Z,\delta_i^j}(1-p_{Z,\delta_i^j})\left(B_{i,j}\right)^2\\ &&\ \ \ \ \ \ \ -2\ \sum_{\begin{tabular}{c} $((i,j),(i',j'))\in (I\times J)^2$\\ $ (i,j)\neq (i',j')$ \end{tabular} }\left(p_{Z,\delta_i^j}p_{Z,\delta_{i'}^{j'}}\right)^{3/2}B_{i,j}B_{i',j'} \end{eqnarray*} which ends the proof of Theorem \ref{thmut}. \end{proof} \noindent In the special case where data are of the form $(x_i,y_i)_{i\in I} $, denote $$B_{i}=\log \frac{ p_{Z,\delta_i}}{p_{X,i}\, p_{Y,i}}, \ \ i\in I$$ and \begin{eqnarray*} \sigma_{\textbf{p}_{(X,Y)}}^2&=&\sum_{i\in I} p_{Z,\delta_i}(1-p_{Z,\delta_i})\left(B_{i}\right)^2 -2\ \sum_{\begin{tabular}{c} $(i,i')\in I^2$\\ $ i\neq i'$ \end{tabular} } \left(p_{Z,\delta_i}p_{Z,\delta_{i'}}\right)^{3/2}B_{i}B_{i'}. \end{eqnarray*} We have \begin{theorem}\label{thmut2} As $n\rightarrow \infty$, the following hold \begin{eqnarray} &&\label{asipz2} \mathcal{E}_{S.m.i.}(\widehat{\textbf{p}}_{(X,Y)}^{(n)})-\mathcal{E}_{S.m.i.}(\textbf{p}_{(X,Y)})\stackrel{a.s.}{\longrightarrow} 0\\ &&\label{nipz2} \sqrt{n}(\mathcal{E}_{S.m.i.}(\widehat{\textbf{p}}_{(X,Y)}^{(n)})-\mathcal{E}_{S.m.i.}(\textbf{p}_{(X,Y)}))\stackrel{\mathcal{D} }{\rightsquigarrow}\mathcal{N}\left(0,\sigma_{\textbf{p}_{(X,Y)}}^2\right). \end{eqnarray} \end{theorem} \section{Test for independence using \textit{S.m.i.}}\label{testindep} \noindent \textit{S.m.i} is an information theoretic measure of dependency between two random variables (see \cite{cover} and \cite{shan2}). Unlike correlation, which characterizes linear dependence, \textit{S.m.i} is completely general. It can be viewed as a statistical test against a null hypothesis that two variables are statistically independent.\\ \noinden Let $X$ and $Y$ two discrete random variables. \textit{S.m.i} of the pair $X,Y)$ possesses the following desirable properties. It is always nonnegative, i.e., $\mathcal{E}_{S.m.i.}(\textbf{p}_{(X,Y)})\geq 0$, and equality holds if and only if the two variables are independent. Therefore we can construct an independence test based on the following hypotheses: \begin{eqnarray*} &&H_0: \mathcal{E}_{S.m.i.}(\textbf{p}_{(X,Y)})=0,\\ \text{versus}&& \ \\ && H_1: \mathcal{E}_{S.m.i.}(\textbf{p}_{(X,Y)})>0. \end{eqnarray*} \noindent Tests based on asymptotic distributions require data with large sample size. For a random sample of $n$ observations independent and identically distributed copies $Z_1,\cdots,Z_n$ of $Z$, calculate the S.m.i. estimator, $\mathcal{E}_{S.m.i.}(\widehat{ \textbf{p}}_{(X,Y)}^{(n)})$.\\ \noindent Consider now the \textit{likelihood ratio test statistic} of the null hypothesis of the independence of X and Y, namely \begin{equation} \gamma_n^2=2n\sum_{(i,j)\in I\times J}\widehat{p}_{Z,\delta_i^j}^{(n)}\log \frac{ \widehat{p}_{Z,\delta_i^j}^{(n)} }{\widehat{p}_{X,i}^{(n)}\, \,\widehat{p}_{Y,j}^{(n)}} ,\label{rat} \end{equation} see \cite{chri}. \noindent From classical statistical theory, under $H_0$, $\gamma_n^2$ is asymptotically chi-square distributed $\chi_{(r-1)(s-1)}^2$ with $(r-1)(s-1)$ degrees of freedom, i.e. under $H_0$, we have $$\gamma_n^2\stackrel{\mathcal{D} }{\rightsquigarrow}\chi_{(r-1)(s-1)}^2,\ \ \text{as}\ \ n\rightarrow+\infty.$$ \noindent The distribution of $2n\mathcal{E}_{S.m.i.}(\widehat{\textbf{p}}_{(X,Y)}^{(n)})$ , under the null hypothesis $H_0$, can be approximated by the empirical distribution of $ \chi_{(r-1)(s-1)}^2$.\\ \noindent Given a \textit{significance level} $\alpha , let $\chi_{(r-1)(s-1)}^2(\alpha)$ be the $(1-\alpha)$th quantile of the \textit{Chi-squared distribution . \\ \noindent We reject the null hypothesis when $$\mathcal{E}_{S.m.i.}(\widehat{\textbf{p}}_{(X,Y)}^{(n)})>\frac{1}{2n}\chi_{(r-1)(s-1)}^2(\alpha).$$ \section{Simulation}\label{simulat} \noindent In this section, we present a example to demonstrate the consistency and the asymptotic normality of the proposed joint entropy and Shannon mutual information estimators. \\ \noindent For simplicity consider two discretes random variables $X$ and $Y$ having each one two outcomes $x_1,x_2$ and $y_1,y_2$ and such that \begin{eqnarray*} &&\mathbb{P}(X=x_1,Y=y_1)=0.2,\ \ \ \mathbb{P}(X=x_1,Y=y_2)=0.4\\ &&\mathbb{P}(X=x_2,Y=y_1)=0.1,\ \ \text{and}\ \ \mathbb{P}(X=x_2,Y=y_2)=0.3. \end{eqnarray*} \noindent We have \begin{eqnarray*} &&\mathcal{E}(\textbf{p}_{(X,Y)})= 1.279854\,\text{nats}\ \ \text{and} \ \ \mathcal{E}_{S.m.i.}(\textbf{p}_{(X,Y)}) = 0.004021\, \text{nats}, \end{eqnarray*} \noindent meaning that the variables $X$ and $Y$ seem not to have a lot of information in common, only $0.004021\, \text{nats}$ of information. \vspace{2ex} \begin{table} \centering \begin{tabular}{|c|c|c|c|c|c|} \hline $(X,Y)$&$(x_1,y_1)$&$(x_1,y_2)$&$(x_2,y_1)$&$(x_2,y_2)$\\ $p_{Z,k}$&0.2&0.4&0.1&0.3\\ \hline \end{tabular} \vspace{3ex} \caption{Joint p.m.f. table of $Z=(X,Y)$} \label{tab2} \end{table} \noindent Construct the \textsc{Table} \ref{tab2} to define the probability distribution $\textbf{p}_Z$, of $Z$. Now let $Z_1,Z_2,\cdots, Z_n$ be an i.i.d. sample of size $n$ from $\textbf{p}_Z$ and construct the joint entropy estimator $\mathcal{E}(\widehat{\textbf{p}}_{(X,Y)}^{(n)})$ and \textit{S.m.i.} estimator $\mathcal{E}_{S.m.i.}(\widehat{\textbf{p}}_{(X,Y)}^{(n)})$ of the pair $(X,Y)$. \noindent \textsc{Figure} \ref{jointentrop} concerns the joint entropy estimator $\mathcal{E}(\widehat{\textbf{p}}_{(X,Y)}^{(n)})$ whereas \textsc{Figure} \ref{smut} concerns that of S.m.i. estimator $\mathcal{E}_{S.m.i.}(\widehat{\textbf{p}}_{(X,Y)}^{(n)})$ of the pair $(X,Y)$. \noindent In each of these \textsc{F}igures, left panels represent plot of the proposed entropy estimator, built from sample sizes of $n=100,200,\cdots,30000$, and the true entropy of the pair $(X,Y)$ (represented by horizontal black line). We observe that when the sample sizes $n$ increase, then the proposed estimator value converges almost surely to the true value. \\ \noindent Middle panels show the histogram of the data and where the red line represents the plots of the theoretical normal distribution calculated from the same mean and the same standard deviation of the data.\\ \noindent Right panels concern the Q-Q plot of the data which display the observed values against normally distributed data (represented by the red line). We observe that the underlying distribution of the data is normal since the points fall along a straight line. \begin{center} \begin{figure}[H] \includegraphics[scale=0.26]{joint-Ent-19-04-06.jpeg} \caption{Plots of joint entropy of the pair ($X,Y)$ when samples sizes increase, histogram and normal Q-Q plots versus $\mathcal{N}(0,1)$.}\label{jointentrop} \end{figure} \begin{figure}[H] \includegraphics[scale=0.26]{Mutual-info-19-04-06.jpeg} \caption{Plots of S.m.i. estimator of the pair ($X,Y)$ when samples sizes increase, histogram and normal Q-Q plots versus $\mathcal{N}(0,1)$.}\label{smut} \end{figure} \end{center} \section{Conclusion}\label{conclus} This paper presented ongoing research on joint entropy and mutual information estimations of a pair of random variables. We have provided plug-in estimator of joint entropy and Shannon mutual information that are shown to approximate joint entropy and mutual information well. As well as asymptotic normality of estimators have been established. We also construct a test for independence based on the Shannon mutual information.
{'timestamp': '2019-06-18T02:05:45', 'yymm': '1906', 'arxiv_id': '1906.06484', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06484'}
arxiv
\section{Background}\label{background} \subsection{Inductive Logic Programming (ILP)} The Inductive Logic Programming (ILP) main challenge, as defined in \cite{muggleton91inductive}, is to search for a logical description (a hypothesis, $H$) of a target concept, based on set of (positive and negative) examples along with a set called background knowledge ($BK$). The central idea is that $H$ is a \emph{consistent hypothesis}, i.e. $BK$ plus the hypothesis $H$ entails the positive examples ($e^{+}$), whilst does not entail the negative ones ($e^{-}$). Formally, $BK \cup \{H \}\vdash e^{+}$ and $BK \cup \{H \} \not \vdash e^{-}$. Typical ILP systems implement search strategies over the space of all possible hypotheses. To reduce search complexity, such mechanisms rely on partial order of $\theta$-subsumption \cite{nienhuys1997foundations}, or on a total ordering over the Herbrand Base to constrain deductive, abductive and inductive operations \cite{muggleton15meta}. As a side-effect, the space of hypotheses grows even more due to quantification over meta-rules by the meta-interpretive process. The Inductive Clause Learning (ICL) technique is fundamentally different, while its learning results are similar to ILP and MIL. It does not generate hypotheses to then test whether $BK \cup H$ entails positive examples but not the negative ones. Instead, ICL anticipates the elimination of inconsistent hypotheses at each induction step by \textit{colliding} atoms obtained from a search across bindings of constants from $e^{+}$ and $e^{-}$. This is possible because NeMuS is a network of shared spaces (for constant terms, predicates and clauses), interconnected through weighted bindings pointing to the target space in which an occurrence of an element appears. In what follows this is briefly described. \subsection{Shared NeMuS} \label{subsec:revisitingNeMuS} NeMuS is an ordered space for components of a first-order language: variables (space 0), atomic constants of the Herbrand Universe (space 1), functions (space 2, suppressed here), predicates with literal instances (space 3), and clauses (space 4), and so on. In what follows vectors are written $\vect{v}$, and $\vect{v}[i]$ or $\vect{v}_i$ is used to refer to an element of a vector at position $i$. Each logical element is described by a vector called T-Node, and in particular each element is uniquely identified by an integer code (an index) within its space. In addition, a T-Node identifies the lexicographic occurrence of the element, and (when appropriate) an attribute position. \newtheorem{TNode}{Definition} \begin{TNode}[T-Node] Let $c \in \mathbb{Z}$, $a, i \in \mathbb{Z}^{+}$ and $h, \in \mathbb{N}$. A {\em T-Node (target node)\/} is a quadruple $(h, c, i, a)$ that identifies an object at space $h$, with code $c$ and occurrence $i$, at attribute position $a$ (when it applies, otherwise 1). ${\cal T}_{N}$ is the set of all T-Nodes. For a vector $\vect{x}$, of T-Nodes, with size $n$, and $c$ is a code occurring in an element of $\vect{x}$, then $\iota(c, \vect{x}) = k$ is the index of $c$ within the T-Node, $0 \leq k \leq (n-1)$. \end{TNode} As T-Nodes are the building block of our approach, all other elements follows from it and we describe as follows. \begin{description} \item [NeMuS Binding] is an indexed pair $(p,w)_k$ in which $p \in {\cal T}_{N}$, $w \in \mathbb{R}$ and $k \in \mathbb{Z}^{+}$, such that $n_{h}(p) = h$, $n_{c}(p) = c$, $n_{a}(p) = a$ and $n_i(p) = i$. It represents the importance $w$ of object $k$ over occurrence $n_i(p)$ of object $n_{c}(p)$ at space $n_{h}(p)$ in position $n_{a}(p)$. \end{description} \begin{description} \item [Variable Space (0)] is a vector $ \vect{V} = [ \vect{y}_1, \ldots, \vect{y}_n ]$, in which each $\vect{y}_i$ is a vector of bindings. The elements of the variable space represent all of the occurrences of a variables. The logical scope of a variable $X$ is identified by the instances of its bindings. \end{description} \begin{description} \item [Constant Space (1)] is a vector $\vect{C} = [ \vect{x}_1, \ldots, \vect{x}_m ]$ , in which every $\vect{x}_i$ is a vector of bindings. The function $\beta$ maps a constant $i$ to the vector of its bindings $\vec{x_i}$, as above. \end{description} Compounds (functions, predicates and clauses), are in higher spaces. Their logical components are formed by a vector of T-Nodes (one for each argument), and a vector of NeMuS bindings (simply bindings) to represent their instances. \begin{description} \item [Compound] in NeMuS is a vector of T-Nodes, i.e. $\vect{x}^{i}_a = [c_1, \ldots, c_m]$, so that each $c_j \in {\cal T}_{N}$, and it represents an attribute of a compound logical expression coded as $i$. \item [Instance Space] (I-Space) of a compound $i$ is the pair $(\vect{x}^{i}_{a}, \vect{w}_i)$ in which $ \vect{w}_i$ is a vector of bindings. A vector of I-Spaces is a NeMuS \emph{Compound Space (C-Space)}. \end{description} A literal (predicate instance), is an element of an I-Space, and so the predicate space is simply a C-Space. Seen as compounds, clauses' attributes are the literals composing such clauses. \begin{description} \item [Predicate Space (3)] is a pair $(\vect{C}^{+}_p, \vect{C}^{-}_p)$ in which $\vect{C}^{+}_p$ and $\vect{C}^{-}_p$ are vectors of C-spaces. \item [Clause Space (4)] is a vector of C-spaces such that every pair in the vector shall be $(\vect{x}^{i}_{a},[ ])$. \end{description} Note that the order of each space is only defined when they are gathered in the following structure. \newtheorem{sharedNeMuS}[TNode]{Definition} \begin{sharedNeMuS}[Shared NeMuS] A \emph{Shared NeMuS} for a set of coded first-order expressions is a 4-tuple (assuming no functions), ${\cal N}: \langle \mathcal{V}, \mathcal{S}, \mathcal{P}, \mathcal{C} \rangle$, in which $ \mathcal{V}$ is the variable space, $\mathcal{S}$ is the constant space, $\mathcal{P}$ is the predicate space and $\mathcal{C}$ is the clause space. \end{sharedNeMuS} The next section describes how inductive learning is performed in Amao using NeMuS structure. \section{Discussion and Future Work}\label{conclusions} This paper has shown how the Amao Shared NeMuS data structure can be used in predicate invention without the need to generate meaningless hypotheses. This is achieved via Inductive Clause Learning, with automatic predicate generation that takes advantage of the degree of importance of constant objects. As atomic object, constants of the Herbrand base had never called much attention for logical inference, but only to validate resolution through unification. Here, we showed how they can be used to guide the search for consistent hypothesis in two ways. First, by walking across their bindings from positive examples which are not rejected by inductive momentum with bindings of negative examples. Second, we use, as a heuristic to a faster generation of potentially recursive hypotheses, the maps or regions of similarities (item 2 of bias for invention), that constant bindings allow us to compute. Such maps as inductive mechanism is demonstrated in \cite{barretoSOIReasoningNeMuS19}. Future works will focus on making more efficient use of weighted structures of concepts and their composition to allow learning and reasoning of complex formulae, as well as dealing with noise, uncertainty, and possible worlds. We then aim to incorporate deep learning-like mechanisms by taking advantage of the inherently interconnected \textit{compound spaces} as a sort of layers for convolution when dealing with massive datasets. \begin{comment} build an inductive logic programming system which has been successfully applied on some small trial examples. The results on inductive learning in Amao show that using its shared structure leads to reliable hypothesis generation in the sense that the minimally correct ones are generated. However, it still generates additional hypothesis, logically sound and correct with respect to the Herbrand base derivation. Most important is the size of the set of hypotheses generated which is small in comparison with the literature, e.g. \cite{bratko11prolog}. Future work will focus on two areas. First, the power of the shared structure to allow a fast implementation of inductive inference. Second, the weights incorporated in the Shared NeMuS structure (not used in the current paper) will be used to play an important role in providing heuristics. In \cite{nemus4NeSy16} it is shown how these weights can be updated in a manner inspired by self-organising maps \cite{kohonenBook}. The propagation across the network of nodes in the structure allows the weights to capture patterns of refutation. It should be possible to capture negative examples in inductive logic programming in the network in this way, guiding search away from these unfruitful regions to fine tune to a small set of generated hypotheses. Alongside improved hypothesis search the use of the weighted structure to drive predicate invention -- to add to the knowledge base additional inferred predicates contained in neither it nor the target predicate -- will be investigated. \end{comment} \subsection*{Acknowledgement} \section{NeMuS-based Inductive Learning}\label{inductive} ICL is based on the concept of Least Herbrand Model (LHM) \cite{lloyd93foundations} to anticipate the elimination of inconsistent hypotheses, at each induction step, before they are fully generated. This is done by \textit{colliding}, via computing the \emph{inductive momentum}, atoms obtained from bindings of arguments from $e^{+}$ (candidates to compose LHM) and $e^{-}$. Then, a pattern of linkage across verified literals is identified, anti-unification (adapted from \cite{idestam93generalization}) is applied, and a conjecture is generated. The process repeats until the conjecture becomes a closed and consistent hypothesis. \subsection{Inductive Learning from the Herbrand Base} \label{aspectsILHB} The problem of inductive learning involves a knowledge base of predicates, called background knowledge ($BK$), a set $E$ of examples that the logical description $H$ of the target concept ($t$) should prove (positive examples, $e^{+}$) and a set of examples that the target concept should not prove (negative examples, $e^{-}$). Figure~\ref{fig:AllHookPathsFromExamples} depicts a possible Herbrand Base that may explain how $H$ entails a positive example for the concept $t$. In its turn, $t$ can be unary ($p(a_k)$), binary ($p(a_k,a_{k1})$), etc. \begin{figure}[h!] \centering \includegraphics[scale=0.9]{./AllHookPaths.png} \caption{Portion of the HB with bindings of $t$'s attributes.} \label{fig:AllHookPathsFromExamples} \end{figure} From attribute bindings of $t$, i.e. $\beta(a_k)$ and possibly $\beta(a_{k1})$, $t$ is connected with attribute mates' bindings. Such connections bridge all concepts they may appear in ($p_1$, $q_1$, etc.), like a path $\{c_1, \ldots, c_j\}$ in a graph, until it reaches the binding concept of $t$'s last attribute. The interconnected concepts form a \emph{linkage pattern}. For example, when $p_1$, $q_1$ etc., are all the same concept, then a recursive hypothesis may be generated. Invention and hypotheses generation and will always take place in the \textit{bridging concepts}' region (including the initial and last binding concepts). The induction method is based on the following aspects: (a) \emph{Inductive momentum} that iteratively ``selects" only those atoms not likely to entail $e^{-}$, (b) \emph{linkage patterns} among atoms passed (a), based on internal connections (bridging concepts); (c) \emph{anti-unification} substitutes constants in an atom from the Herbrand Base by variables (and optionally (d) \emph{category-first ordering}, \cite{categoryBaseLNeMuS4NeSy17}, useful when $BK$ contains monadic definitions of categories). \subsection{Linkage Patterns and Hypothesis} \label{sec:linear-linkpattern} A special form of intersection $\rho$ identifies the common terms between both literals. For instance, in Figure~\ref{fig:AllHookPathsFromExamples}, suppose $j=1$, i.e. bridging concepts has just two literals of the same concept $p_1$: $p_1(a_k, c_1)$ and $p_1(c_{1}, a_{k1})$. Then $\rho(p^{1}_{1},p^{2}_{1})=c_1$. \newtheorem{hook4Indution}[TNode]{Definition} \begin{hook4Indution}[Linkage and Hook-Terms] Let $p$ and $q$ be two predicates of a $BK$. There is a \emph{Linkage} between $p$ and $q$ if a same constant, $t_h$, appears (at least) once in ground instances of $p$ and $q$. We call $t_h$ a \emph{hook-term}, computed by $t_h = \rho(p,q)$. The \emph{attribute mates} $t_h$ w.r.t. an atom $p$, written $\overline{\rho(p,q)}_p$ is a set of terms occurring in $p$, but not in $q$. \end{hook4Indution} With $p^{1}_{1},p^{2}_{1}$ as above, $c_1$ is their hook term and $\overline{\rho(p^{1}_{1},p^{2}_{1})}_{p^{1}_{1}} = \{a_{k}\}$ and $\overline{\rho(p^{1}_{1},p^{2}_{1})}_{p^{2}_{1}} = \{a_{k1}\}$. This would form the definite clause $p(a_k, a_{k1}) \leftarrow p_1(a_k, c_1) \land p_1(c_{1}, a_{k1})$, which is not generated but it is built using anti-unification to generalize over its hooked ground literals. In the following definition we use the standard notion of a substitution $\theta$ as a set of pairs of variables and terms like $\{X_1/t_1, \ldots, X_n/t_n\}$. \newtheorem{antiUnification}[TNode]{Definition} \begin{antiUnification}[Anti-substitution and Anti-unification] Let $G$ be a first-order expression with no constant term and $X_1, \ldots, X_n$ be free variables of $G$, $e$ is a ground first-order expression, and $t_1, \ldots, t_n$ are constants terms of $e$. An \emph{anti-substitution} is a set $\theta^{-1} = \{t_1/X_1, \ldots, t_n/X_n\}$ such that $G = \theta^{-1} e$, and $G$ is called a simple \emph{anti-unification} of $e$. The \emph{anti-unification} $f^{-1}_{\theta}$ maps a ground atom $e$ to its corresponding \emph{anti-substitution} set that generalizes $e$, i.e. $f^{-1}_{\theta}(e) = \theta^{-1}$ \end{antiUnification} Note that in the original definition of anti-unification, \cite{idestam93generalization}, $G$ should be the generalisation of two ground expressions. Here, as we build a hypothesis by adding literals from a definite clause the definition is \newtheorem{ground2General}[TNode]{Definition} \begin{ground2General}[Anti-unification on linkage terms] Given two literals $p(a_k, a_z)$ and $q(a_z, a_{k1})$. A \emph{linkage term}, say $Z_0$, for their hook term $a_z$, is a variable that can be placed, by anti-unification, in the hook's position wherever it appears in the ground instance that will produce two non-ground literals. \end{ground2General} The definite clause $p(a_k, a_{k1}) \leftarrow p_1(a_k, c_1) \land p_1(c_{1}, a_{k1})$, from Figure~\ref{fig:AllHookPathsFromExamples} ($j=1$), $\theta^{-1} = \{a_k/X, a_{k1}/Y, c_{1}/Z \}$ is incrementally anti-unified, and so the following general clause is found: $p(X, Y) \leftarrow p_1(X, Z) \land p_1(Z, Y)$. This concept is the fundamental operation to generate a hypothesis because it generalizes ground formulas into universally quantified ones. Before describing how negative examples are used we have the following definition. \newtheorem{hypothesis}[TNode]{Definition} \begin{hypothesis}[Hypothesis] Let $H$ be a formula with no constant term, $S$ be a set of ground atoms formed by concepts and constants from a Herbrand universe $H_u$, $t$ is a ground atom with $k$ terms (which belongs to the base of constants, $H_0$) such that $t \not \in S$. We say that $H$ is a \emph{hypothesis} for $t$ with respect to $S$ if and only if there is a set of atoms $E = \{e_1, \ldots, e_n \}$ and a $ \theta^{-1}$ such that for \begin{enumerate} \item every $a$ of $t$, there is some $e_i \in E$ and $\rho(t, e_i) = a$ \item every $e_i$ and $e_{i+1}$ $\rho(e_i, e_{i+1})$ is not empty. \item when 1 and 2 hold, then $H = \theta^{-1} (\{t\} \cup E)$. \end{enumerate} An \emph{open hypothesis} is one that at least one term of $t$ have not been anti-unified. Thus, 1, 2 and 3 will always generate a closed least hypothesis. \end{hypothesis} Recall that \emph{learning should involve the generation of a hypothesis and to test it against positive and negative examples}. Such a ``test" could be done while the hypothesis is being generated. This is the fundamental role of the following concept. Note that, in the interest of saving space, the following sections shall use logic notation. It is important, however, to recall the definitions given in section \ref{subsec:revisitingNeMuS}, as the method described runs on top of the Shared NeMuS structure. \subsection{Inductive Momentum} \label{subsec:im} In the following definition, $a_k$ is a constant originating from the path of a positive example, and $b_k$ is another constant originating from a negative example. \newtheorem{inductiveMomentum}[TNode]{Definition} \begin{inductiveMomentum}[Inductive Momentum] Let $(\vect{x}^{i}_a, \vect{w}_i)$ and $(\vect{x}^{j}_a, \vect{w}_j)$ be two I-spaces of atoms $i$ and $j$, representing $l^{+} $ and $l^{-}$ atomic formulas (literals) in the Herbrand base. If $\exists k$ and $m$, from $e^{+}$ and $e^{-}$, such that $l^{+} \in \beta(k)$ and $l^{-} \in \beta(m)$, i.e. $k$ is an element of $\vect{x}^{i}_a$ and $m$ is an element of $\vect{x}^{j}_a$, then the \emph{inductive momentum} between $l^{+}$ and $l^{-}$ with respect to $k$ and $m$ is \[ I_{\mu}(\vect{x}^{i}_a, \vect{x}^{j}_a)^{k}_{m} = \begin{cases} \text{inconsistent} & \text{if } i = j \text{, and } \\ & \quad \iota(k,\vect{x}^{i}_a) = \iota(m,\vect{x}^{j}_a)\\ \text{consistent} & \text{otherwise} \end{cases} \] \end{inductiveMomentum} Note that if $i = j$, then it is assumed $ \| \vect{x}^{i}_a \| = \| \vect{x}^{j}_a \| $ since they are the same code in the predicate space. When it is clear in the context we shall simply write $I_{\mu}(l^{+}, l^{-})^{k}_{m}$ rather than the T-Node vector notation. \noindent {\bf Example 1}. $BK$ is formed by ground instances of binary and monadic predicates (not limited to them), atoms and Herbrand universe $H_u$ as follows. \begin{enumerate} \item $\{p_1(a,a_1), \ldots, p_k(a_k,a)\}$, \item $\{q_1(a_1, b_1), \ldots, q_j(b_j,a_1)\}$, \item $\{r_1(c_1, a_k) \ldots, r_m(a_k,c_m)\}$, \item $\{t_1(b_j), \ldots, s_1(c_1),\ldots, v_1(c_m),\ldots\}$, \item target $p(X)$, with $e^{+}$: $p(a)$ and $e^{-}$: $\sim p(b)$. \end{enumerate} \begin{comment} Figure~\ref{fig:bindindSpaceP} illustrates an example of how the search space could be. \begin{figure}[h!] \centering \includegraphics[scale=0.5]{./bindingSpaceP.png} \caption{Search space formed by $\beta(a)$.} \label{fig:bindindSpaceP} \end{figure} \begin{figure}[h!] \centering \includegraphics[scale=0.5]{./bindingSpaceN.png} \caption{Search space formed by $\beta(b)$.} \label{fig:bindindSpaceN} \end{figure} The first level (top round rectangles) represents the bindings for $a$ and $b$, respectively. The levels below expand branches with the bindings of attribute-mates forming linkage patterns for $a$ and $b$, and so on. \end{comment} When the BK is compiled its correspondent NeMuS structure is also built. The induction mechanism, at each step, adds to the premise of a hypothesis the next available atom from the bindings of a constant only if such an atom ``resists" the inductive momentum. \begin{table}[th] \centering \begin{tabular}{crl} \toprule Step & partial hypothesis & $I_{\mu}$ \\ \midrule 1 & $p(X) \leftarrow p_1(X,Y)$ & n/a \\ 2 & $p(X) \leftarrow p_1(X,Y) $ & $I_{\mu}(q_1(a_1,b_1), r_1(b_1,c_1))^{a_1}_{b_1}$ \\ & $\land q_1(Z, Y)$ & = {\it consistent} \\ 3 & $p(X) \leftarrow p_1(X,Y)$ & $I_{\mu}(q_1(a_1,b_2), r_2(b_2,c_2))^{a_1}_{b_1}$ \\ & $\land q_2(Z, Y)$ & = {\it consistent} \\ $\ldots$ & $\ldots$ & \\ $n$ & $p(X) \leftarrow p_1(X,Y) $ & $I_{\mu}(q_j(b_j, a_1), q_j(b_j,b_1))^{a_1}_{b_1}$ \\ & $\land q_j(Z, Y)$ & = {\it inconsistent} \\ \bottomrule \end{tabular} \end{table} \begin{comment} \begin{table}[th] \centering \begin{tabular}{cl} \toprule Step/ $I_{\mu}$ & partial hypothesis \\ \midrule 1 & $p(X) \leftarrow p_1(X,Y)$ \\ $I_{\mu}$ & not applied \\ 2 & $p(X) \leftarrow p_1(X,Y) \land q_1(Z, Y)$ \\ $I_{\mu}$ & $I_{\mu}(q_1(a_1,b_1), r_1(b_1,c_1))^{a_1}_{b_1}$ = {\it consistent} \\ 3 & $p(X) \leftarrow p_1(X,Y) \land q_2(Z, Y)$ \\ $I_{\mu}$ & $I_{\mu}(q_1(a_1,b_2), r_2(b_2,c_2))^{a_1}_{b_1}$ = {\it consistent} \\ $\ldots$ & $\ldots$ \\ $n$ & $p(X) \leftarrow p_1(X,Y) \land q_j(Z, Y)$ \\ & $I_{\mu}(q_j(b_j, a_1), q_j(b_j,b_1))^{a_1}_{b_1}$ = {\it inconsistent} \\ \bottomrule \end{tabular} \end{table} \end{comment} For a partial hypothesis would be $p(X) \leftarrow p_1(X,Y) \land q_j(Z, Y)$ with $\theta^{-1} = \{ a/X, a_1/Y, b_j/Z\}$, but the equivalent path from negative example would reach $q_j(b_j, b_1)$. This would allow $p(b)$ to be also deduced, which is not what it is expected from a sound hypothesis. Thus, this hypothesis is dropped. For this example, a sound hypothesis could be $p(X) \leftarrow p_k(Y, X) \land r_1(Z, Y) \land s_1(Z)$. Had the target concept be $s(X)$ and positive example $s(c_1)$, then a possible hypothesis generated would be $s(X) \leftarrow s_1(X) \land r_1(X, Z_0) \land p_k(Z_0, Z_1)$. \begin{comment} The search for a hypothesis ends in one of the following cases. When a bias ``rule" holds for the current hypothesis, or when the current clause hypothesis subsumes any further inclusion of anti-unified atoms. It is adopted the former, and the latter is taken as default if no bias is given. "Invention" as a bias given by the programer/user or an automated generation of predicate names whenever a constraint is imposed on the size of the hypothesis' premise (body). \end{comment} \subsection{Predicate Invention} \label{sec:predicateInvent} Predicate invention, according to ILP definition, is a \textit{bias} defined by the user via a declarative language. It is a way to deal with predicates missing from the $BK$ for the lack of information. Suppose that target concept $p$ of Figure~\ref{fig:AllHookPathsFromExamples} is $ancestor(X,Y)$, BK is the set $B = \{ father(jake, alice), mother(matilda, alice), \ldots \}$. There are two different concept relations in which the constant $alice$ participates as a second attribute.There can be many instances of both $father$ and $mother$, and no constant appear as first argument of both. There seems to be new concept that \emph{captures the property that all persons share when appearing as the first attribute of either relation}. \begin{figure}[h!] \centering \includegraphics[scale=0.75]{./PInventionRecursivePattern.png} \caption{The invented predicate bridges the two regions of concepts.} \label{fig:recursivePattern} \end{figure} On a closer look at Figure~\ref{fig:recursivePattern}, it is possible that our general approach to predicate invention generates hypotheses that do not look like what we expect. For example $ancestor(X,Y)$ given $ancestor(jake, bob)$, might generate $ancestor(X,Y) \leftarrow father(X,Z_0) \land p_1(Z_0,Y)$. Is is assumed that two concepts, say $c_1$ and $c_2$, are ``specialisations" of another concept $c$ whenever there are objects appearing as second argument of both, but can only appear as first in one of them. This is informed to Amao as follows \vspace{11pt} \noindent {\tt Consider induction on T knowing E assuming P1 or P2 defines NewP}, \noindent to mean that the bias we are looking for is {\tt NewP $\rightarrow$ P1} or {\tt NewP $\rightarrow$ P2}. \vspace{11pt} We say that an \emph{invented predicate bridges two regions of concepts}, and so allowing a more simple generalisation of ground rules into hypothesis. This is illustrated in Figure~\ref{fig:recursivePattern}. \noindent $target(X, Y) \leftarrow newConcept(X, Z) \land target(Z, Y)$ Every time either or both concepts are involved in a hypothesis generation, the new concept is used to intentionally define the target predicate. So, from the figure above the rule base would be \begin{center} $newConcept(X, Y) \leftarrow (father(X, Y) \lor mother(X, Y))$ \end{center} Of course the new concept is parent and it is not a target concept to consider induction, but shall be used as a bridge or as a base form of a hypothesis, while the target shall be a linear or recursive linkage pattern (in our approach), or tail recursive. \section{Introduction} One of the key challenges in Inductive Logic Programming (ILP) is finding good heuristics to search the hypothesis space. In Standard ILP, a good heuristic is one that can arrive quickly at a hypothesis that is both successful and succinct. To achieve this, the efficiency of hypothesis generation depends on the partial or even total order over the Herbrand Base to constrain deduction operations. This work presents a new approach called Inductive Clause Learning (ICL) building on \cite{nemus4NeSy16}, which introduces a data structure named Neural Multi-Space (NeMuS) used in Amao, a neural-symbolic reasoning platform that performs symbolic reasoning on structured clauses via Linear Resolution \cite{ar:resolution}. Inspired by \cite{boyer-moore}, NeMuS is a shared multi-space representation for a portion of first-order logic designed for use with machine learning and neural network methods. Such a structure contains weightings on individual elements (atoms, predicates, functions and constants or variables) to help guide the use of these elements in tasks such as theorem proving, as well as in using them to guide the search in the hypothesis space and improve the efficiency and success of inductive learning. Although it has some similarities to ILP, the hypotheses search mechanism is fundamentally different. It uses the Herbrand Base (HB) to build up hypothesis candidates using inverse unification (adapted from \cite{idestam93generalization}), and prunes away meaningless hypotheses as a result of {\em inductive momentum\/} between predicates connected to positive and negative examples. In \cite{ilSNeMuS4NeSy17} inverse or anti-unification \cite{idestam93generalization} was added to allow induction of general rules from ground clauses, which is supported by the idea of {\em regions of concepts\/}. However, the inductive learning algorithm presented did not consider an adequate representation and use of \emph{bias}, and the invention of predicates called \emph{predicate invention}. Here we show how this can be achieved without using meta-interpreter level of bias specification or reasoning. It is important to note that weights are still not automatically used, but are taken into account when apparently unconnected literals have a common predicate name. This paper makes the following contributions: it demonstrates that it is possible to have predicate invention without the use of meta-rules, and consequently, of Meta-Interpretive Learning. It shows that the NeMuS structure can be used for this purpose without generating numerous meaningless hypotheses, as the invention is made during Inductive Clause Learning. For that, we use bias or automated predicate generation. Finally, it demonstrates how invention of recursive rules takes advantage of weights of the logical component representation within NeMuS. The remainder of this paper is structured as follows: section~\ref{background} gives some brief background on inductive logic programming and the Shared NeMuS data structure, sections~\ref{inductive} and \ref{sec:ICL-invent} describe the implementation of inductive learning in Amao using the Shared NeMuS data structure, then section~\ref{related} describes some related work and section~\ref{conclusions} discusses the work presented. \section{Inductive Clause Learning with Invention} \label{sec:ICL-invent} The method we are going to present in this section joins all ideas described in section~\ref{inductive}. We shall use standard logic program notation for clauses just for readability sake, but recall that Amao language treats $q \leftarrow p$ as $q \lor \lnot p$. The general idea of ICL can be summarised in three mains steps. \begin{enumerate} \item to walk across the linkages found in the Herbrand Base in order to select atoms as candidates for composing hypotheses, as well as those to oppose the compositions \item to compute $I_{\mu}$ of atoms as candidates for anti-unification that were selected from positive and negative linkages. \item to generalize, via anti-unification, only atomic formulas likely to build consistent hypotheses, i.e. those composed by atoms consistent with respect to $I_{\mu}$ \end{enumerate} In the following description we shall consider a dyadic theory with no function terms \subsection{Selecting Candidates to Compose Hypothesis} \label{sec:hypoCandidateSelection} Given the target $t(X,Y)$, $e^{+}$ : $t(a_k, a_{k1})$ and $e^{-}$ : $t(b_k, b_{k1})$. We access, from the NeMuS of the BK, $\beta(a_k)$ and $\beta(a_{k1})$. The initial view of the space of possible hypotheses that can be formed using atoms from the Herbrand Base and anti-unification is illustrated in Figure~\ref{fig:HypoSpaceHB}. \begin{figure}[h] \centering \includegraphics[scale=0.7]{./HypothesesSpace.png} \caption{Space of hypotheses formed by Herbrand Base atoms.} \label{fig:HypoSpaceHB} \end{figure} Each $\beta(a_{k})_i$ in a triangle represents a hypothesis formation branch that can be expanded following the bindings of the attribute in $e^{+}$. Some of them may allow the deduction of $e^{-}$, and thus \emph{inductive momentum} is applied to validate fetched atoms. After adding an anti-unified literal from $\beta(a_k)_1$ into the premise of the hypothesis being generated, say $H_1$, the next induction step will take a branch from the attribute-mates of $a_k$ to compute $I_{\mu}$, generalize and so on. This is a depth-first walk across the Herbrand Base. In the breadth-first walk the generation of $H_1$ is postponed until all triangle branches have been initially exploited. For completeness sake it is implemented breadth-first. \subsection{Computing $I_{\mu}$ and Linkages} \label{sec:computeIm} Accessing the bindings of constants is straightforward, we keep a loop selecting the instances of the literals that appear until the last is verified. Basically it is running while computing $I_{\mu}$ and moving across links of the sub-trees (triangles) from Figure~\ref{fig:HypoSpaceHB}. If $I_{\mu}(q_1, \eta)^{a_k}_{b_k} = $ \emph{consistent} for all $\eta \in \beta(b_k)$, then \begin{itemize} \item [] If $q_1(a_k,a_{k1}) \in \beta(a_k)$ and $q_1(a_k,a_{k1}) \in \beta(a_{k1})$, then \subitem $H_1$: $t(X,Y) \leftarrow q_1 (X,Y)$, $\theta^{-1}_1 = \{a_k/X, a_{k1}/Y\}$ \item [] Else if $q_1(a_k,a_{k1}) \in \beta(a_k)$ and $q_1(a_k,a_{k1}) \not \in \beta(a_k)$, then $H_1$: $t(X,Y) \leftarrow q_1 (X,Z_0)$, $\theta^{-1}_1 = \{a_k/X, c/Z_0\}$ \item [] Otherwise, get another $q_j \in \beta(a_k)$ and repeat the process until there are no more elements to test. In this case there is no hypothesis. \end{itemize} For a consistent $H_1$, then there may exist $r_l \in \beta(c)$, and \begin{itemize} \item [a)] $r_l \in \beta(a_{k1}): r_l \not = q_1$, $r_l(c, a_{k1})$ is an atom from the Herbrand Base then for $\theta^{-1}_1 = \{a_k/X, c/Z_0, a_{k1}/Y\}$ $H_1$: $t(X,Y) \leftarrow q_1 (X,Z_0) \land r_l(Z_0, Y)$. (Chain in ILP) \item [b)] $r_l \not \in \beta(a_{k1})$: path can only form a \emph{long linear linkage} pattern. For non dyadic, if $I_{\mu}(r_l,\eta')$ is ok then expand hypotheses : $\beta(c) - \{r_l\}$. $H_1$'s body is added with $r_l(Z_0,Z_1)$ (see expansion illustrated in Figure~\ref{fig:HypoSpaceExpansion}). \end{itemize} \begin{figure}[h] \centering \includegraphics[scale=0.7]{./ExpandingHypothesesBranch.png} \caption{Expanding space of hypotheses following $\beta(a_k)$ and $\beta(c)$.} \label{fig:HypoSpaceExpansion} \end{figure} \subsection{``Bias" as Invention of Predicates} \label{sec:biasAsInvention} Amao performs a similarity training on NeMuS's weights using the vector representation for each constant as well as for literals. Those with similar linkages end up with similar weight values associated to the argument they have and their position within them. Besides, bias may be used to add non targeted new predicates. \subsubsection*{Non user bias: ``automated" invention} For this, it is necessary ``to invent" a predicate, say $p_0$, such that $H_1$ becomes a closed hypothesis. For the sake of space $\theta^{-1}$ will be suppressed when anti-substituions are clear. \begin{itemize} \item [] $H_1$: $t(X,Y) \leftarrow q_1(X,Z_0) \land p_{0}(Z_0,Y)$, The invented predicate becomes the head of "invented hypothesis", as \item []$H_2$: $p_{0}(X,Y) \leftarrow r_l(X,Z_0)$ with $\theta^{-1}_1 = \{c/X, c_k/Z_0\}$, and it becomes the \emph{current open hypothesis}. The search now is guided by $\beta(c_k)$. \end{itemize} \subsubsection*{User defined bias for invention} When an assumption that $r_l$ defines another concept, say $p_b$, then $H_1$'s body would have $p_b$ and $H_2$'s head would have $p_b$, rather then $p_0$. This would be something like {\tt assuming} $r_l(X,Y)$ {\tt defines} $p_b(X,Y)$, then \begin{itemize} \item []$H_1$: $t(X,Y) \leftarrow q_1(X,Z_0) \land p_{b}(Z_0,Y)$, \item []$H_2$: $p_{b}(X,Y) \leftarrow r_l(X,Z_0)$ \end{itemize} \begin{itemize} \item Assuming $r_l = q_1$, i.e. both are the same predicate (concept region). \begin{enumerate} \item If $q_1(c,a_{k1}) \in BK$, and no bias given. Simple \emph{linear linkage} pattern (chain) \subitem $H_1$: $t(X,Y) \leftarrow q_1(X,Z_0) \land q_1(Z_0,Y)$, ``Shallow" \emph{recursive linkage} pattern (recursive tail) \subitem $H_1$: $t(X,Y) \leftarrow q_1(X,Z_0) \land t(Z_0,Y)$ \subitem $H_2$: $t(X,Y) \leftarrow q_1(X,Y)$ The order they are introduced into the set of clauses is unimportant \item If $q_1(c,a_{k1}) \not \in BK$ \begin{enumerate} \item For bias and non dyadic theory: long linear linkage pattern of the same concept would generate $H_1$: $t(X,Y) \leftarrow q_1(X,Z_0) \land q_1(Z_0,Z_1) \land \ldots \land q_1(Z_n,Y)$. Instead, if $q_1(a_{k},c)$ and $q_1(c,a_{k1})$ region's weights are similar, then invent of a recursive hypothesis. \subitem $H_1$: $t(X,Y) \leftarrow q_1(X,Z_0) \land t(Z_0,Y)$, \subitem $H_2$: $t(X,Y) \leftarrow q_1(X,Y)$, \end{enumerate} \end{enumerate} \end{itemize} As there can be many bindings, we close an open hypothesis for each possible combination of bindings. Then, we keep computing the momentum and expanding a new branch for each combination (as explained in sections~\ref{sec:hypoCandidateSelection} to~\ref{sec:biasAsInvention}). \subsection{A Running Example: the Family Tree} {\bf Example 2}. Consider the Family Tree, from \cite{muggleton15meta}. We may request to Amao the following \begin{figure}[h!] \centering \includegraphics[scale=0.73]{./familyTreeMuggleton.png} \caption{A simple family tree.} \label{fig:familyTreeMGTON} \end{figure} \noindent \textbf{consider induction on} ancestor(X,Y) \textbf{knowing} ancestor(jake,bob) \textbf{assuming} father(X,Y) \textbf{or} mother(X,Y) \textbf{defines} parent(X,Y). \begin{table}[th] \centering \begin{tabular}{cll} \toprule $i$ & atom/hypothesis & $ \theta^{-1}_i$ / $\beta(a)$ \\ \midrule 0 & $ancestor(jake,bob) $ & $\{jake/X, bob/Y\} $ \\ $H_0$ & $ancestor(X,Y) \leftarrow$ & \\ 1 & $\beta_{1}(jake)$ & $father(jake,alice)$ \\ & $\beta_{1}(bob)$ & $father(ted,bob)$ \\ & $I_{\mu} = consistent$ & no hook \\ \hdashline bias & $father(X,Y)$ & match both $\beta_{1}$ \\ for & $parent(X,Y) $ & rename variable \\ \hdashline $H^{i}_0$ & $parent(X,Y) \leftarrow $ & $father(X,Y)$ \\ & $\{jake/X, bob/Y, alice/Z_0\} $ & \\ $H_1$ & $ancestor(X,Y) \leftarrow$ & $parent(X,Z_0)$ \\ & $\beta_{1}(alice)$ & $mother(alice, ted)$ \\ \hdashline bias & $mother(X,Y)$ & match both $\beta_{1}(alice)$ \\ for & $parent(X,Y) $ & rename variable \\ \hdashline $H^{i}_1$ & $parent(X,Y) \leftarrow $ & $mother(X,Y)$ \\ $H_1$ & reaches maximun body size, & do not add another \\ & $parent(Z_0, Z_1)$. Check for & region similarity \\ \hdashline $H^{i}_2$ & $ancestor(X,Y) \leftarrow $ & $parent(X,Y)$ \\ $H_1$ & $ancestor(X,Y) \leftarrow$ & $parent(X,Z_0)$ $\land$ \\ & & $ancestor(Z_0,Y)$ \\ \bottomrule \end{tabular} \end{table} \section{Related Work}\label{related} \begin{comment} Use the text between *** *** Recent advances in Inductive Logic Programming (ILP) ease predicate invention by constraining logical learning operations with higher-order meta-rules, in what has been called Meta-Intepretive Learning (MIL) technique. Although MIL nicely extends Prolog meta-interpreter to fetching such meta-rules and store only successful meta-substitutions to form a program, as a side-effect it increases the generation of \textit{meaningless hypotheses}. Amao is a cognitive agent framework that takes a total different approach by using a Neural Multi-Space (NeMuS) graph structure to perform ILP-style learning called Inductive Clause Learning (ICL). *** \end{comment} Recent advances in Inductive Logic Programming (ILP) ease predicate invention by constraining logical learning operations with higher-order meta-rules, expressions that describe the formats of the rules. These rules have order constraints associated to them (to ensure termination of the proof) and are provided to the meta-interpreter, which attempts to prove the examples. When successful at this task, it then saves the substitutions for existentially quantified variables in the meta-rules \cite{muggletonachievements}. This technique has been used to build Metagol \cite{muggleton14meta,muggleton15meta}, which has been successful in various examples. However, this approach tends to increase the generation of \textit{meaningless hypotheses} and, consequently, leads to a large hypotheses space. \cite{cropperijcai16} tackles this challenge by extending Metagol to support abstractions and invention, but it remains a problem. Amao takes a totally different approach by using NeMuS to perform Inductive Clause Learning (ICL). This work extends ICL by using the results of exploring weights of logical components, already present in NeMuS, to support inductive learning by expanding clause candidates with literals which passed in the inductive momentum check. This allows an efficient invention of predicates, including the learning of recursive hypotheses, while restricting the shape of the hypothesis by adding bias definitions or idiosyncrasies of the language. \begin{comment} Inductive logic programming has a large literature, from its antecedents in inductive generalization \cite{plotkin69note}, through work on search strategies, the logical framework that the learning sits in, as well as the building of systems and application of these to specific problems. Inductive learning continues to be of interest in a wide range of contexts and applications as recently surveyed in \cite{gulwani15inductive}. Of particular relevance is the work in \cite{bunescu05shortest} that investigates path based algorithms to generate relationships and \cite{richards95automated} that uses inductive logic programming concepts in an early instance of theory repair (that is, revising a theory that is incorrect so that the counter-examples are no longer such). Additionally \cite{idestam93generalization}, that investigates variations on the standard anti-unification algorithm and how these impact on the efficiency of hypothesis search, is of interest in the current context. More recently, in \cite{ahlgren13efficient} boolean constraints are used to describe undesirable areas of the hypothesis search space and solving these to prune the search space achieves significant speed ups over older inductive logic programming systems on a range of examples, whilst retaining accuracy. The higher-order approach taken in \cite{muggleton14meta,muggleton15meta} uses a meta-interpreter with iterative deepening to build Metagol. Metagol has had success on a range of examples, including learning a subclass of context-free grammars from examples and inferring relationships in sports data (whilst also uncovering an error in the data representation). This includes predicate invention, a topic that these papers suggest has not been paid due attention in inductive learning. Muggleton proposed four types of meta-rules to be used in a Prolog-Like meta-interpreter for ILP with invention. They are to be understood as bias for the inductive learning algorithm \begin{table}[h] \centering \begin{tabular}{ll} \hline Instance: & $p(X, Y) \leftarrow$ \\ Base: & $p(X, Y) \leftarrow q(X, Y)$ \\ Chain: & $p(X, Y) \leftarrow q(X, Z), r(Z, Y)$ \\ Tail Recursive (TailRec): & $p(X, Y) \leftarrow q(X, Z), p(Z, Y)$ \\ \hline \end{tabular} \end{table} Instances easily matches atoms from the background knowledge, chains are similar to what we called linear hooks (or linkage), and Base along with TailRec completes the recursive types of hypotheses. \end{comment}
{'timestamp': '2019-06-18T02:04:25', 'yymm': '1906', 'arxiv_id': '1906.06455', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06455'}
arxiv
\section{Introduction} The general nonparametric regression problem can be stated as \begin{align}\label{eq:mod:1} y_i = f^*(x_i) + w_i, \;i = 1,\dots,n, \quad \ex w = 0,\; \cov(w) = \sigma^2I_n \end{align} where $w = (w_i) \in \reals^n$ is a noise vector and $f^*: \mathcal X \to \reals$ is the function of interest to be approximated from the noisy observations $\{y_i\}$. Here, $\mathcal X$ is the space to which the \emph{covariates} $\{x_i\}$ belong. We consider the fixed design regression where the covariates are assumed to be deterministic. The problem has a long history in statistics and machine learning~\cite{wasserman2006all,tsybakov2009intro}. In this paper, we assume that $f^*$ belongs to a reproducing kernel Hilbert space (RKHS), denoted as $\mathcal H$~\cite{paulsen2016introduction}. Such spaces are characterized by the existence of a reproducing kernel, that is, a positive semidefinite function $\mathbb K : \mathcal X \times \mathcal X \to \reals$ that uniquely determines the underlying function space $\mathcal H$. RKHSs are very versatile modeling tools and include, for example, Sobolev spaces of smooth functions whose norms are measures of function roughness (the opposite of smoothness)~\cite{wahba1990spline}. Throughout, we think of these Sobolev spaces as the concrete examples of $\mathcal H$. By assuming an upper bound on the Hilbert norm of $f^*$, we can encode a prior belief that the true data generating function $f^*$ has a certain degree of smoothness. Without loss of generality, we assume that $f^*$ belongs to the unit ball of the RKHS, that is, \begin{align}\label{assu:unit:ball:f} f^* \;\in\; \mathbb{B}_\mathcal H := \{f \in \mathcal H:\; \norm{f}_\mathcal H \le 1\}. \end{align} A natural estimator is then, the kernel ridge regression (KRR), defined as the solution of the following optimization problem: \begin{align}\label{eq:krr:f:1} \widetilde f_{n,\lambda} := \min_{f \in \mathcal H} \;\frac1{n} \sum_{i=1}^n (y_i - f(x_i))^2 + \lambda \norm{f}_\mathcal H^2, \end{align} where $\lambda > 0$ is a regularization parameter. It is well-known that this problem can be reduced to a finite-dimensional problem (by an application of the so-called representer theorem)~\cite{kimeldorf1971some}: \begin{align}\label{eq:krr:omg:1} \min_{\omega \,\in\, \reals^n} \; \frac1{n} \vnorm{y- \sqrt n K \omega}^2 + \lambda \omega^T K \omega, \quad \text{where}\quad K =\frac1n \big( \mathbb K(x_i,x_j)\big) \in \reals^{n \times n} \end{align} is the (normalized empirical) kernel matrix. Although~\eqref{eq:krr:omg:1} has a closed form solution, it involves inverting an $n \times n$ dense matrix, with time complexity $O(n^3)$, which is prohibitive in practice. Various approximation schemes have been proposed to mitigate the computational costs, including (i) approximating the kernel matrix or (ii) directly approximating the optimization problem~\eqref{eq:krr:omg:1}. Examples of the former are the Nystr\"{o}m approximation, column sampling and their variants~\cite{williams2001using,zhang2008improved,kumar2009ensemble,li2010making,talwalkar2014matrix}. An example of the latter is sketching~\cite{alaoui2015fast,yang2017randomized} where one restricts $\omega$ to the subspace $\ran(S) := \{S\alpha \mid \alpha \in\reals^r\}$, for some random matrix $S \in \reals^{n \times r}$. It is in fact known that Nystr\"{o}m can be considered a special case of sketching with random standard basis vectors~\cite{yang2017randomized}. Sketching, with sufficiently large $r$, has been shown in~\cite{yang2017randomized} to achieve minimax optimal rates over Sobolev spaces, under mild conditions on the sketching matrix $S$. Similarly, the Nystr\"{o}m approximation has been analyzed in~\cite{cortes2010impact,yang2012nystrom,jin2013improved,alaoui2015fast,bach2013sharp} and~\cite{rudi2015less}, the latter showing minimax rate optimality. In addition to the above, (iii) divide and conquer approaches have been proposed~\cite{zhang2013divide}, where one solves the problem over subsamples and then aggregate by averaging, with some rate optimality guarantees. Other notable approaches to scaling include (iv) approximating translation-invariant kernel functions via Monte Carlo averages of tensor products of randomized feature maps~\cite{rahimi2008random,le2013fastfood} and (v) applying stochastic gradient in the function space~\cite{dai2014scalable}. In this paper, we consider the most direct kernel approximation, namely, replacing $K$ by its best rank $r$ approximation (in Frobenius norm). This amounts to truncating the eigenvalue decomposition of $K$ to its top $r$ eigenvalues. We refer to the resulting KRR approximation as the \emph{spectrally-truncated} KRR (ST-KRR). Although somewhat slower than the Nystr\"{o}m approximation and fast forms of sketching, ST-KRR can be considered an ideal rank-$r$ spectral approximation. By analyzing it, one can also gain insights about approximate SVD truncation approaches such as Nystr\"{o}m or sketching. In addition, practically, it is a very viable solution for moderate size problems. See Appendix~\ref{app:time} for a discussion of the time complexity of various schemes. We derive an exact expression for the maximum (empirical) mean-squared error (MSE) of ST-KRR, uniformly over the unit ball of the RKHS. This expression is solely in terms of the eigenvalues $\{\mu_i\}$ of the kernel matrix $K$, the regularization parameter $\lambda$, the truncation level $r$, and the noise level $\sigma^2$. Thus if one has access to $\{\mu_i\}$ and the noise level (or estimates of them), one can plot the exact regularization curve (maximum MSE versus $\lambda$) for a given truncation level $r$ and sample size $n$, and determine the optimal value of $\lambda$. We also note that since the empirical eigenvalues $\{\mu_i\}$ quickly approach those of the integral operator associated with $\mathbb K$ (as $n \to \infty$)~\cite{koltchinskii2000random}, one can use these idealized eigenvalues instead of $\{\mu_i\}$ to get an excellent approximation of these regularization curves. We then show that there is an optimal threshold on $r$, the truncation level, which we denote as $r_n$ such that for all $r \ge r_n$, the minimal maximum-risk of $r$-truncated KRR, with minimum taken over the regularization parameter, is strictly better than that of the full KRR whenever $\mu_{r+1} > 0$. In particular, for infinite-dimensional RKHSs, $\mu_{r_n+1} > 0$, hence truncating at level $r_n$ is guaranteed to strictly improve performance. The slower the decay of the eigenvalues, the larger this gap in performance. We also show how the exact expression for the maximum MSE can be used to easily establish an slightly weaker bound for ST-KRR, similar to those derived in~\cite{yang2017randomized} for sketching. We discuss the link between the statistical dimension considered in~\cite{yang2017randomized} and the optimal truncation level $r_n$, and show how the same rate-optimality guarantees hold for ST-KRR. (Rate-optimality also follows form the fact that ST-KRR, with proper $r$, strictly dominates full KRR and the latter is rate-optional. However, we do these calculations to make the comparison easier.) Finally, we illustrate the results with some numerical simulations showing some further surprises. For example, the Gaussian kernel has a much faster eigendecay rate than a Sobolev-1 kernel (exponential versus polynomial decay). Hence, the optimal truncation level $r_n$ asymptotically grows much slower for the Gaussian kernel. However, for finite samples, depending on the choice of the Gaussian bandwidth, the exact optimal truncation level, computed numerically, can be larger than that of Sobolev-1. \section{Preliminaries} Before stating and studying the spectrally-truncated problem in more details, let us make some observations regarding the original KRR problem in~\eqref{eq:krr:f:1}. For $\omega \in \reals^n$, we define the \emph{kernel mapping} \begin{align}\label{eq:f:om} f_\omega := \frac1{\sqrt n} \sum_j \omega_j \mathbb K(\cdot,x_j). \end{align} Note that $\omega \mapsto f_\omega$ is a linear map from $\reals^n \to \mathcal H$. This map is the link between the solutions of the two optimization problems~\eqref{eq:krr:f:1} and~\eqref{eq:krr:omg:1}: For any optimal solution $\omega$ of~\eqref{eq:krr:omg:1}, $f_\omega$ will be an optimal solution of~\eqref{eq:krr:f:1}. The link is easy to establish by observing the following two identities: \begin{align}\label{eq:hilnorm:ident} \norm{f_\omega}_\mathcal H^2 = \omega^T K \omega, \quad f_\omega(x_i) = \sqrt n (K \omega)_i, \end{align} the first of which uses the \emph{reproducing property} of the kernel: $\hip{f, \Kerarg{x}} =f(x)$. We will frequently use this property in the sequel. The proof of the equivalence follows from an argument similar to our discussion of the identifiability below. \subsection{Identifiability}\label{sec:indentify} Let us first observe that $f^*$ in~\eqref{eq:mod:1} is not (statistically) identifiable. That is, there are multiple functions $f^*$ (in fact infinitely many if $\mathcal H$ is infinite dimensional) for which the vector $(y_i)$ has the exact same distribution. To see this, let \begin{align}\label{eq:LcX} \mathcal{L}_X := \text{span}\{ \Kerarg{x_i}:\; i \in [n]\} = \{f_\omega :\; \omega \in \reals^n\}. \end{align} Let $f_{\omega^*}$ be the projection of $f^*$ onto $\mathcal{L}_X$. (It is always possible to choose at least one such $\omega^*$ by the definition of projection and since $\mathcal{L}_X$ is a closed subspace of $\mathcal H$.) Given observations $(y_i)$, we can only hope to recover the following equivalence class: \begin{align*} \{ f \in \mathcal H :\; f(x_i) = f^*(x_i), \; \forall i\} &= \{ f \in \mathcal H :\; \ip{f-f^*, \Kerarg{x_i}}_\mathcal H = 0, \; \forall i\} \\ & = \{ f^* + g:\; g \perp_\mathcal H \mathcal{L}_X\} \\ &= \{ f_{\omega^*} + g:\; g \in \mathcal{L}_X^\perp\} = f_{\omega^*} + \mathcal{L}_X^\perp \end{align*} where the last line follows since $f^* - f_{\omega^*} \in \mathcal{L}_X^\perp$ by the property of orthogonal projection (and can be absorbed into $g$). We will use $f_{\omega^*}$ as the representative of the (identifiable) equivalence class of $f^*$. We are interested in measuring functional deviations (e.g., the error in our estimate relative to the true function) in the \emph{empirical $\ell_2$ norm}: \begin{align*} \empnorm{f-g} = \Big[\frac1n \sum_{i=1}^n \big(f(x_i) - g(x_i) \big)^2\Big]^{1/2}. \end{align*} The use of this norm is common in the literature of nonparametric regression~\cite{van2000empirical,wainwright2019high}. It is interesting to note that $\vnorm{f^*-f_{\omega^*}}_n = 0$, \begin{align}\label{eq:equiv:empnorm} \empnorm{f-f^*} = \empnorm{f-f_{\omega^*}}, \quad \forall f \in \mathcal H, \end{align} and $\vnorm{f_{\omega^*}}_\mathcal H \le \vnorm{f^*}_\mathcal H$, since projections are contractive. Thus, recalling~\eqref{assu:unit:ball:f}, $f_{\omega^*}$ also belongs to the Hilbert unit ball: $f_{\omega^*} \in \mathbb{B}_\mathcal H$. It is in fact easy to see that $f_{\omega^*}$ has the least Hilbert norm among the members in the equivalence class (i.e., the smoothest version). Thus, without loss of generality, we can identify $f^*$ with $f_{\omega^*}$. Equivalently, we can assume from the start that $f^*$ is of the form $f_{\omega^*}$ for some $\omega^* \in \reals^n$. Note that the ``no loss of generality'' statement holds as long as we are working with the empirical $\ell_2$ norm, due to~\eqref{eq:equiv:empnorm}. \section{Main results} Let $K = U DU^T$ the eigenvalue decomposition (EVD) of the empirical kernel matrix defined in~\eqref{eq:krr:omg:1}. Here, $U \in \reals^{n \times n}$ is an orthogonal matrix and $D = \diag(\mu_i)_{i=1}^n$ where $\mu_1 \ge \mu_2 \ge \dots \ge \mu_n \ge 0$ are the eigenvalues of $K$. We assume for simplicity that $\mu_n> 0$, that is, the exact kernel matrix is invertible. Consider the rank $r$ approximation of $K$, obtained by keeping the top $r$ eigenvalues and truncating the rest to zero, that is, \begin{align*} \Kap = \Kap_r := U \begin{pmatrix} D_r & 0 \\ 0 & 0 \end{pmatrix} U^T = U_r D_r U_r^T. \end{align*} Here, $D_r = \diag(\mu_1,\dots,\mu_r)$ and $U_r \in \reals^{n \times r}$ collects the first $r$ columns of $U$. The idea is to solve~\eqref{eq:krr:omg:1} with $K$ replaced with $\Kap$, to obtain $\widetilde \omega$. We then form our functional estimate $\widetilde f$ by using the (exact) kernel mapping~\eqref{eq:f:om}. \begin{defn}\label{dfn:trunc:krr} An \emph{$r$-truncated $\lambda$-regularized KRR estimator} with input $y \in \reals^n$ , is a function $\widetilde f := f_{\widetilde \omega} = \frac1{\sqrt n} \sum_j \widetilde \omega_j \mathbb K(\cdot,x_j)$ where \vspace{-1.5ex} \begin{align} \widetilde \omega \in &\argmin_{\omega \,\in\, \reals^n} \label{eq:omt:min} \; \frac1{n} \vnorm{y- \sqrt n \Kap \omega}^2 + \lambda \omega^T \Kap \omega, \\ &\text{such that } \Kap \widetilde \omega = K \widetilde \omega\label{eq:omt:cond}. \end{align} \end{defn} A minimizer in~\eqref{eq:omt:min}, without the additional condition $\Kap \widetilde \omega = K \widetilde \omega$, is not unique due to the rank deficiency of $\Kap$. Thus, we can ask for it to satisfy additional constraints. The equality condition in~\eqref{eq:omt:cond}, which can be stated as $\widetilde \omega \in \ker(\Kap - K)$ can always be satisfied. It is enough to choose $\widetilde \omega$ to be the unique minimizer in $\ran(\Kap) = \ran(U_r)$, that is, $\widetilde \omega = U_r \alpha$ for some $\alpha \in \reals^r$. This is how the estimator is often implemented in practice. \smallskip We are interested in the deviation of $\widetilde f$ from the true function $f^*$ in the empirical $\ell_2$ norm. More precisely, we are interested in the mean-squared error as the statistical risk: \begin{align*} \mse(\widetilde f,f^*) = \ex \empnorm{\widetilde f - f^*}^2. \end{align*} Our main result is an expression for the worst-case risk of $\widetilde f$ over the unit ball of the RKHS: \begin{thm}\label{thm:krr:spec:trunc} Let $\widetilde f = \widetilde f_{r,\lambda}$ be an $r$-truncated $\lambda$-regularized kernel KRR estimator (Definition~\ref{dfn:trunc:krr}) applied to input $y$ generated from model~\eqref{eq:mod:1}. Let \begin{align*} H_r(\lambda) := \max_{1 \le i \le r} h_\lambda(\mu_r) \end{align*} where $h_\lambda(x) = \lambda^2 x/(x+\lambda)^2$. Then, for all $r=1,2,\dots,n$ and $\lambda > 0$, \begin{align}\label{eq:krr:trunc:res} \sup_{f^* \, \in \, \mathbb{B}_\mathcal H} \mse(\widetilde f_{r,\lambda},f^*) \;=\; \max\big\{ H_r(\lambda), \; \mu_{r+1} \big\} + \frac{\sigma^2}{n} \sum_{i=1}^r \Big(\frac{\mu_i}{\mu_i + \lambda}\Big)^2, \end{align} with $\mu_{n+1} := 0$. \end{thm} The first term in~\eqref{eq:krr:trunc:res} is the worst-case approximation error (WAE) and the second term the estimation error (EE). The approximation error (AE) is the risk (relative to $f^*$) of $\overbar{f}$ which is obtained by passing the noiseless observations $(f^*(x_i))$, instead of $y$, through the estimation procedure. The AE is the deterministic part of the risk and is given by $\empnorm{\overbar{f}-f^*}^2$. The estimation error is the stochastic part of the risk and is given by $\ex \empnorm{\widetilde f - \overbar{f}}^2$. \medskip The function $x \mapsto h_\lambda(x)$ attains its maximum of $\lambda/4$, over $[0,\infty)$, at $x = \lambda$. Thus, as long as $\lambda \in [\mu_r, \mu_1]$, the bound $H_r(\lambda) \le \lambda/4$ is good. In general, \begin{align}\label{eq:wae:bound} \text{WAE}_{r,\lambda} \le \max\Big\{\frac\lambda4 , \;\mu_{r+1} \Big\}. \end{align} We note that since the KRR estimates are linear in $y$, Theorem~\ref{thm:krr:spec:trunc} easily gives the maximum MSE expression over the Hilbert ball of arbitrary radius $R$, by replacing $\sigma^2$ in~\eqref{eq:krr:trunc:res} with $\sigma^2/R^2$ and multiplying the entire right-hand side by $R^2$. We also have a precise result on the regularized risk of the approximating function: \begin{prop}\label{lem:approxerr:pluse:smoothness:good} Let $\overbar{f} = \overbar{f}_{r,\lambda}$ be obtained by passing the noiseless observations $(f^*(x_i))$, instead of $y$, through the estimation procedure in Definition~\ref{dfn:trunc:krr}. Then, \begin{align}\label{eq:approxerr:pluse:smoothness:good} \sup_{f^* \,\in\, \mathbb{B}_\mathcal H} \vnorm{f^* - \overbar{f}}_n^2 + \lambda \vnorm{\overbar{f}}_\mathcal H^2 \;=\; \max\Big\{\max_{1\le i \le n} \frac{\lambda \mu_i}{\mu_i + \lambda}, \;\mu_{r+1}\Big\}. \end{align} \end{prop} \subsection{Maximum-risk inadmissibility} Let us now consider how the maximum risk of the truncated KKR compares with the full version. For every, $\lambda > 0$, define \begin{align*} r(\lambda) := \min\{r \in [n]:\; \mu_{r+1} \le H_n(\lambda) \}. \end{align*} In addition, recalling that $\widetilde f_{n,\lambda}$ is the full KRR estimator, let \begin{align}\label{eq:lambda:n} \lambda_n := \argmin_{\lambda > 0} \sup_{f^* \, \in \, \mathbb{B}_\mathcal H} \mse(\widetilde f_{n,\lambda},f^*), \quad \text{and} \quad r_n := r(\lambda_n). \end{align} That is, $\lambda_n$ is the regularization parameter that achieves the minimal maximum-risk for the full KRR. We have the following corollary of Theorem~\ref{thm:krr:spec:trunc}: \begin{cor}\label{cor:domination} For every $\lambda > 0$, and every $r \in [n]$ with $r \ge r(\lambda)$, \begin{align}\label{eq:max:risk:domination} \sup_{f^* \, \in \, \mathbb{B}_\mathcal H} \mse(\widetilde f_{r,\lambda},f^*) \;\le\; \sup_{f^* \, \in \, \mathbb{B}_\mathcal H} \mse(\widetilde f_{n,\lambda},f^*). \end{align} In particular, for every $r \ge r_n$, \begin{align}\label{eq:minmax:risk:domination} \min_{\lambda > 0} \sup_{f^* \, \in \, \mathbb{B}_\mathcal H} \mse(\widetilde f_{r,\lambda},f^*) \;\le \; \min_{\lambda > 0} \sup_{f^* \, \in \, \mathbb{B}_\mathcal H} \mse(\widetilde f_{n,\lambda},f^*). \end{align} Both inequalities are strict whenever $\mu_{r+1} > 0$. \end{cor} Corollary~\ref{cor:domination} shows that $\lambda$-optimized $\widetilde f_{r_n,\lambda}$ strictly improves on optimized full KRR whenever $\mu_{r_n+1} > 0$, in a sense rendering the full KRR inadmissible, as far as the maximum risk over $\mathbb{B}_\mathcal H$ is concerned. Note that we are not claiming inadmissibility in the classical sense which requires one estimator to improve on another for all $f^* \in \mathbb{B}_\mathcal H$. In general, the slower the decay of $\{\mu_i\}$, the more significant the improvement gained by truncation. Note that~\eqref{eq:lambda:n} allows one to set the precise truncation level including the exact constants if one has access to the eigenvalues of the kernel matrix. In practice, for large $n$, the eigenvalues of the associated kernel integral operator (if available) can act as excellent surrogates for $\{\mu_i\}$~\cite{koltchinskii2000random}. \subsection{Gaussian complexity and rates Less precise bounds, albeit good enough to capture the correct asymptotic rate as $n \to \infty$, can be obtained in terms of the Gaussian complexity of the unit ball of the RKHS. These types of results have been obtained for the Sketched-KRR. To make a comparison easier, let us show how such bounds can be obtained from Theorem~\ref{thm:krr:spec:trunc}. Let us define the $r$-truncated complexity (of the empirical Hilbert ball) as \begin{align}\label{eq:Gauss:complexity} R_r(\delta) = \Big( \frac{\sigma^2}{n}\sum_{i=1}^r \min\{\mu_i, \delta^2\}\Big)^{1/2}. \end{align} For the case $r=n$, this matches the definition of the kernel complexity in~\cite{yang2017randomized}, which we refer to for the related background. In particular,~\eqref{eq:Gauss:complexity} is a tight upper bound on the Gaussian complexity of the intersection of $\mathbb{B}_\mathcal H$ and $\{f:\;\norm{f}_n \le \delta \}$~\cite[Chapter 13]{wainwright2019high}. We have: \begin{cor}[Looser bound]\label{cor:Gauss} Under the setup of Theorem~\ref{thm:krr:spec:trunc}, for any $\lambda \ge \max\{\delta^2, 4\mu_{r+1}\}$, \begin{align}\label{eq:weaker:upper:bound} \sup_{f^* \,\in\, \mathbb{B}_\mathcal H} \mse(\widetilde f_{r,\lambda}, f^*) \;\le\; \frac14 \lambda + \Big(\frac{R_r(\delta)}{\delta} \Big)^2. \end{align} If $\lambda \ge \mu_1$, one can replace the first term with $\mu_1\lambda^2/(\lambda+\mu_1)^2$ for a better bound. \end{cor} Choosing $\lambda = \delta^2 \ge 4 \mu_{r+1}$, we obtain \[ \text{RMSE} = \sqrt{\mse} \le \frac{\delta}2 + \frac{R_r(\delta)}{\delta} \le \frac{\delta}2 + \frac{R_n(\delta)}{\delta}. \] The latter upper bound is what one would get for the full KRR. Matching the two terms in that bound, we chooses $\delta_n$ such that $ \delta_n^2 = 2 R_n(\delta_n)$ which gives the well-known critical radius for the KRR problem~\cite{wainwright2019high}. It is known that $\delta_n$ gives the optimal rate of convergence for estimating functions in $\mathbb{B}_\mathcal H$, i.e., its rate of decay matches that of the minimax risk~\cite{yang2017randomized}. The above argument shows that as long as $r$ is taken large enough so that $4 \mu_{r+1} \le \delta_n^2$, the $r$-truncated KRR achieves (at least) the same rate as the full KRR. (For the sketching, the same conclusion is established in~\cite{yang2017randomized}, where the smallest $r$ satisfying $\mu_{r} \le \delta_n^2$ is referred to as the \emph{statistical dimension} of the kernel.) For Sobolev-$\alpha$ kernels, with eigendecay $\mu_i \asymp i^{-2\alpha}$, we obtain $\mse \lesssim \delta_n^2 \asymp (\sigma^2/n)^{-\frac{2\alpha}{2\alpha+1}}$. Interestingly, in this case, the estimate based on the weaker bound~\eqref{eq:weaker:upper:bound} and the exact bound~\eqref{eq:krr:trunc:res} give the same rate (cf.~Appendix~\ref{app:rates}). This is expected since the given rate is known to be minimax optimal for Sobolev spaces. The same goes for the Gaussian kernel for which $\mu_j \asymp e^{- c j \log j}$ and the rate is $\gamma \log(1/\gamma)$ for $\gamma = \sigma^2/n$. Order-wise, $\delta_n^2$ will be the same as $\lambda_n$ defined in~\eqref{eq:lambda:n}, that is $\lambda_n \asymp \delta_n^2$, whenever $\delta_n^2$ matches the optimal rate. Hence, often $\mu_1 > \lambda_n \gg \mu_n$ for large $n$ and the argument leading to~\eqref{eq:wae:bound} suggests that in this case $H_n(\lambda_n) \approx \lambda_n/4$. Then, \begin{align*} r_n \approx \min\Big\{r \in [n]:\; \mu_{r+1} \le \frac{\lambda_n}{4} \Big\}. \end{align*} For Sobolev-$\alpha$ kernels, this suggests truncation level $r_n \gtrsim (\sigma^2/n)^{\frac{1}{2\alpha+1}}$ which gives moderate savings for high smoothness levels $\alpha$. Similarly, for the Gaussian kernel, it is not hard to see that truncating to $r_n \gtrsim \log(n/\sigma^2)$ is enough to get the same rate as the full KRR, which is a substantial saving. \begin{figure}[t] \centering \begin{tabular}{cc} \includegraphics[width=.45\textwidth]{figs/{Gaussian}.eps} & \includegraphics[width=.45\textwidth]{figs/{Sobolev-1}.eps} \\ \includegraphics[width=.45\textwidth]{figs/{empmse_Gaussian}.eps} & \includegraphics[width=.45\textwidth]{figs/{empmse_Sobolev-1}.eps} \\ \end{tabular} \caption Plots of (top) the maximum theoretical MSE (bottom) typical empirical MSE, versus the regularization parameter ($\lambda$) for the Gaussian (with bandwidth = 10) and Sobolev-1 kernels on $[-1,1]$ with $n=200$ equispaced samples. The optimally-truncated KRR is shown ($r=r_n$) together with the full KRR ($r=n$). } \label{fig:mse} \end{figure} \section{Simulations} We now present some numerical experiments to corroborate the theory. We consider a Gaussian kernel $K(s,t) = e^{-(u-v)^2/2b^2}$ of bandwidth $b = 0.1$ on $[-1,1]$, as well as the Sobolev-1 kernel $K(s,t) = \min(s,t)$ on $[0,1]$. We take the covariates $\{x_i\}$ to be $n=200$ equi-spaced points in each interval. The top row of Figure~\ref{fig:mse} shows the plot of the theoretical maximum MSE as given by Theorem~\ref{thm:krr:spec:trunc} for the two kernels, for both the full KRR ($r=n$), and the optimally truncated version ($r = r_n$). We have used $\sigma = 2$ in~\eqref{eq:krr:trunc:res}. As predicted by Theorem~\ref{thm:krr:spec:trunc}, the minimum achievable maximum MSE is smaller for the truncated KRR. To compute the optimal truncation, we have evaluated the regularization curve of the full KRR first, obtained the minimizer $\lambda_n$ and then used~\eqref{eq:lambda:n} to compute the optimal truncation level $r_n$. For the setup of the simulation, we get $r_n = 10$ for the Gaussian and $r_n = 3$ for the Sobolev-1. It is interesting to note that although in terms of rates, $r_n$ for the Gaussian should be asymptotically much smaller than that of Sobolev-1, in finite samples, the truncation level for the Guassian could be bigger as can be seen here. This is due to the unspecified, potentially large, constants in the rates (that depend on the bandwidth $b$ as well). Also, notice how surprisingly small $r_n$ is relative to $n$ in both cases. The bottom row of Figure~\ref{fig:mse} shows the empirical MSE obtained for a typical random $f^* \in \mathbb{B}_\mathcal H$, by computing the KRR estimates for observation $y$ and comparing with $f^*$. The random true function is generated as $f^* = f_{\omega^*}$ where $\omega^* \sim N(0,I_n)$ and further normalized so that $(\omega^*)^T K \omega^* = 1$. We have generated $n=200$ observations from~\eqref{eq:mod:1} with $\sigma = 2$. The plots were obtained using 1000 replications. The truncation levels are those calculated based on the maximum MSE formula~\eqref{eq:krr:trunc:res}. The plots show that for a typical application, the truncated KRR also dominates the full KRR. \section{Proof of the main result} Here we give the proof of Theorem~\ref{thm:krr:spec:trunc}. The remaining proofs can be found in Appendix~\ref{app:rem:proofs}. \paragraph{The $u$-transform.} From the discussion in Section~\ref{sec:indentify}, both the KRR estimate and the true function belong to $\mathcal{L}_X$ given in~\eqref{eq:LcX}. It is then useful to have an expression for the empirical $\ell_2$ error of functions belonging to this space. First, we observe that $\vnorm{f_\omega}_n^2 = \frac1n \sum_{i=1}^n [f_\omega(x_i)]^2 = \vnorm{K \omega}^2$. Now, take any $\omega, \omega^* \in \reals^d$, and let $u = K \omega$ and $u^* = K \omega^*$. Then, we have \begin{align}\label{eq:emp:uspace:equiv} \empnorm{f_\omega - f_{\omega^*}} = \empnorm{f_{\omega - \omega^*}} = \norm{K(\omega - \omega^*)} = \norm{u - u^*} \end{align} where the fist equality is by the linearity of $\omega \mapsto f_\omega$. For any function $f_\omega \in \mathcal{L}_X$, we call $u = K\omega$ the \emph{$u$-space} representation of $f_\omega$. Identity~\eqref{eq:emp:uspace:equiv} shows that it is often easier to work in the $u$-space since the \emph{$u$-transform} turns empirical $\ell_2$ norms on functions into the usual $\ell_2$ norms on vectors. In other words, the map $f_\omega \mapsto u$, is a Hilbert space isometry from $(\mathcal{L}_X,\empnorm{\cdot})$ to $(\reals^n,\norm{\cdot})$. In the $u$-space, the KRR optimization problem can be equivalently stated as: \begin{align}\label{eq:krr:u:1} \min_{u \,\in\, \ran(K)} \; \frac1{n} \vnorm{y- \sqrt{n} u}^2 + \lambda u^T K^{+} u \end{align} where $K^+$ is the pseudo inverse of $K$, and $\ran(K)$ its range. More precisely: \begin{lem}\label{lem:omega:u:equiv} For any $K \in \reals^{n \times n}$, problems~\eqref{eq:krr:omg:1} and~\eqref{eq:krr:u:1} are equivalent in the following sense: \begin{itemize}[label=-] \item For any minimizer $\overbar{\omega}$ of~\eqref{eq:krr:omg:1}, $K \overbar{\omega}$ is a minimizer of~\eqref{eq:krr:u:1}, and \item for any minimizer $\overbar{u}$ of~\eqref{eq:krr:u:1}, any $\overbar{\omega} \in \{ \omega :\; K \omega = \overbar{u}\}$ is a minimizer of~\eqref{eq:krr:omg:1}. \end{itemize} \end{lem} It is often the case that the kernel matrix itself is invertible, in which case $K^+ = K^{-1}$, $\ran(K) = \reals^n$ and problem~\eqref{eq:krr:u:1} simplifies. However, the equivalence in Lemma~\ref{lem:omega:u:equiv} holds even if we replace $K$ with an approximation which is rank deficient. This observation will be useful in the sequel. \begin{proof}[Proof of Theorem~\ref{thm:krr:spec:trunc}] Take $\widetilde \omega$ to be as in Definition~\ref{dfn:trunc:krr} and let $\widetilde{y} = y/\sqrt{n}$. Since $\widetilde \omega$ is the minimizer of $ F(\omega;y) = \vnorm{\widetilde{y}- \Kap \omega}^2 + \lambda \omega^T \Kap \omega, $ we have $\nabla F(\widetilde \omega;y) = 0$ or $\Kap(\Kap \widetilde \omega - \widetilde{y}) + \lambda \Kap \widetilde \omega = 0$. Hence, $(\Kap + \lambda I) \Kap\widetilde \omega = \Kap \widetilde{y}$ or \begin{align}\label{eq:Kap:optim:cond} \Kap \widetilde \omega = \Psi_\lambda \widetilde{y}, \quad \text{where}\;\; \Psi_\lambda = (\Kap + \lambda I)^{-1} \Kap. \end{align} Let $w = (w_i) \in \reals^n$ be the noise vector in~\eqref{eq:mod:1} and $\widetilde{w} = w/\sqrt{n}$. We also let \begin{align}\label{eq:us:def} u^* = (f_{\omega^*}(x_i)) /\sqrt{n} = K \omega^*. \end{align} Then, we can write model~\eqref{eq:mod:1} as $\widetilde{y} = u^* + \widetilde{w}$, where $\widetilde{w}$ is zero mean with $\cov(\widetilde{w}) = \sigma^2 I_n / n$. % From~\eqref{eq:emp:uspace:equiv}, we have $\empnorm{\widetilde f - f^*}^2 = \norm{K(\widetilde \omega - \omega^*)}^2$, and \begin{align*} K(\widetilde \omega - \omega^*) = \Kap \widetilde \omega - u^* = \Psi_\lambda \widetilde{y} - u^* = (\Psi_\lambda - I) u^* + \Psi_\lambda \widetilde{w}, \end{align*} where the first equality uses assumption~\eqref{eq:omt:cond}. It follows that \begin{align*} \ex \vnorm{\widetilde f - f^*}_n^2 = \vnorm{(I - \Psi_\lambda) u^*}^2 + \ex \vnorm{\Psi_\lambda \widetilde{w}}^2. \end{align*} where the first term is the approximation error (AE) and the second term, the estimation error (EE). % Let us write $\Dap = \diag(\mu_1,\dots,\mu_r,0,\dots,0) \in \reals^{n \times n}$ so that $\Kap = U \Dap U^T$. We define \begin{align}\label{eq:Gaml:def} \Gamma_\lambda = (\Dap + \lambda I)^{-1} \Dap, \quad \text{so that}, \quad \Psi_\lambda = U \Gamma_\lambda U^T \end{align} and note that $\Gamma_\lambda$ is diagonal. Let $v^* = U^T u^*$ and $\widehat w = U^T \widetilde{w}$. Then, since $\ell_2$ norm is unitarily invariant, we have \begin{align*} \ex \vnorm{\widetilde f - f^*}_n^2 = \vnorm{(I - \Gamma_\lambda) v^*}^2 + \ex \vnorm{\Gamma_\lambda \widehat w}^2. \end{align*} \noindent \emph{Controlling the estimation error:} We have \begin{align*} \text{EE}_{r,\lambda} := \ex\vnorm{\Gamma_\lambda \widehat w }^2 = \ex \big[\widehat w^T \Gamma_\lambda^2 \widehat w\big] = \tr\big( \Gamma_\lambda^2 \cov(\widehat w)\big) = \frac{\sigma^2}{n} \tr(\Gamma_\lambda^2), \end{align*} using $\cov(\widehat w) = U^T \cov(\widetilde{w}) U = (\sigma^2 / n) U^T U = \sigma^2 I_n / n$ since $U$ is an orthogonal matrix. Then, \begin{align}\label{eq:Gaml:diag} (\Gamma_\lambda)_{ii} = \Big( \frac{\Dap_{ii}}{\Dap_{ii}+\lambda}\Big) = \begin{cases} \frac{\mu_i}{\mu_i + \lambda}, & i =1,\dots,r \\ 0 & i=r+1,\dots,n, \end{cases} \end{align} establishing the EE part of the result. \medskip \noindent \emph{Controlling the approximation error:} Recall that we are interested in the worst-case approximation error (WAE) over the unit ball of the Hilbert space, i.e., over $f^* \in \mathbb{B}_\mathcal H$. Also, recall that without loss of generality, we can take $f^* = f_{\omega^*}$. Hence, \begin{align}\label{eq:vs:ellips} 1 \ge \hilnorm{f}^2 = \hilnorm{f_{\omega^*}}^2 = (\omega^*)^T K \omega^* = (u^*)^T K^{-1} u^* = (v^*)^T D^{-1} v^* \end{align} where the second equality is from~\eqref{eq:hilnorm:ident}, and the latter two are by definitions of $u^*$ and $v^* = U^T u^*$. We obtain \begin{align*} \text{WAE}_{r,\lambda} = \sup_{(v^*)^T D^{-1} v^* \,\le\, 1} \vnorm{(I-\Gamma_\lambda) v^*}^2. \end{align*} A further change of variable $v^* = D^{1/2} v$ gives \begin{align*} \text{WAE}_{r,\lambda} = \sup_{v^T v \, \le \, 1} \vnorm{(I-\Gamma_\lambda) D^{1/2}v}^2 = \opnorm{(I-\Gamma_\lambda) D^{1/2}}^2, \end{align*} where $\opnorm{\cdot}$, applied to matrices, is the $\ell_2\to \ell_2$ operator norm. Note that $\Gamma_\lambda$ is a diagonal matrix with diagonal elements, $\mu_i/(\mu_i + \lambda)$ for $i=1,\dots,r$ followed by $n-r$ zeros. It follows that $(I - \Gamma_\lambda)D^{1/2}$ is diagonal with diagonal elements: \begin{align}\label{eq:Gamil:D:diag} [(I - \Gamma_\lambda)D^{1/2}]_{ii}= \begin{cases} \frac{\lambda \sqrt{\mu_i}}{\lambda + \mu_i}, & i = 1,\dots,r,\\ \sqrt{\mu_i}, & i = r+1,\dots,n. \end{cases} \end{align} Since $\{\mu_i\}$ is a non-increasing sequence, we obtain \begin{align*} \text{WAE}_{r,\lambda} = \max\Big\{ \max_{1 \le i \le r}\frac{\lambda^2 \mu_i}{(\lambda + \mu_i)^2}, \; \mu_{r+1} \Big\}, \end{align*} which is the desired result. \end{proof} \printbibliography
{'timestamp': '2019-06-17T02:16:46', 'yymm': '1906', 'arxiv_id': '1906.06276', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06276'}
arxiv
\section{Introduction} The growing interest in both quantum computing and machine learning has inspired researchers to study a combination of both fields, termed \emph{quantum machine learning} \cite{Neven2008BinaryClassificationOnDWave, Pudenz2012QML, Neven2012QBoost, Adachi2015QMLApplicationToDeepLearning, Potok2017DWMLComplexDLNetworks, OMalley2017DWMLNNBinaryMatrixFactorization, Ottaviani2018DWMLLowRankMatrixFactorization}. Recently, it has been shown that using the D-Wave quantum annealer can yield advantages in classification performance over state-of-the-art conventional approaches for certain computational biology problems using a linear classifier \cite{Li2018TFDNABindingAffinity}. In this paper, we improve on these results by replacing the linear classifier with a superior nonlinear classification approach, the kernel-based support vector machine (SVM) \cite{schoelkopf2002learningwithkernels, Bishop2006MachineLearning}. We introduce its formulation for a D-Wave quantum annealer and present training results for both synthetic data and real data. To distinguish between the SVM formulations, we use the word \emph{classical} to denote the original version of an SVM as defined in \cite{schoelkopf2002learningwithkernels}. The field of supervised machine learning deals with the problem of learning model parameters from a set of labeled training data in order to make predictions about test data. SVMs in particular are known for their stability (in comparison to decision trees or deep neural networks \cite{Li2002DecisionTreeInstability, Yuan2003DecisionTreesVSSVMs, Xu2009RobustnessSVM, Raczko2017SVMvsRandomForestandNN}), in the sense that small differences in the training data do not generally produce huge differences in the resulting classifiers. Moreover, kernel-based SVMs profit from the \emph{kernel trick}, effectively maneuvering around the ``curse of dimensionality'' \cite{schoelkopf2002learningwithkernels,numericalrecipes}. In contrast to Deep Learning, which often requires large amounts of training data, SVMs are typically used when only small sets of training data are available. But also in combination with Deep Learning, where SVMs are applied on top of neural networks to classify the detected features, SVMs have been found to yield significant gains in classification performance \cite{Tang2013DLwithSVM, Kim2013DeepNetworkWithSVM, Lazri2018SVMwithANNandRF, Zareapoor2018KernelSVMwithDL}. Quantum annealers manufactured by D-Wave Systems Inc.~are available with about 2000 qubits \cite{Harris2010DWave, Johnson2011DWave, Bunyk2014DWave, DW2000Q}. They automatically produce a variety of close-to-optimal solutions to a given optimization problem \cite{Mott2017HiggsQML, Li2018TFDNABindingAffinity, DW2000Q}. This is particularly interesting in the context of machine learning, because any of the solutions produced for a given \emph{training dataset} has the potential to perform well on new \emph{test data}. For SVMs, for which the original solution is the \emph{global optimum} of the underlying convex optimization problem for the training data \cite{Bishop2006MachineLearning}, it is an interesting question whether the ensemble of different solutions from the quantum annealer can improve the classification performance for the test data. We conduct our SVM experiments on a D-Wave 2000Q (DW2000Q) quantum annealer \cite{DW2000Q}. Quantum annealing (QA) is so far the only paradigm of quantum computing for which processors of a reasonable size are available. The other paradigm of quantum computing, i.e., the gate-based (or universal) quantum computer \cite{NielsenChuang}, is still limited to less than 100 quantum bits (qubits) \cite{NationalAcademyOfSciences2018QuantumComputing}. It is worth mentioning that for gate-based quantum computers, a quantum algorithm for SVMs has already been proposed \cite{Rebentrost2014gatebasedQSVMtheory}. However, only a few very simple tasks, for which almost all classification was already done in the preprocessing step, have been studied experimentally \cite{Li2015gatebasedQSVMexperiment}. QA requires the formulation of the computational problem as a quadratic unconstrained binary optimization (QUBO). A QUBO problem is defined as the minimization of the energy function \begin{align} \label{eq:qubo} E = \sum_{i\le j} a_i Q_{ij} a_j, \end{align} where $a_i\in\{0,1\}$ are the binary variables of the optimization problem, and $Q$ is an upper-triangular matrix of real numbers called the QUBO weight matrix. Note that the size of the DW2000Q quantum processor and the Chimera topology \cite{Bunyk2014DWave} impose certain restrictions on this matrix. A popular alternative formulation of the problem in terms of variables $s_i\in\{-1,1\}$ is known as the Ising model \cite{Ising1925, Barahona1982IsingSpinGlassModel}. We present a formulation of SVMs as a QUBO defined by \equref{eq:qubo} and discuss certain mathematical properties in the training of SVMs that make it particularly appealing for use on a quantum annealer. In comparison to the classical SVM, we find that a combination of the solutions returned by the quantum annealer often surpasses the single solution of the classical SVM. This paper is structured as follows: In \secref{sec:SVM}, we introduce the classical SVM, our formulation of an SVM for QA, and the metrics we use to compare the performance of both. \ssecref{sec:applications} contains the application of both SVM versions to synthetic two-dimensional data and real data from biology experiments, including the calibration, training, and testing phase. We conclude our study with a short discussion in \secref{sec:conclusion}. \section{SVMs on a quantum annealer} \label{sec:SVM} In this section, we first briefly review the classical SVM, and then introduce the QA version of an SVM. Finally, we discuss ways to evaluate the classification performance in the applications presented in the next section. \subsection{The classical SVM} \label{sec:cSVM} An SVM is a supervised machine-learning algorithm for classification and regression. It operates on a dataset \begin{align} \label{eq:data} D = \{ (\mathbf x_n, t_n) : n = 0,\ldots,N-1 \}, \end{align} where $\mathbf x_n \in \mathbb R^d$ is a point in $d$-dimensional space (a \emph{feature vector}), and $t_n$ is the target label assigned to $\mathbf x_n$. We consider the task of learning a binary classifier that assigns a class label $t_n = \pm 1$ for a given data point $\mathbf x_n$. In the following, we call the class $t_n = 1$ ``positive'' and the class $t_n = -1$ ``negative''. Training an SVM amounts to solving the quadratic programming (QP) problem \cite{numericalrecipes} \begin{align} &\text{minimize} && E = \frac 1 2 \sum\limits_{nm} \alpha_n \alpha_m t_n t_m k(\mathbf x_n, \mathbf x_m)\nonumber\\ \label{eq:qp} &&&\qquad - \sum\limits_n \alpha_n,\\ \label{eq:qpb} &\text{subject to} && 0 \le \alpha_n \le C, & \\ \label{eq:qpzero} &\text{and} && \sum\limits_n \alpha_n t_n = 0, \end{align} for $N$ coefficients $\alpha_n\in\mathbb R$, where $C$ is a regularization parameter and $k(\cdot,\cdot)$ is the kernel function of the SVM \cite{schoelkopf2002learningwithkernels}. The resulting coefficients $\alpha_n$ define a $(d-1)$-dimensional decision boundary that separates $\mathbb R^d$ in two regions corresponding to the predicted class label. A typical solution often contains many $\alpha_n=0$. The decision boundary is then determined by the points corresponding to $\alpha_n\neq0$ (the \emph{support vectors} of the SVM). A prediction for an arbitrary point $\mathbf x\in\mathbb R^d$ can be made by evaluating the decision function \begin{align} \label{eq:decisionfunction} f(\mathbf x) = \sum\limits_n \alpha_n t_n k(\mathbf x_n,\mathbf x) + b, \end{align} where a reasonable choice to determine the bias $b$ is given by \cite{numericalrecipes} \begin{align} \label{eq:biasaveraging} b = \frac{\sum\limits_n \alpha_n (C-\alpha_n) \left[t_n - \sum\limits_m \alpha_m t_m k(\mathbf x_m,\mathbf x_n)\right]} {\sum\limits_n \alpha_n (C-\alpha_n)}. \end{align} Geometrically, the decision function $f(\mathbf x)$ represents a signed distance between the point $\mathbf x$ and the decision boundary. Thus the class label for $\mathbf x$ predicted by the trained SVM is $\widetilde{t} = \mathrm{sign}(f(\mathbf x))$. The formulation of the problem given in \equsref{eq:qp}{eq:qpzero} is the so-called dual formulation of an SVM (see \cite{Bishop2006MachineLearning} for more information). Since it represents a convex quadratic optimization problem, it is one of the rare minimization problems in machine learning that have a global minimum. Note, however, that the global minimum with respect to the training dataset $D$ may not necessarily be optimal for generalizing to the test dataset. Kernel-based SVMs are particularly powerful since they allow for nonlinear decision boundaries defined by $f(\mathbf x)=0$ (see \equref{eq:decisionfunction}), implicitly mapping the feature vectors to higher-dimensional spaces \cite{Burges1998SVMTutorial}. Interestingly, the complexity of the problem does not grow with this dimension, since only the value of the kernel functions $k(\mathbf x_n, \mathbf x_m)$ enters the problem specification (see \equref{eq:qp}). This fact is known as the \emph{kernel trick} \cite{schoelkopf2002learningwithkernels,numericalrecipes}. We use a Gaussian kernel (also known as radial basis-function kernel or rbf kernel) defined by \begin{align} \label{eq:rbf} \mathrm{rbf}(\mathbf x_n, \mathbf x_m) = e^{-\gamma\|\mathbf x_n - \mathbf x_m\|^2}, \end{align} where the value of the hyperparameter $\gamma>0$ is usually determined in a calibration procedure prior to the training phase. When no particular set of values for $\gamma$ is known for the data, a good strategy is to try exponentially growing sequences like $\gamma \in \{ \ldots, 2^{-3}, 2^{-2}, \ldots \}$ \cite{Hsu1992PracticalGuideSVM}. Gaussian kernels have the advantage of not suffering as much from numerical difficulties as polynomial kernels \cite{Hsu1992PracticalGuideSVM} and, in general, compare favourably to sigmoid or tanh kernels (which are, strictly speaking, not positive semi-definite) \cite{Lin2003SVMsigmoidkernel}. They implicitly map the feature vector onto an infinite-dimensional space \cite{Bishop2006MachineLearning}. In principle, a Gaussian kernel also includes the linear kernel as an asymptotic case \cite{Keerthi2003SVMasymptoticRBFkernel}. However, we explicitly include a linear kernel for convenience, denoted by the special value $\gamma=-1$. Therefore, we formally define \begin{align} \label{eq:kernel} k(\mathbf x_n, \mathbf x_m) := \begin{cases} \mathrm{rbf}(\mathbf x_n, \mathbf x_m) & (\gamma > 0) \\ \mathbf x_n \cdot \mathbf x_m & (\gamma = -1), \end{cases} \end{align} as the kernel function for our experiments. \boxit{ In the following, we symbolically write $\texttt{cSVM}(C,\gamma)$ to denote the training of the classical SVM defined by \equsref{eq:qp}{eq:qpzero} with the kernel function given in \equref{eq:kernel}. } For the computational work associated with \texttt{cSVM}, we studied both a quadratic programming solver \cite{numericalrecipes} and two software packages optimized for the task \cite{Chang2001LibSVM, scikitlearn}. \subsection{The quantum SVM} \label{sec:qSVM} The solution to \equsref{eq:qp}{eq:qpzero} consists of real numbers $\alpha_n\in\mathbb R$. However, the DW2000Q can only produce discrete, binary solutions to a QUBO (see \equref{eq:qubo}). Therefore, we use an encoding of the form \begin{align} \label{eq:encoding} \alpha_n = \sum\limits_{k=0}^{K-1} B^k a_{Kn+k}, \end{align} where $a_{Kn+k} \in\{0,1\}$ are binary variables, $K$ is the number of binary variables to encode $\alpha_n$, and $B$ is the base used for the encoding. In practice, we obtained good results for $B=2$ or $B=10$ and a small number of $K$ (see also the list of arguments given below). To formulate the QP problem given in \equsref{eq:qp}{eq:qpzero} as a QUBO (see \equref{eq:qubo}), we use the encoding defined in \equref{eq:encoding} and introduce a multiplier $\xi$ to include the second constraint given in \equref{eq:qpzero} as a squared penalty term. We obtain \begin{align} E &= \frac 1 2 \sum\limits_{nmkj} a_{Kn+k} a_{Km+j} B^{k+j} t_n t_m k(\mathbf x_n, \mathbf x_m)\nonumber\\ \label{eq:qsvmfull} &\quad - \sum\limits_{nk} B^k a_{Kn+k} + \xi \left(\sum\limits_{nk} B^k a_{Kn+k} t_n\right)^2 \\ &= \sum\limits_{n,m=0}^{N-1} \sum\limits_{k,j=0}^{K-1} a_{Kn+k} \widetilde{Q}_{Kn+k,Km+j} a_{Km+j}, \end{align} where $\widetilde{Q}$ is a matrix of size $KN\times KN$ given by \begin{align} \widetilde{Q}_{Kn+k,Km+j} &= \frac 1 2 B^{k+j} t_n t_m (k(\mathbf x_n, \mathbf x_m)+\xi) \nonumber\\ \label{eq:qsvmqubo} &- \delta_{nm} \delta_{kj} B^k. \end{align} Since $\widetilde{Q}$ is symmetric, the upper-triangular QUBO matrix $Q$ required for the QUBO formulation given in \equref{eq:qubo} is defined by $Q_{ij}=\widetilde{Q}_{ij}+\widetilde{Q}_{ji}$ for $i<j$ and $Q_{ii} = \widetilde{Q}_{ii}$. Note that the constraint \equref{eq:qpb} is automatically included in \equref{eq:qsvmfull} through the encoding given in \equref{eq:encoding}, since the maximum for $\alpha_n$ is given by \begin{align} \label{eq:boxconstraintparameter} C = \sum\limits_{k=1}^K B^k, \end{align} and $\alpha_n\ge0$ by definition. Given $K$, each $\alpha_n$ can take only $2^K$ different values according to \equref{eq:encoding}. At first, it may seem questionable why a small number of $B$ and $K$ should be sufficient. The following arguments and empirical findings for SVMs motivated us to try the QUBO approach: \begin{enumerate} \item A typical solution to \equsref{eq:qp}{eq:qpzero} consists of many $\alpha_n = 0$ with only a few $\alpha_m \neq 0$ (the corresponding data points $\{\mathbf x_m\}$ are the support vectors). On a digital computer using floating-point numbers, establishing convergence to exactly $0$ is a subtle task, whereas the encoding in \equref{eq:encoding} directly includes this value. \item The box constraint \equref{eq:qpb} is automatically satisfied by the choice of the encoding \equref{eq:encoding} (see \equref{eq:boxconstraintparameter}). \item In principle, one can extend the encoding \equref{eq:encoding} to fractional numbers by replacing the base $B^k$ with $B^{k-k_0}$ for some $k_0\in\mathbb N$. Eventually, this would yield the same range of floating-point numbers as used in conventional digital computers, namely the IEEE standard for floating-point arithmetic \cite{ieee754std}. However, it was observed that this kind of precision is not required for SVMs to produce reasonable results (see \cite{Lesser2011SVMwithReducedFloatPrecision}), and it would also not be feasible with the current generation of QA devices. \item For the classification task addressed by an SVM, the global order of magnitude of all $\alpha_n$ is often not as important as the relative factors between different $\alpha_n$. This can be understood by studying the effect of substituting $\alpha_n\mapsto S\alpha_n$ for some factor $S$ in \equsref{eq:qp}{eq:qpzero}. Since $E$ and $E/S^2$ are optimal for the same $\{\alpha_n\}$, and the hyperparameters of the box constraint are calibrated separately, it only replaces the linear term in \equref{eq:qp} by $-\sum_n \alpha_n/S$. This term only affects the size of the margin between the decision boundary and the support vectors (see also \cite{Bishop2006MachineLearning}). However, if this is still found to be an issue, one can simply adjust the encoding \equref{eq:encoding} accordingly. \item Especially for the Gaussian kernel given in \equref{eq:rbf}, points with a large distance $\|\mathbf x_n - \mathbf x_m\|\gg1$ result in $k(\mathbf x_n,\mathbf x_m)\approx0$. This can be used to reduce couplings between the qubits such that embedding the problem on the quantum annealer is less complex. This may either yield better solutions or allow larger problems to be embedded on the DW2000Q. \item The constraint $\sum_n a_n t_n=0$ mathematically corresponds to an optimal bias $b$ in the decision function given in \equref{eq:decisionfunction} (see \cite{Bishop2006MachineLearning}). We have included it in \equref{eq:qsvmfull} through the multiplier $\xi$. However, the constraint need not be satisfied exactly for the classification task to produce good results. Since the bias $b$ is only one parameter, it can easily be adjusted afterwards if necessary. For this reason, it can be that $\xi=0$ already suffices to get reasonable results. Furthermore, the special value $\xi=1$ yields the Mangasarian-Musicant variant of an SVM (see \cite{MangasarianMusicant1999SVMoverrelaxation, MangasarianMusicant2001NonlinearGeneralizedSVM} for more information). This variant has been shown to produce equally good classifiers while, at the same time, being numerically much more tractable \cite{numericalrecipes}. An alternative approach would be to include $\xi$ in the parameter set that has to be optimized (as conventionally done for Lagrange multipliers) by choosing an additional encoding for $\xi$ such as \equref{eq:encoding}. In this case, it would suffice to replace the last term in \equref{eq:qsvmfull} by the linear penalty term $\xi\sum_n a_n t_n$. We experimented with this approach and it yields similar but less robust results (data not shown). For this reason, and due to the (on present quantum annealers) small set of numbers represented by the encoding \equref{eq:encoding}, and also because of the SVM's sensitivity to the bias, we found it more convenient to keep $\xi$ as a hyperparameter, and if necessary adjust the bias afterwards (see also \appref{app:bias}). \end{enumerate} The last step required to run the optimization problem on the DW2000Q is the embedding procedure \cite{Choi2008Embedding, Cai2014DWaveEmbedding}. It is necessary because in general, the QUBO given in \equref{eq:qubo} includes some couplers $Q_{ij} \neq 0$ between qubit $i$ and qubit $j$ for which no physical connection exists on the chip (the connectivity of the DW2000Q is given by the Chimera topology \cite{Bunyk2014DWave}). The idea of embedding is to combine several physical qubits to one logical qubit (also called \emph{chain}) by choosing a large negative value for their coupling strengths to favor solutions where the physical qubits are aligned. This can be used to increase the logical connectivity between the qubits. We use a function provided by D-Wave Systems Inc.~to generate embeddings for the QUBOs given by \equref{eq:qsvmqubo} \cite{DWOceanSDK}. When no embedding can be found, we successively decrease the number of nonzero couplers $n_{\mathrm{cpl}}$ by setting the smallest couplers to zero until an embedding is found. This works especially well in combination with the Gaussian kernel given in \equref{eq:rbf}, where points with a large squared distance $\|\mathbf x_n - \mathbf x_m\|^2$ only produce negligible contributions to the QUBO. Typical values for $n_{\mathrm{cpl}}$ for the applications discussed in \secref{sec:applications} are between 1600 and 2500, while the number of required qubits ranges from 28 to 114 with peaks at 56, 58, 84, and 87. We chose to test the default mode of operation of the DW2000Q with an annealing time of $20\,\mu\mathrm{s}$ and leave the analysis of improving the QA results by advanced features like reverse annealing, spin-reversal transforms, special annealing schedules, or alternative embedding heuristics to the future \cite{Ohkuwa2018DWaveReverseAnnealing, Boixo2013ExperimentalSignatureQA, DW2000Q}. To summarize, the final QA version of the SVM defined by the QUBO in \equref{eq:qsvmqubo} depends on the following hyperparameters: the encoding base $B$, the number $K$ of qubits per coefficient $\alpha_n$, the multiplier $\xi$, and the kernel parameter $\gamma$ (the number $n_{\mathrm{cpl}}$ of strongest couplers embedded on the DW2000Q is different for every run and is not a parameter of the SVM itself). \boxit{ We denote the QA version of an SVM defined in \equref{eq:qsvmqubo} as $\texttt{qSVM}(B,K,\xi,\gamma)$, by analogy with $\texttt{cSVM}(C,\gamma)$ defined in \equsref{eq:qp}{eq:qpzero}, } For each run on the DW2000Q, we consider the twenty lowest-energy samples from 10,000 reads, denoted by $\texttt{qSVM}(B,K,\xi,\gamma)\#i$ for $i=0,\ldots,19$. Note that the cut at $i=20$ is arbitrary; one could also consider 50 or more samples from the distribution if appropriate. In principle, it can happen that a particular sample $\#i$ yields only $\alpha_n=0$ or $\alpha_n=C$ such that the bias $b$ in \equref{eq:biasaveraging} is undefined. This reflects the rare situation that no support vectors have been found. In this case, one may simply discard the affected sample and consider only the remaining samples. \subsection{Evaluating the classification} \label{sec:evaluation} We consider a separation of the data $D$ given in \equref{eq:data} into two disjoint subsets $D^{(\mathrm{train})}$ and $D^{(\mathrm{test})}$. The training data $D^{(\mathrm{train})}$ is used to learn a set of coefficients $\{\alpha_n\}$ using $\texttt{cSVM}(C,\gamma)$ or $\texttt{qSVM}(B,K,\xi,\gamma)$. The result is then evaluated by comparing the class prediction $\widetilde{t_n} = \mathrm{sign}(f(\mathbf x_n))$ (see \equref{eq:decisionfunction}) with the true label $t_n$ for each $(\mathbf x_n,t_n)\in D^{(\mathrm{test})}$ from the test data. Note that the DW2000Q produces a variety of close-to-optimal solutions (i.e., a variety of different coefficients $\{\alpha_n\}^{(i)}$ obtained from \equref{eq:encoding}). Many of these solutions may have a slightly higher energy than the global minimum $\{\alpha_n\}^*$ found by \texttt{cSVM}, but still solve the classification problem for the training data as intended. The different solutions often emphasize different features of the training data. When applied to the test data, a combination of these solutions has the potential to solve the classification task better than \texttt{cSVM}, which only yields the global minimum for the training data. A simple measure to judge the classifier defined by the set of coefficients $\{\alpha_n\}$ would be the count of correct predictions divided by the size of the test set $|D^{(\mathrm{test})}|$. The resulting ratio is the \emph{classification accuracy}. However, in binary classification problems, accuracy is generally considered a bad measure for classifiers \cite{Provost1998AccuracyBadMeasure, Cortes2003AUROCvsErrorRate}, because a higher accuracy does not necessarily imply that the classifier is better. As a simple example, consider a dataset with 80\% negatives, where a trivial classifier returning always $-1$ would get an accuracy of 80\%, while being practically useless. In contrast, we are often interested in identifying good positives, at the cost of sometimes making an incorrect decision, or vice versa. These more desirable properties are measured by the metrics AUROC (area under the Receiver Operating Characteristic curve) and AUPRC (area under the Precision-Recall curve) \cite{Cortes2003AUROCvsErrorRate, DavisGoadrich2006AUROCandAUPRC}. They can be computed by counting the number of the four different cases that can occur when making the class prediction $\widetilde{t_n}=\mathrm{sign}(f(\mathbf x_n))$: the number TP of true positives where $\widetilde{t_n}=t_n=1$, the number FP of false positives where $\widetilde{t_n}=1$ but $t_n=-1$, the number TN of true negatives where $\widetilde{t_n}=t_n=-1$, and the number FN of false negatives where $\widetilde{t_n}=-1$ but $t_n=1$ (note that the sum of the four counts is equal to the number of test data points $|D^{(\mathrm{test})}|$). Given these counts, one can compute the true positive rate $\text{TPR} = \text{TP}/(\text{TP}+\text{FN})$ (also known as Recall), the false positive rate $\text{FPR} = \text{FP}/(\text{FP}+\text{TN})$, and the $\text{Precision}=\text{TP}/(\text{TP}+\text{FP})$ (defined to be $1$ if $\text{TP}+\text{FP}=0$). The crucial step to generate a curve from these points is made by sweeping the bias $b$ in the decision function $f(x)$ (see \equref{eq:decisionfunction}). This procedure artificially moves the decision boundary through all test data points, thereby measuring the characteristic shape of the decision boundary: For $b\to-\infty$, the classifier always predicts $-1$, resulting in $\text{TPR}=\text{FPR}=\text{Recall}=0$ and $\text{Precision}=1$. Similarly, for $b\to\infty$, the classifier always predicts $1$ such that $\text{TPR}=\text{FPR}=\text{Recall}=1$ and $\text{Precision}$ equals the number of positives divided by $N$. By sweeping $b$ and plotting TPR vs.~FPR, one generates the ROC curve, and by plotting Precision vs.~Recall one generates the Precision-Recall curve (see below for an example of these curves). The area under both curves is termed AUROC and AUPRC, respectively, and represents a much more robust measure for the quality of a classifier than the accuracy. This means that optimizing a classifier for AUROC and AUPRC is unlikely to result in a useless classifier, which can happen when optimizing for the accuracy instead \cite{Cortes2003AUROCvsErrorRate}. Note, however, that when searching for a good bias $b$, optimizing for the accuracy with respect to the training data is reasonable, because changing $b$ does not affect AUROC and AUPRC. In the following applications, we use both AUROC and AUPRC to compare the classifiers, but for completeness, we also report the classification accuracy. \section{Applications} \label{sec:applications} \subsection{Two-dimensional synthetic data} As a proof of concept and to understand the power of $\texttt{qSVM}$, we consider a small set of two-dimensional synthetic data. This has the advantage that the results can be easily visualized and the quality of the many different classifiers returned by the quantum annealer can be compared. The dataset $D$ consists of $n=1,\ldots,40$ points $(\mathbf x_n,t_n)$, where the first half corresponds to the negative class $t_n=-1$ representing an outer region, and the second half corresponds to the positive class $t_n=1$ representing an inner region. It was generated according to \begin{align} \label{eq:toydatageneration} \mathbf x_n &= r_n \begin{pmatrix} \cos \varphi_n \\ \sin \varphi_n \end{pmatrix} + \begin{pmatrix} s_n^x \\ s_n^y \end{pmatrix}, \end{align} where $r_n = 1$ if $t_n=-1$ and $r_n = 0.15$ if $t_n=1$, $\varphi_n$ is linearly spaced on $[0,2\pi)$ for each class, and $s_n^x$ and $s_n^y$ are drawn from a normal distribution with mean $0$ and standard deviation $0.2$. We visualize the resulting decision boundaries $f(\mathbf x)=0$ for $\texttt{cSVM}(3,16)$ in \figref{fig:toyproblem}(a), and for three separate solutions from the ensemble found by $\texttt{qSVM}(2,2,0,16)$ in \figref{fig:toyproblem}(b)--(d). For demonstration purposes, the plotted data points do not come from a separate test set but are the same $40$ points that the SVM versions have been trained on. The value of the decision function $f(\mathbf x)$ given in \equref{eq:decisionfunction} determines the background color, obtained by evaluating $f(\mathbf x)$ for each point $\mathbf x$ in the two-dimensional plotting grid. \begin{figure} \centering \includegraphics[width=\linewidth]{toyproblem.pdf} \caption{(Color online) Visualization of the classification boundary resulting from (a) the global optimum produced by the classical SVM, and (b)--(d) various solutions from the ensemble produced by the QA version of the SVM for the same problem (the identifier $\texttt{qSVM}\#i$ indicates the $(i+1)^{\mathrm{th}}$ sample produced by the DW2000Q, starting at $i=0$ and ordered by lowest energy). The parameters for the SVMs are $B=K=2$, $\xi=0$, $\gamma=16$, and $C=3$. The two classes for the two-dimensional synthetic data are plotted as red squares ($t_n=1$) and blue circles ($t_n=-1$), respectively. The corresponding background color indicates the distance to the decision boundary.} \label{fig:toyproblem} \end{figure} \begin{figure*} \centering \includegraphics[width=\linewidth]{datahandling.pdf} \caption{Data handling procedure for the computational biology problem. Each of the nine datasets is split into 90\% calibration and training data $D^{(\mathrm{train})}$ and 10\% test data $D^{(\mathrm{test})}$. In the calibration phase, 10-fold Monte Carlo cross-validation is used to select the hyperparameters $B$, $K$, $\xi$, and $\gamma$ (see \secref{sec:qSVM}), training on 2\% of $D^{(\mathrm{train})}$ and validating on the rest. In the test phase, the selected $\texttt{qSVM}(B,K,\xi,\gamma)$ is applied to every 2\% slice of $D^{(\mathrm{train})}$. The resulting classifiers are combined to classify the test data $D^{(\mathrm{test})}$ to evaluate the AUROC, the AUPRC, and the classification accuracy (see \secref{sec:evaluation}). The test procedure is repeated 10 times to gather statistics.} \label{fig:datahandling} \end{figure*} We see that \texttt{cSVM} shown in \figref{fig:toyproblem}(a) satisfies all the properties expected from the global minimum of an SVM, i.e., separating the dataset into two regions where the decision boundary has a maximum margin to the closest data points (the support vectors). The DW2000Q, however, automatically produces a variety of alternative classifiers shown in \figref{fig:toyproblem}(b)--(d). Each of them solves the classification task of the training set as intended, and additionally highlights different features present in the training data. While sample \#1 shown in \figref{fig:toyproblem}(b) still resembles the properties of the global minimum, sample \#6 shown in \figref{fig:toyproblem}(c) yields a more narrow enclosure of the outer circle. The classifier from sample \#16 shown in \figref{fig:toyproblem}(d) is even sensitive to the gaps in the outer circle. This result suggests that a combination of the classifiers returned by $\texttt{qSVM}$ may be more powerful than the single classifier produced by $\texttt{cSVM}$. \subsection{Application to real data} As an application to real data, we apply the QA version of the SVM introduced in \secref{sec:SVM} to data from the computational biology problem studied in \cite{Li2018TFDNABindingAffinity} (see also \cite{Zhou2015TFDNABindingAffinity, Yang2017TFDNAbindingHTSELEX}). Briefly, the classification task is to decide whether a certain protein (a transcription factor labeled Mad, Max, or Myc) binds to a certain DNA sequence such as CCCACGTTCT. The data consists of nine separate datasets labeled Mad50, Max50, Myc50, Mad70, Max70, Myc70, Mad80, Max80, and Myc80. The datasets consist of $N=1655$ (Mad), $N=1599$ (Max), and $N=1584$ (Myc) data points, respectively. The data points $(\mathbf x_n, t_n)$ for $n=1,\ldots,N$ consist of a 40-dimensional vector $\mathbf x_n\in \{-1,+1\}^{40}$ representing the DNA sequence, and a label indicating whether the protein binds to this DNA sequence ($t_n=+1$) or not ($t_n=-1$). The DNA sequence is encoded by mapping each base-pair in the DNA alphabet \{A,C,G,T\} according to $\mathrm A\mapsto(+1,-1,-1,-1)$, $\mathrm C\mapsto(-1,+1,-1,-1)$, $\mathrm G\mapsto(-1,-1,+1,-1)$, and $\mathrm T\mapsto(-1,-1,-1,+1)$, and concatenating all encoded base-pairs. An encoding of this type is sometimes called \emph{one-hot encoding} (often using 0 instead of $-1$) since only one element in each encoded base-pair is $+1$ (cf.~also \cite{Li2018TFDNABindingAffinity, Zhou2015TFDNABindingAffinity}). For each dataset, the number behind the protein label indicates the percentage of negative classes such that e.g.~the dataset Max80 contains 80\% non-binding DNA sequences ($t_n=-1$) and 20\% binding DNA sequences ($t_n=+1$). We separate each of the nine dataset into 90\% training data $D^{(\mathrm{train})}$ and 10\% test data $D^{(\mathrm{test})}$. The training data is used for calibration of the hyperparameters and for training the classifiers. The test data is unseen during training and exclusively used to test the classifiers in the test phase. The entire data handling procedure is sketched in \figref{fig:datahandling}. \subsubsection{Calibration phase: Results for a small training dataset} To select the hyperparameters of $\texttt{qSVM}$, we use 10-fold Monte Carlo (or split-and-shuffle) cross-validation. This means that we train $\texttt{qSVM}(B,K,\xi,\gamma)$ on 2\% of $D^{(\mathrm{train})}$ (approximately 30 data points) and evaluate its performance on the remaining data points of $D^{(\mathrm{train})}$ for validation. The data is then shuffled and the process is repeated a total number of ten times (see \figref{fig:datahandling}). \begin{figure} \centering \includegraphics[width=\linewidth]{rocprc_max80p2.pdf} \caption{(Color online) Example for the generated ROC and PR curves to measure the quality of the classifiers. (a) $\texttt{qSVM}(10,3,0,-1)\#14$ using $n_{\mathrm{cpl}}=2000$ couplers, and (b) $\texttt{cSVM}(111,-1)$ (note that $C=111$ for \texttt{cSVM} corresponds to $B=10$ and $K=3$, see \equref{eq:boxconstraintparameter}). Both SVMs have been trained and validated on the same data, taken from the fifth step in the 10-fold cross-validation procedure for the dataset Max80 \cite{Li2018TFDNABindingAffinity}.} \label{fig:rocprc} \end{figure} The small fraction of 2\% was chosen because of the size limitations of the quantum annealer (cf.~also \cite{Li2018TFDNABindingAffinity}). Since this is a very small amount of data, we performed some initial tests before systematically calibrating the hyperparameters. In these tests, we observed that $\texttt{qSVM}$ can produce significantly stronger classifiers than $\texttt{cSVM}$ for the same little training data and parameters. One example is shown in \figref{fig:rocprc}, where the ROC and PR curves are plotted for $\texttt{qSVM}(10,3,0,-1)\#14$ (see \figref{fig:rocprc}(a)) and for $\texttt{cSVM}(111,-1)$ (see \figref{fig:rocprc}(b)), generated by sweeping the bias $b$ as explained in \secref{sec:evaluation}. While the QA version produces almost optimal curves, the global optimum from the classical SVM obviously lacks precision when applied to the much larger validation data. For each dataset, the hyperparameters are calibrated by evaluating $\texttt{qSVM}$ for $B\in\{2,3,5,10\}$ and $K\in\{2,3\}$ (cf.~\equref{eq:encoding}), $\xi\in\{0,1,5\}$ (cf.~\equref{eq:qsvmfull}), and $\gamma\in\{-1,0.125,0.25,0.5,1,2,4,8\}$ (cf.~\equref{eq:kernel}). We generically consider the classifiers $\{\alpha_n^{(i)}\}$ from the twenty best solutions $\texttt{qSVM}(B,K,\xi,\gamma)\#i$ for $i=0,\ldots,19$ as described in \secref{sec:qSVM}. The evaluation is repeated ten times for the Monte Carlo cross-validation. Therefore, each set of hyperparameters for each dataset results in a total of 200 values for AUROC, AUPRC, and accuracy. \begin{figure} \centering \includegraphics[width=\linewidth]{calibration_max70p2.pdf} \caption{(Color online) Calibration performance of \texttt{qSVM} for the best sets of hyperparameters $(B,K,\xi,\gamma)$, ordered by mean AUROC, for the dataset Max70 \cite{Li2018TFDNABindingAffinity}. Shown are the AUROC (blue dashed line), the AUPRC (red dash-dotted line), the accuracy (green dotted line), and the respective standard deviations (shaded areas) over 200 classifiers (10 different calibration folds times 20 of the best solutions from the DW2000Q). Lines connecting the averages are guides to the eye. Squares, circles, and triangles denote the maximum performance among each of the 200 classifiers.} \label{fig:calibration} \end{figure} An example of the calibration procedure for the dataset Max70 is shown in \figref{fig:calibration}. For this dataset, we see that the linear kernels denoted by $\gamma=-1$ (see \equref{eq:kernel}) dominate (but Gaussian kernels perform still reasonably well). The selected set of hyperparameters in this case is $B=10$, $K=3$, $\xi=5$, and $\gamma=-1$, corresponding to the leftmost points in \figref{fig:calibration}. We also see fluctuations in the mean accuracy which are not reflected by AUROC and AUPRC. Since AUROC and AUPRC are insensitive to the bias, this indicates that the choice for the bias $b$ given by \equref{eq:biasaveraging} may not always be optimal (see \appref{app:bias} for a way to improve the bias if the accuracy matters). We selected the hyperparameters based on both mean AUROC and AUPRC. The reason for this is that we observed, when selecting exclusively based on the best AUPRC (cf.~\cite{Li2018TFDNABindingAffinity}), we sometimes obtained hyperparameters yielding $\mathrm{AUROC}\approx0.5$ (the result for a random classifier \cite{Cortes2003AUROCvsErrorRate}). \begin{table} \caption{\label{tab:calibration} Selected hyperparameters for each dataset \cite{Li2018TFDNABindingAffinity}. The parameters are the base $B$, the number $K$ of qubits per coefficient $\alpha_n$, the multiplier $\xi$, the kernel parameter $\gamma$, and the box constraint parameter $C$ (see \secref{sec:SVM}). The value of $C$ is fixed by $B$ and $K$ through \equref{eq:boxconstraintparameter} and is given for reference only.} \begin{ruledtabular} \begin{tabular}{@{}lccccc@{}} Dataset & $B$ & $K$ & $\xi$ & $\gamma$ & $C$\\ \colrule {Mad50} & $2$ & $3$ & $5$ & $0.125$ & $7$ \\ {Max50} & $2$ & $3$ & $5$ & $0.125$ & $7$ \\ {Myc50} & $2$ & $2$ & $0$ & $0.125$ & $3$ \\ {Mad70} & $10$ & $3$ & $5$ & $-1$ & $111$ \\ {Max70} & $10$ & $3$ & $5$ & $-1$ & $111$ \\ {Myc70} & $10$ & $3$ & $5$ & $-1$ & $111$ \\ {Mad80} & $10$ & $3$ & $5$ & $-1$ & $111$ \\ {Max80} & $10$ & $3$ & $0$ & $-1$ & $111$ \\ {Myc80} & $10$ & $3$ & $5$ & $-1$ & $111$ \\ \end{tabular} \end{ruledtabular} \end{table} In \tabref{tab:calibration}, we list the best hyperparameters selected for each dataset. The trend from Gaussian kernels to linear kernels can be observed in all datasets: For Mad50, Max50, and Myc50, where half of the data is classified as positive and the other half as negative, only the Gaussian kernels can produce a reasonable decision boundary (see also \tabref{tab:results} in \appref{app:numericalresults}). But when going to higher class imbalances as present in the datasets Mad80, Max80, and Myc80, a linear decision boundary suffices to classify the DNA sequences. The numerical results of the calibration procedure for each dataset in comparison with the corresponding \texttt{cSVM} are listed in \tabref{tab:results} in \appref{app:numericalresults}. \subsubsection{Training and test phase: Results for a larger training dataset} In this section, we examine a way to overcome the size limitations of the DW2000Q for real applications with a bigger training dataset. We take the same nine DNA datasets as before, but now consider the full datasets $D^{(\mathrm{train})}$ for training a classifier. The goal is to construct an aggregated classifier from the results of $\texttt{qSVM}$ trained on each $2\%$ slice of the available training data (see Fig. \figref{fig:datahandling}). Each of the $L=50$ slices is labeled $D^{(\mathrm{train},l)}$ for $l=0,\ldots,49$. The hyperparameters for each dataset are taken from the calibration results listed in \tabref{tab:calibration}. The combined classifier is constructed in two steps. First, for each slice $D^{(\mathrm{train},l)}$, the twenty best solutions from the DW2000Q (labeled $\texttt{qSVM}(B,K,\xi,\gamma)\#i$ for $i=0,\ldots,19$) are combined by averaging over the respective decision functions $f^{(l,i)}(\mathbf x)$ (see \equref{eq:decisionfunction}). Since the decision function is linear in the coefficients and the bias ($b^{(l,i)}$ is computed from $\alpha_n^{(l,i)}$ via \equref{eq:biasaveraging}), this procedure effectively results in one classifier with an effective set of coefficients $\alpha_n^{(l)} = \sum_i \alpha_n^{(l,i)} / 20$ and an effective bias $b^{(l)} = \sum_i b^{(l,i)}/20$. The second step is to average over the $L=50$ slices. Note, however, that the data points $(\mathbf x_n^{(l)},t_n^{(l)})\in D^{(\mathrm{train},l)}$ are now different for each $l$. The full decision function is \begin{align} \label{eq:fulldecisionfunction} F(\mathbf x) = \frac 1 L \sum\limits_{nl} \alpha_n^{(l)} t_n^{(l)} k(\mathbf x_n^{(l)},\mathbf x) + b, \end{align} where $b=\sum_{l}b^{(l)}/L$. As before, a decision for the class label of a point $\mathbf x$ is obtained through $\widetilde{t} = \mathrm{sign}(F(\mathbf x))$. We use this decision function to evaluate the metrics discussed in \secref{sec:evaluation} for the test data $D^{(\mathrm{test})}$ using the procedure illustrated in \figref{fig:datahandling}. Note that in \cite{Li2018TFDNABindingAffinity}, instead of separating the training data into 50 disjoint subsets (each containing 2\% of the data), an approach similar to bagging (bootstrap aggregating) \cite{Breiman1996Bagging} was used. In that approach, 50 subsets are constructed by drawing $2\%$ of the training data \emph{with replacement}. We also tested this bagging inspired approach (data not shown) and found that, although the results were similar, the fluctuations were much larger. This makes sense because drawing with replacement means that different subsets can share the same data points and also include a single point more than once. Consequently, one may expect that some points are not included in any of the datasets. In fact, the probability that a certain $x\in D^{(\mathrm{train})}$ is not included in any of the $D^{(\mathrm{train},l)}$ is $(1-1/N)^N\approx 36.8\%$ for $N=|D^{(\mathrm{train})}|\approx1500$. Apart from this counting argument, the general observation in \cite{Breiman1996Bagging} was that bagging is better suited for \emph{unstable} classification algorithms, whereas SVMs are stable. We therefore conclude that splitting the training data in disjoint, equally-sized subsets is superior. As before, it is interesting to compare the results from the combined classifier with results from applying \texttt{cSVM} to the same data points and parameters. Note that \equref{eq:fulldecisionfunction} also applies to \texttt{cSVM}, but that $\alpha_n^{(l)}$ comes directly from the global minimum to \equsref{eq:qp}{eq:qpzero} and not from an average of the twenty best solutions produced by DW2000Q. The results for each dataset are shown in \figref{fig:finaltraining}, where the mean and the standard deviation have been obtained from ten repetitions of the test procedure as sketched in \figref{fig:datahandling}. \begin{figure} \centering \includegraphics[width=\linewidth]{finaltraining.pdf} \caption{(Color online) Performance of $\texttt{qSVM}$ (solid green line) and $\texttt{cSVM}$ (dash-dotted red line) as measured by (a) AUROC, (b) AUPRC, and (c) accuracy (see \secref{sec:evaluation}) using the decision function given in \equref{eq:fulldecisionfunction} for each of the nine datasets from the computational biology problem \cite{Li2018TFDNABindingAffinity}. The parameters for each dataset are taken from \tabref{tab:calibration}. The standard deviation over ten repetitions (see \figref{fig:datahandling}) is shown as shaded areas. Lines are guides to the eye.} \label{fig:finaltraining} \end{figure} \begin{figure} \centering \includegraphics[width=\linewidth]{finaltraining_heuristic.pdf} \caption{(Color online) Classification accuracy of $\texttt{qSVM}$ (solid green line) and $\texttt{cSVM}$ (dash-dotted red line) as shown in \figref{fig:finaltraining}(c), after adjusting the suboptimal bias $b$ to $b^*$ where the accuracy for the training data is higher (see \appref{app:bias}). The metrics AUROC and AUPRC are the same as in \figref{fig:finaltraining}(a) and (b).} \label{fig:finaltrainingheuristic} \end{figure} Based on the resulting accuracy shown in \figref{fig:finaltraining}(c), one could conclude that \texttt{cSVM} outperforms $\texttt{qSVM}$ (especially for the dataset Max80 for which we studied one of the contributing classifiers in \figref{fig:rocprc}). However, from the metrics AUROC and AUPRC reported in \figref{fig:finaltraining}(a) and (b), we find that the resulting classifiers from the QA version are in fact superior. This hints at a problem in the construction of the final decision function given in \equref{eq:fulldecisionfunction}, which would have been overlooked if the accuracy had not been evaluated: Recall that AUROC and AUPRC are generated by sweeping the bias $b$ in \equref{eq:fulldecisionfunction} to move the decision boundary through the feature space $\mathbb R^{40}$ from a full negative predictor to a fully positive predictor (see \secref{sec:evaluation}). If AUROC and AUPRC are better for $\texttt{qSVM}$, this means that the bias $b$ has been chosen suboptimally and there must be some bias $b^*$ for which the classifier produces better results. The reason for this is that \equref{eq:biasaveraging} from the original SVM may not be suited to obtain the optimal bias for the QA version of the SVM defined by \equref{eq:qsvmfull}. The condition for an optimal bias is the constraint \equref{eq:qpzero}, included through the multiplier $\xi$ in \equref{eq:qsvmfull}. Since $\xi=0$ for Max80 (cf.~\tabref{tab:calibration}), this explains the particularly bad accuracy for this dataset despite better AUROC and AUPRC (see also the discussion under point 6 of the motivations given in \secref{sec:qSVM}). We correct for the suboptimal bias by replacing $b$ with the $b^*$ for which the classification accuracy for $D^{(\mathrm{train})}$ is highest (see \appref{app:bias} for more information). Note that it is only allowed to use the training data $D^{(\mathrm{train})}$ for such modifications and not the test data. The classification accuracy of $\texttt{qSVM}$ after adjusting the bias for each dataset is shown in \figref{fig:finaltrainingheuristic}. It clearly improves the results for the linear kernel ($\gamma=-1$) with high class imbalance (Mad80, Max80, and Myc80). We also observe that the Gaussian kernel used for (Mad50, Max50, and Myc50) was not affected as strongly by the suboptimal bias. As changing the bias of the decision function given in \equref{eq:fulldecisionfunction} does not affect AUROC and AUPRC, the results shown in \figref{fig:finaltraining}(a) and (b) also apply to the adjusted version of $\texttt{qSVM}$. To summarize, we observe a better or comparative performance of $\texttt{qSVM}$ compared to \texttt{cSVM} for all datasets, as measured by AUROC, AUPRC, and classification accuracy. For completeness, the numerical results of the test are given in \tabref{tab:results} in \appref{app:numericalresults}. \section{Conclusion} \label{sec:conclusion} In this paper, we studied the implementation of kernel-based SVMs on a DW2000Q quantum annealer \cite{DW2000Q}. We found that the optimization problem behind the training of SVMs can be straightforwardly expressed as a QUBO and solved on a quantum annealer. The QUBO form exhibits certain mathematical advantages, such as its ability to produce exact zeros or the inherent inclusion of the box constraint. Each run of the training process on the quantum annealer yields a distribution of different classifiers that can later be used to classify arbitrarily many test data points. Our results show that the ensemble of classifiers produced by the quantum annealer often surpasses the single classifier obtained by the classical SVM for the same computational problem as measured by AUROC, AUPRC, and accuracy. The advantage stems from the fact that the DW2000Q produces not just the global optimum for the training data, but a distribution of many reasonably good, close-to-optimal solutions to the given optimization problem. A combination of these has the potential to generalize better to the test data. This observation is in line with findings in other machine learning problems studied on a quantum annealer \cite{Mott2017HiggsQML, Li2018TFDNABindingAffinity}. Therefore we conclude that the QA version of the SVM is a useful practical alternative to the classical SVM. If the capabilities of future quantum annealers continue to scale at the current pace, training SVMs on quantum annealers may become a valuable tool for classification problems, and can already be helpful for hard problems where only little training data is available. An interesting project for future research would be to examine other approaches to building strong classifiers by constructing weighted sums of the class predictions from several SVMs as done in boosting methods like AdaBoost or QBoost \cite{Neven2012QBoost, Freund1996AdaBoost, Friedman2000StatisticalViewBoosting, Bishop2006MachineLearning}. It would also be valuable to examine how the QA results for SVMs can be further improved using advanced features offered by the DW2000Q like reverse annealing, spin-reversal transforms, special annealing schedules, or enhanced embeddings \cite{Ohkuwa2018DWaveReverseAnnealing, Boixo2013ExperimentalSignatureQA, DW2000Q}. Furthermore, since SVMs can also be used for multi-class classification and regression tasks \cite{schoelkopf2002learningwithkernels}, it seems worthwhile to study corresponding applications to such problems using the QA formulation presented here. Finally, it would be a potentially interesting avenue to explore if suitable modifications to the original SVM can lead to an equally good distribution of solutions as the one produced by the quantum annealer. \section{Acknowledgments} We would like to thank Richard Li and Daniel Lidar for providing preprocessed data from TF-DNA binding experiments. We are grateful to Seiji Miyashita for helpful discussions. Access and compute time on the D-Wave machine located at the headquarters of D-Wave Systems Inc.~in Burnaby (Canada) were provided by D-Wave Systems Inc. D.W. is supported by the Initiative and Networking Fund of the Helmholtz Association through the Strategic Future Field of Research project ``Scalable solid state quantum computing (ZT-0013).'' \bibliographystyle{apsrev4-1custom}
{'timestamp': '2019-06-17T02:16:58', 'yymm': '1906', 'arxiv_id': '1906.06283', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06283'}
arxiv
\section{Introduction} In this work, we consider the problem of reinforcement learning (RL) for risk-sensitive policies under epistemic uncertainty, i.e. the uncertainty due to the agent not knowing how the environment responds to the agent's actions. This is in contrast to typical approaches in risk-sensitive decision making, which have focused on the aleatory uncertainty due to inherent stochasticity in the environment. Modelling risk-sensitivity in this way makes more sense for applications such as autonomous driving, where systems are nearly deterministic, and most uncertainty is due to the lack of information about the environment. In this paper, we consider epistemic uncertainty and risk sensitivity both within a Bayesian utilitarian framework. We develop novel algorithms for policy optimisation in this setting, and compare their performance quantitatively with policies optimised for the \emph{risk-neutral} setting. Reinforcement learning (RL) is a sequential decision-making problem under uncertainty. Typically, this is formulated as the maximisation of an expected return, where the return $\return$ is defined as the sum of scalar rewards obtained over time $\return \defn \sum_{t=1}^T r_t$ to some potentially infinite or random horizon $T$. As is common in RL, we assume that agents acting in a discrete Markov decision process (MDP). For any given finite MDP $\mdp \in \MDP$, the optimal risk-neutral policy $\pol^*(\mdp) \in \argmax_\pol \E_\mdp^\pol[\return]$ be found efficiently via dynamic programming algorithms. Because the learning problem specifies that $\mdp$ is unknown, the optimal policy under epistemic uncertainty must take into account expected information gain. In the Bayesian setting, we maintain a subjective belief in the form of a probability distribution $\bel$ over MDPs $\MDP$ and the optimal solution is given by: \begin{equation} \label{eq:bayes-maximisation} \max_\pol \E_\bel^\pol[\return] = \max_\pol \int_\MDP \E_\mdp^\pol[\return] \, d \bel(\mdp). \end{equation} This problem is generally intractable, as the optimisation is performed over \emph{adaptive} policies, which is exponentially large in the problem horizon. A risk-neutral agent would only wish to maximise expected return. However, we are interested in the case where the agent is risk-sensitive, and in particular with respect to uncertainty about $\mdp$. \paragraph{Contribution.} Typically, risk sensitivity in reinforcement learning has addressed risk due to the inherent environment stochasticity (aleatory) and that due to uncertainty (epistemic) with different mechanisms. We instead wish to consider both under a coherent utility maximising framework, where the convexity of the utility with respect to the return $\return$ determines whether our behaviour will be risk-seeking or risk-averse. By applying this utility function on the actual return or the expected return given the MDP we can easily trade off between aleatory and epistemic risk-sensitivity. \subsection{Related work} Defining risk sensitivity with respect to the return $\return$ can be done in a number of ways. In this paper, we focus on the expected utility formulation, whereby the utility is defined as a function of the return: concave functions lead to risk aversion and convex to risk seeking. In the context of reinforcement learning, this approach was first proposed by~\citet{mihatsch2002risk}, who derived efficient temporal-difference algorithms for exponential utility functions. However, the authors considered risk only with respect to the MDP stochasticity. Works on Robust MDPs have traditionally dealt with uncertainty due to epistemic risk. In~\citet{givan2000bounded} the authors extend the exact MDP setting by allowing bounded transition probabilities and rewards. They introduce optimal pessimistic and optimistic policy updates for this setting. \citet{mannor2012lightning} further extend this by allowing the parameter uncertainties to be coupled which allows for less conservative solutions. \citet{tamar2014scaling} use RL and approximate dynamic programming (ADP) to scale the Robust MDP framework to problems with larger state spaces using function approximators. Another way of dealing with risk is conditional value-at-risk (CVaR)~\cite{rockafellar2000optimization, sivara2017} measures. Compared to more traditional risk measures such as Mean-Variance trade-off~\cite{markowitz1952portfolio, tamar2012policy} or expected utility framework~\cite{friedman1948uac}, CVaR allows us to control for tail risk. CVaR has been used for risk-sensitive MDPs in \citet{chow2014algorithms,chow2015risk,chow2015riskconstrained,stanko2018distribuvcni}. A Bayesian setting is also considered by~\citet{depeweg2018decomposition}, who focus on a risk decomposition in aleatory and epistemic components. The authors model the underlying dynamics with a neural network. Under the risk-sensitive framework, they aim to trade-off expected performance with variation in performance. The risk-sensitive criterion they aim to maximise is $\mathbb{E}\big[\sum_t r_t\big] + \beta\sigma\big(\sum_t r_t\big)$ where $\beta$ controls for the level of risk-aversion. Thus, they are essentially considering risk only with respect to individual rewards. Our paper instead considers the risk with respect to the total return, which we believe is a more interesting setting for long-term planning problems under uncertainty. \section{Optimal policies for epistemic risk} \label{sec:epistemic_setting} Under the expected utility hypothesis, risk sensitivity can be modelled~\citep{friedman1948uac} through a concave or convex utility function $\utility : \Reals \to \Reals$ of the return $\return$. Then, for a given model $\mdp$, the optimal $\utility$-sensitive policy with respect to \emph{aleatory} risk is the solution to $\max_\pol \E_\mdp^\pol [\utility(\return)]$. In the case where we are uncertain about what is the true MDP, we can express it through belief $\bel$ over models $\mdp$. Then optimal policy is the solution to \begin{equation} \pol^A(\utility, \bel) \defn \argmax_\pol \int_\MDP \E_\mdp^\pol [\utility(\return)] \, d \bel(\mdp). \label{eq:aleatory-bayes-risk} \end{equation} However, this is only risk-sensitive with respect to the stochasticity of the underlying MDPs. We believe that \emph{epistemic} risk, i.e. the risk due to our uncertainty about the model is more pertinent for reinforcement learning. The optimal \emph{epistemic risk sensitive} policy maximises: \begin{equation} \pol^E(\utility, \bel) \defn \argmax_\pol \int_\MDP \utility\left(\E_\bel^\pol (\return)\right) \, d \bel(\mdp). \label{eq:epistemic-bayes-risk} \end{equation} When $\utility$ is the identity function, both solutions are risk-neutral. In this paper, we shall consider functions of the form $\utility(x) = \beta^{-1}e^{\beta x}$, so that $\beta > 0$ is risk-seeking and $\beta < 0$ risk-averse. We consider two algorithms for this problem. The first, based on an approximate dynamic programming algorithm for Bayesian reinforcement learning introduced in~\cite{dimitrakakis:mmbi:ewrl:2011}, is introduced in Section~\ref{sec:adp}. The second, based on the policy gradient framework~\cite{sutton2000policy}, allows us to extend the previous algorithm to larger MDPs and allows for learning of stochastic policies. The priors used in the experiments are detailed in Section~\ref{sec:experiment}. \subsection{Utility functions.} \label{sec:utility} Previous works~\cite{mihatsch2002risk,howard1972risk} on utility functions for risk-sensitive reinforcement learning used an \emph{exponential} utility function of the form $U(x) = \beta^{-1} e^{\beta x}$. The $\beta$ parameter could then be used to control the shape of the utility function and determine how risk-sensitive we want to be with respect to $x$. This is the utility function we will use in this paper.\footnote{Other choices are $U(x) = x^\beta$ or $U(x) = \log(x)$, however they both come with significant drawbacks, such as handling negative returns $R$.} \citet{mihatsch2002risk} consider not only exponential utility functions, but a special form of them, that is: \begin{equation} \pi^E(U) = \underset{\pol}{\arg\max} \frac{1}{\beta} \log{} \mathbb{E}\Big(\exp(\beta R)\Big) \end{equation} \citet{mihatsch2002risk,coraluppi1999risk,marcus1997risk} argue that this utility function has some interesting properties. In particular, maximising leads to maximising: \begin{equation} \mathbb{E}[R] + \frac{\beta}{2}Var[R] + \mathcal{O}(\beta^2) \end{equation} From this, we get that the behavior of our policy $\pol^E(U)$ as $\beta \rightarrow 0$ is the same as for the risk-neutral case. For $\beta < 0$ we get risk-averse behavior and for $\beta > 0$ risk-taking behavior. In our work, we are working in a Bayesian setting. Consequently, we introduce a belief $\bel$ over models and define the expected utility of a policy $\pi$ related to the model uncertainty as follows: \begin{equation} \label{eq:exp-utility} U^E_\beta(\xi, \pi) \defn \frac{1}{\beta}\log\int_{\mathcal{M}} \exp\big(\beta\mathbb{E}_\mdp^\pol[R]\big)d\xi(\mu). \end{equation} \subsection{Epistemic risk sensitive backward induction} \label{sec:adp} Algorithm~\ref{alg:evi} is an Approximate Dynamic Programming (ADP)~\cite{powell2007approximate} algorithm for optimising policies in our setting. While the algorithm is given for a belief over a finite set of MDPs, it can be easily extended to arbitrary $\bel$ through simple Monte-Carlo sampling, as in~\citet{dimitrakakis:mmbi:ewrl:2011}. The algorithm essentially maintains a separate $Q_\mdp$-value function for every MDP $\mdp$. At every step, it finds the best local policy $\pol$ with respect to the utility function $\utility$. Then the value function $V_\mdp$ of each MDP reflects the value of $\pol$ within that MDP. This algorithm will be used as a baseline for the experiments with risk aversion. We know that as the epistemic uncertainty vanishes; if there is only one underlying true model, then the optimal policy for the epistemic risk-sensitive algorithm will be the same as the optimal policy for the epistemic risk-neutral algorithm. It is important to point out that this is only true when our belief is concentrated around the true MDP. Behavior during learning of the MDP could be very different. For cases with multiple models, the epistemic uncertainty will always exist and there are no such guarantees. \begin{algorithm}[tb] \caption{Epistemic Risk Sensitive Backwards Induction} \label{alg:evi} \begin{algorithmic} \STATE {\bfseries Input:} $\mathcal{M}$ (set of MDPs), $\bel$ (current posterior) \REPEAT \FOR{$\mdp \in \mathcal{M}$ $s \in \mathcal{S}$, $a \in \mathcal{A}$} \STATE $Q_\mdp(s,a) = \mathcal{R}_\mdp(s,a) + \gamma \sum_{s'} \mathcal{T}_\mdp^{ss'} V_\mdp(s')$ \ENDFOR \FOR{$s \in \mathcal{S}$} \FOR{$a \in \mathcal{A}$} \STATE $\mathcal{Q}_\bel(s,a) = \sum_\mdp \bel(\mdp) \utility[(Q_\mdp(s,a)]$ \ENDFOR \STATE $\pol(s) = \argmax_a \mathcal{Q}_\bel(s,a)$. \FOR{$\mdp \in \mathcal{M}$} \STATE $V_\mdp(s) = {Q}_\mdp(s,\pol(s))$. \ENDFOR \ENDFOR \UNTIL{\itshape convergence} \STATE {\bfseries return $\pol$} \end{algorithmic} \end{algorithm} \subsection{Bayesian policy gradient} \label{sec:bpg} A common method for model-free reinforcement learning is policy gradient~\cite{sutton2000policy}. It is also very useful in model-based settings, and specifically for the Bayesian reinforcement learning problem, where sampling from the posterior allows us to construct efficient stochastic gradient algorithms. Bayesian policy gradient (BPG) methods have been explored for these contexts before,~\citet{ghavamzadeh:bpga} uses BPG to plan how to maximise information gain given our current belief $\xi_t$ for the risk-neutral setting. In our specific setting, we are interested in maximising (\ref{eq:epistemic-bayes-risk}), where we use utility function~(\ref{eq:exp-utility}) to model risk sensitivity. Our choice of policy parametrisation is a softmax policy with non-linear features. The probability of selecting action $a$ in state $s$, given current parameters $\theta$, is $\pi_\theta(a|s) = \frac{e^{\phi(s,a, \theta)}}{\sum_{a' \in \mathcal{A}}e^{\phi(s,a',\theta)}}$, where the features $\phi(s, a, \theta)$ are calculated by a feedforward neural network with one hidden layer. Full parameter details of the neural networks are given in Section~\ref{sec:experiment}. We choose to introduce a policy parametrisation over (\ref{eq:epistemic-bayes-risk}). This gives us (\ref{eq:epistemic-bayes-risk-theta}). \begin{equation} \label{eq:epistemic-bayes-risk-theta} \pi^E(U, \xi, \theta) = \int_{\mathcal{M}} U\Big(\mathbb{E}_{\pi_\theta}^\mu[R]\Big)d\xi(\mu) \end{equation} Combining our choice of utility function in (\ref{eq:exp-utility}) and (\ref{eq:epistemic-bayes-risk-theta}) gives us our new objective function (\ref{eq:epistemic-bayes-risk-theta-utility}). \begin{equation} \label{eq:epistemic-bayes-risk-theta-utility} \pi^E(U, \xi, \theta) = \frac{1}{\beta} \log{} \int_{\mathcal{M}} \exp\Big(\beta\mathbb{E}_{\pi_\theta}^\mu[R]\Big)d\xi(\mu) \end{equation} Our goal is now to find the set of parameters $\theta$ so as to maximise information gain. Taking the gradient of (\ref{eq:epistemic-bayes-risk-theta-utility}) gives (\ref{eq:pgbefore}) which leads to (\ref{eq:pg}) after a straightforward derivation. \begin{equation} \label{eq:pgbefore} \nabla_\theta \pi^E(U, \xi, \theta) =\nabla_\theta \frac{1}{\beta} \log{} \int_{\mathcal{M}} \exp\Big(\beta\mathbb{E}_{\pi_\theta}^\mu[R]\Big)d\xi(\mu) \end{equation} \begin{equation} \label{eq:pg} =\frac{\int_\mathcal{M}\exp\Big(\beta \mathbb{E}_{\pi_\theta}^\mu[R]\Big)\nabla_\theta\mathbb{E}_{\pi_\theta}^\mu[R]d\xi(\mu)}{\int_{\mathcal{M}} \exp\Big(\beta\mathbb{E}_{\pi_\theta}^\mu[R]\Big)d\xi(\mu)} \end{equation} The RHS of the numerator is the classical policy gradient~\cite{sutton2000policy}. We can replace the integrals in~(\ref{eq:pg}) with a sum by sampling models from our belief $\xi$. Note that this has to be done independently for the numerator and the denominator to avoid bias. To get each of the separate $\mathbb{E}_{\pol_\theta}^{\mu}[R]$ we make use of rollouts. Each expected return term is estimated independently with their own set of rollouts. We now have an estimate for the gradient and can move our policy parameters accordingly to act optimally given our belief $\xi_t$. The procedure of calculating the gradient in ({\ref{eq:pg}}) is given in Algorithm~\ref{alg:papg}. The algorithm builds upon the classic episodical \emph{REINFORCE} algorithm~\cite{williams1992simple}. Basing the algorithm on an episodical update makes sense in this case since it decreases the number of rollouts we have to do. One drawback is that it restricts updates episode by episode and so the information gained in the current episode cannot be used until after the episode ends. Monte-Carlo methods such as \emph{REINFORCE} also have a few other drawbacks such as high variance and low convergence, problems that could be addressed by extending the current framework to an actor-critic based one, as in~\citet{barto1983neuronlike,ghavamzadeh2007bayesian,ghavamzadeh2016bayesian}. The algorithm consists of two stages. One planning stage which is used to identify the best policy parameters $\theta_t$ given our current belief $\xi_t$. This is done through model-based simulation by sampling MDPs from our belief. After the rollouts have been collected the neural network is optimised and a new policy $\pi_{\theta_{t+1}}$ is attained. We then commit to this policy for one episode and move on to the next stage of the algorithm. The second stage of the algorithm uses the new policy to act in the real environment. Trajectories $\tau = (s_0, a_0, r_1, s_1, ..., s_{T-1}, a_{T-1}, r_T, s_T)$ are collected from this environment and used to update our belief over transitions and reward functions. \begin{algorithm}[tb] \caption{Epistemic Risk Sensitive Policy Gradient} \label{alg:papg} \begin{algorithmic} \STATE {\bfseries Input:} Policy parametrisation $\theta_t$, $\bel_t$ (current posterior). \REPEAT \STATE $\texttt{Simulate to get }\theta_{t+1}$ \FOR{$i=1$ {\bfseries to} $N$} \STATE $\mdp_{(1)}, \mdp_{(2)} \sim (\mathcal{M}_t, \mathcal{R}_t)$ \FOR{$j=1$ {\bfseries to} $M$} \STATE $\tau_{\mdp_{(1)}}^{(1)}, \tau_{\mdp_{(1)}}^{(2)} \sim \pol_\theta, \mdp_{(1)}$ \STATE $\tau_{\mdp_{(2)}}^{(3)} \sim \pol_\theta, \mdp_{(2)}$ \ENDFOR \ENDFOR \STATE $\theta_{t+1} \leftarrow \theta_t - \frac{\sum_{i=0}^N \exp\Big(\beta {\tau_{\mdp_i}}^{(1)}\Big){\tau_{\mdp_i}}^{(2)}\nabla_\theta\log{}\pi_\theta(a|s)}{\sum_{i=0}^N \exp\Big(\beta {\tau_{\mdp_i}}^{(3)}\Big)}$ \STATE $\texttt{Deploy }\pol_{\theta_{t+1}}$ \STATE $\tau \sim \mdp, \pol_{\theta_{t+1}}$ \STATE $\bel_{t+1} \leftarrow \bel_t, \tau$ \UNTIL{\itshape convergence} \end{algorithmic} \end{algorithm} \subsection{Bayesian Epistemic CVaR} \label{sec:risk-sensitive} Another common approach of handling risk-aversion is to optimize with respect to a CVaR objective, \cite{chow2014algorithms, chow2015risk, tamar2015optimizing, stanko2018distribuvcni}. In this paper, we investigate Bayesian epistemic CVaR, first studied by~\citet{chen2018leverage} in the context of investment strategies. In their case, they use it to do posterior inference of a SV-ALD model to efficiently estimate risk. We define Bayesian epistemic CVaR as follows, defining the set of MDPs where we get at least $z$ utility as the following; \begin{equation} \MDP_z^\pi \defn \Big\{ \mdp \, | \, \E_\mdp^\pol[R] \geq z \Big\}. \end{equation} The $\nu_\bel^\pol(\alpha)$ is value-at-risk in the Bayesian setting for a given quantile $\alpha$. \begin{equation} \nu^\pol_\bel(\alpha) = \inf \Big\{z \, | \, \bel(\MDP_z^\pol) \geq \alpha\Big\}. \end{equation} \begin{align} C^\pol_\bel(\alpha) &= \E^\pol_\bel\Big[ \E_\mdp^\pol[R] \mid \E_\mdp^\pol[R] \leq \nu^\pol_\bel(\alpha)\Big] \\ &= \int_{\MDP^\pol_{\nu^\pol_\bel(\alpha)}} \E_\mdp^\pol[R] \, d \bel(\mdp). \end{align} Concisely stated; we want to maximize our performance for the $\alpha$ least likely MDPs according to our belief $\bel$. The intuition behind this is that we want to be risk-averse with respect to what we are the most uncertain about. \section{Experiments} \label{sec:experiment} In this paper, we conduct two kinds of experiments. Firstly, a classical learning problem on a \emph{Gridworld}. This is discrete, so we can use Algorithm~\ref{alg:evi} to find a near-optimal deterministic policy. Similar problems have been studied before in the field of robust MDPs and there are already solutions for finite state and action-space problems. As this is a discrete state-action space, the belief maintained over the MDP transitions is in the form of a Dirichlet-product prior and Belief over rewards is in the form of a NormalGamma prior. Further experimental details about this problem can be found in Section~\ref{ex:gw} and Appendix~\ref{sec:agw}. Secondly, we consider a continuous state-space problem in Section~\ref{ex:opt}. We do not see a trivial extension of previous works in robust MDPs to the case with infinite state-space. Previous works such as~\citet{tamar2014scaling} scale earlier works on robust MDP to large state-space problems but not to continuous. The problem has been studied to a great extent in the field of risk-aversion, see~\citet{tamar2012policy, tamar2015optimizing, chow2014algorithms} and Appendix~\ref{sec:ao}. For this problem, we maintain function priors in the form of Gaussian Processes on the reward functions and transition kernels. \subsection{Gridworld experiment} \label{ex:gw} \begin{figure} \caption{Experiment detailing the results of the run of \emph{ADP} Algorithm~\ref{alg:evi} for varying choices of $\beta$. (a) The top plot of the grid is the regret over time with respect to the optimal deterministic risk-neutral policy. (b) The bottom plot shows the distribution of falls throughout over all experiments.} \includegraphics[width=\linewidth]{gridworld_experiment} \centering \label{fig:gw} \end{figure} Shown in Figure~\ref{fig:gw} are the results of Algorithm~\ref{alg:evi} ran for different values of $\beta$. We aimed to test both risk-aversion and risk-taking behavior through the choice of this parameter. The regret is averaged over $\approx 100$ independent experiment runs. We can see that the regret increases for more risk-taking policies in the top plot. In this environment the risk-neutral and the risk-averse behavior is almost identical, with only a minor difference in \emph{$\# Falls$}. The risk-taking policy is in one sense, over-exploring while the risk-averse policy in general, would be more inclined to do exploitation. Note that in this experiment the only epistemic uncertainty comes from that the agent does not know the true MDP $\mu$. This uncertainty will go down over time as more transitions are observed. \subsection{Option pricing experiment} \label{ex:opt} \begin{figure} \caption{Experiment detailing the results of the run of Epistemic Bayesian Policy gradient \emph{EBPG} Algorithm~\ref{alg:papg} for varying choices of $\beta$. For comparison we also include a risk-neutral \emph{PG}, a risk-neutral \emph{BPG} and \emph{CVaR BPG}. (a) The upper plot is a histogram over returns for all episodes observed. (b) The bottom plot is a histogram of the return over the last 10000 episodes, so the most current policy. } \includegraphics[width=\linewidth]{option_experiment} \centering \label{fig:opt} \end{figure} The result of runs in this environment is depicted in Figure~\ref{fig:opt}. The blue colored line will serve as a reference and has been verified to have an almost optimal risk-neutral policy. It also has the most observed data (millions of episodes) compared to the other algorithms (hundreds of thousands of episodes). We do see some notable difference in behavior between the policies and can identify that the algorithm with CVaR objective and the algorithm with $\beta=-0.001$ are overly cautious. On the other hand for $\beta=\{-0.01, -0.1\}$ and BPG we see behavior similar to that of regular PG. \section{Conclusions} We have introduced a framework that allows us to control for how risk-sensitive we want to be with respect to model uncertainty in the Bayesian RL setting. In Section~\ref{ex:gw} we detail the performance of Algorithm~\ref{alg:evi}, an ADP algorithm that has the ability to control for risk-sensitiveness in environments with discrete state and action-spaces. The results point towards risk-averse policies lead to less exploratory policies; that is, we would only expect to explore additionally if we are convinced there is much more to be gained by doing so, compared to a risk-neutral policy. Figure~\ref{fig:opt} shows an extension of this, using Policy gradient algorithms to more complicated environments with continuous state-space. A few hurdles noted is the speed of Algorithm~\ref{alg:papg}. In order to get a rich representation of the model uncertainty, a lot of MDPs should be sampled. However, sampling MDPs in this setup is quite expensive. Other belief models could be considered instead of GP if we were to scale this up to real problems. \paragraph{Future work.} We can see an adaptive agent that could change its risk-sensitive parameter $\beta$ with time. For problems where we know uncertainties will resolve later into the future, this could be one approach. There could be an avenue to explore using utility functions to induce more exploratory behavior in complicated environments. Current methods use concepts such as curiosity~\cite{houthooft2016vime,pathak2017curiosity} for reward shaping or entropy regularization~\cite{williams1991function, mnih2016asynchronous,o2016combining} to enforce additional exploration. However, under the expected utility framework we could perhaps get this for free by changing the utility function. Decreasing variance and speeding up Algorithm~\ref{alg:papg} is of utmost importance for this framework to be used for more complex problems. As we touched upon in Section~\ref{sec:bpg} a straight-forward improvement would be to move towards the Bayesian actor-critic framework introduced in~\citet{ghavamzadeh2007bayesian}. \section*{Acknowledgement} This work was partially supported by the Wallenberg AI, Autonomous Systems and Software Program (WASP) funded by the Knut and Alice Wallenberg Foundation.\\ The simulations were performed on resources provided by the Swedish National Infrastructure for Computing (SNIC) at Chalmers Centre for Computational Science and Engineering (C3SE).
{'timestamp': '2019-06-17T02:16:43', 'yymm': '1906', 'arxiv_id': '1906.06273', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06273'}
arxiv
\subsection*{Acknowledgements} We thank Karin Niemantsverdriet for her much appreciated counsel and support with the visual elements of this paper. This material is based upon work supported in whole or in part with funding from the Laboratory for Analytic Sciences (LAS). Any opinions, findings, conclusions, or recommendations expressed in this material are those of the author(s) and do not necessarily reflect the views of the LAS and/or any agency or entity of the United States Government. The third author gratefully acknowledges funding from the Natural Sciences and Engineering Research Council of Canada (NSERC). } \eat{ \noindent {\bf Acknowledgements: } We gratefully acknowledge Karin Niemantsverdriet's assistance with the design and creation of figures; and the Laboratory for Analytic Sciences (LAS) and the Natural Sciences end Engineering Research Council of Canada (NSERC) for funding this work. Any opinions, findings, conclusions, or recommendations expressed in this material are those of the author(s) and do not necessarily reflect the views of NSERC, the LAS and/or any agency or entity of the United States Government. } \bibliographystyle{named} \begin{small} {\fs{9} \section{Computation} \label{comp} In this section, we describe how to compute a solution to the EmP problem\eat{, as well as how to integrate the two paradigms}. In our computation and evaluation, we assume that \textsc{Obs} is omniscient\eat{(and thus also empathizes with \textsc{Act})}. In this case, a solution to an MEP problem\eat{, an action tree,} `collapses' to a single path, as \textsc{Obs} has knowledge of the results of the sensing actions. We call the sequence of actions that defines the path a plan and say that its cost is the number of actions in the sequence. \eat{\subsubsection*{EmPR as Epistemic Planning} We build on the `Plan Recognition as Planning' (PRAP) paradigm \cite{ramirez2010probabilistic} to find a solution, $\pi$, to the EmPR problem. In PRAP, rather than requiring plan libraries to be specified in advance, we appeal to the flexibility of planning techniques to generate plans. This is especially important when \textsc{Act} is following invalid plans due to, e.g., misconceptions it may have. We transform the EmPR problem to an MEP problem and constrain the plan generation such that only plans that satisfy $O$ are computed. Given $R$ $=$ $\langle Q, I, \mathcal{G}, O \rangle$, where $Q = \langle \mathcal{P}, \mathcal{A}, Ag \rangle$, we define a correspondence between $\langle \mathcal{P}, \mathcal{A}, I, O \rangle$ and $\langle \mathcal{P}', \mathcal{A}', I', O' \rangle$, such that $\mathcal{P}' = \mathcal{P} \cup \{p_a \mid a \in O\} \cup \{p_0\}$, $\mathcal{A}' = \mathcal{A}$, and $O' = \emptyset$. For every action $a \in \mathcal{A}'$ that appears in the observation sequence $O$, we add $(\top, p_a)$ to the conditional effects of $a$ and add $p_b$ to the preconditions. $p_b$ corresponds to the action $b$ that immediately precedes $a$ in $O$. $p_0$ is added to the preconditions of the first observation in $O$. $I' = I\land p_0$. In this way, all plans that solve the transformed problem respect the order of the observation sequence $O$.\eat{ The order is enforced by the precondition $p_b$ which only allows an action $a$, which appears in $O$, to be executed after all the observations in $O$ which precede it have been executed.} $(\top, p_{last})$ is added to the conditional effects of the last observation in $O$. In the transformed problem, we modify the goal such that for some $G \in \mathcal{G}$, $G'=G \land p_{last}$. Thus, the transformed MEP domain and problem corresponding to $R$ and $G$ are $Q' = \langle \mathcal{P}', \mathcal{A}', Ag \rangle$ and $\langle Q', I', G' \rangle$, respectively. For every $G \in \mathcal{G}$, $P(G|O)$ is obtained by computing $\Delta$, the cost difference between two plans - one that satisfies $O$ and one that does not. $\Delta$ is computed by running an off-the-shelf epistemic planner twice on the transformed MEP problem, once with $G' = G \land \lnot p_{last}$ and once with $G' = G \land p_{last}$. Assuming a uniform prior, $P(G)$, Bayes' Rule is used to compute $P(G|O) = \alpha P(O|G) P(G)$ where $\alpha$ is a normalization constant. Assuming a Boltzmann distribution, as in \cite{ramirez2010probabilistic}, $P(O|G) \approx \frac{e^{-\beta\Delta}}{1+ e^{-\beta\Delta}}$ where $\beta$ is a positive constant. We then choose $\pi$, the solution to $R$, from the set of optimal plans that achieve the goals $G \in \mathcal{G}$ which are assigned the highest posterior probability. } \subsubsection*{Computing a Solution to the EmP Problem} A solution to the EmP problem, $Z$ $=$ $\langle Q, I, {G}_{\textsc{Act}}\rangle$, is a plan $\pi$ that belongs to the set of optimal plans which achieve ${G}_{\textsc{Act}}$, $\Pi^{*}$.\eat{To realize this solution computationally, we turn, once again, to epistemic planning.} While ${G}_{\textsc{Act}}$ can be obtained in different ways (e.g., \textsc{Act} could explicitly tell \textsc{Obs} their goal or communicate it to a fellow agent), inferring ${G}_{\textsc{Act}}$ via plan recognition (i.e., the problem of inferring an actor's plan and goal given observations about its behavior) is of most interest to us. At an overview, by solving the recognition problem we can set $G_{\textsc{Act}}$ to be the goal most likely being pursued by \textsc{Act}, given a sequence of observations. While we do not focus on the recognition component in this work, we have formalized the notion of empathetic plan recognition in an unpublished manuscript and proposed an integrative approach to empathetic planning and plan recognition. Further investigation is left to future work. To obtain a solution to the EmP problem, we solve the MEP problem $\langle Q, I, {G}_{\textsc{Act}}\rangle$ by using an optimal off-the-shelf epistemic planner.\eat{There are currently no off-the-shelf epistemic planners that readily address preferences, and so in our experiments $\preceq$ is defined wrt the cost of a plan, where $\pi_1$ is preferred to $\pi_2$ \textit{iff} $\pi_1$ has a lower cost than $\pi_2$.}\eat{ As described in the next section, we use an off-the-shelf optimal epistemic planner to solve $\langle Q, I, {G}_{\textsc{Act}}\rangle$.} \textbf{Complexity\quad}\commentms{I wonder if we can do without this paragraph. 2 of the reviewers mentioned complexity}Epistemic planning has been shown to be computationally expensive (e.g., \cite{aucher2013undecidability}).\eat{ There are, however, a number of decidable and expressive fragments of epistemic planning (e.g., \cite{charrier2016impact}).} E.g., the encoding process in RP-MEP, the epistemic planner proposed by \cite{MuiseBFMMPS15} and used in this work, generates an exponential number of fluents when transforming the problem into a classical planning problem. \section{Discussion and Summary} In this work, we have introduced the notion of EmP which we formally specified by appealing to a rich epistemic logic framework and building upon epistemic planning paradigms. We proposed a computational realization of EmP as epistemic planning that enables the use of existing epistemic planners. We conducted a study which demonstrated the potential benefits of assistive empathetic agents in a diversity of scenarios as well as participants' favorable perceptions of the empathetic agent's assistive capabilities. It has been claimed recently that richer representational frameworks are needed to bridge some of the gaps in current virtual assistants - AI systems that frequently interact with human users \cite{cohen2018back}. The scenarios we have presented illustrate precisely this need in the context of reasoning over the beliefs and goals of agents and our approach is well-suited to address such settings. \eat{Further, while we focus on assistive empathetic agents, empathy may be wielded by agents who are not benevolent and this `darker side' of empathy invites a deeper discussion of EmP and EmPR.} There is a diverse body of research related to the ideas presented here. Empathy has been incorporated into intelligent agent systems in various settings (e.g., \cite{aylett2005fearnot}) but has not appealed to generative epistemic planning techniques. Work on BDI has explored notions of epistemic reasoning \cite{sindlar2008mental} and affect \cite{steunebrink2007logic}, but has typically not appealed to the flexibility of AI planning to generate plans.\eat{\citeauthor{freedman2017integration} [\citeyear{freedman2017integration}] have integrated planning with PR but haven't addressed agent beliefs or affect. Finally, \cite{talamadupula2014coordination} have combined belief modelling with PR but did not address affect or epistemic goals.} There exist many avenues for future work such as the integration of affect into our framework. Future work could also appeal to related work which attempts to reconcile the human's model \cite{chakraborti2017plan} when providing the human with explanations (e.g., informing them of the bus' status). Lastly, partially observable settings will be addressed, where the empathtizer may have uncertainty regarding the mental state of the empathizee, as well as the environment in general. \subsubsection*{Acknowledgments} The authors gratefully acknowledge funding from NSERC and thank their colleague Toryn Q. Klassen for helpful discussions. \section{Empathetic Plan Recognition} In this section, we define the EmPR problem and its solution. We make use of work that has defined the \textit{Epistemic Plan Recognition} problem, which appeals to a notion of epistemics to (1) recognize epistemic goals (where the agent is trying to change its own (or another agent's) state of belief or knowledge, compared to an ontic goal where it is trying to change the state of the world); and (2) model the observer, and its knowledge of the actor, as first class elements of the PR process \cite{anonEPR}. We view the epistemic plan recognition paradigm in the context of empathy and formalize the notion of EmPR. In Section \ref{comp}, we describe how to integrate EmPR with EmP. Note that we assume there is only one actor. \eat{Our disucssion of EmPR in this paper is fairly brief.} We define the EmPR problem as follows: \begin{definition}[EmPR] An empathetic plan recognition problem is a tuple $R$ $=$ $\langle Q, I, \mathcal{G}, O \rangle$, where $Q$ $= \langle \mathcal{P}, \mathcal{A}, Ag \rangle$ is an MEP domain with $\textsc{Obs}$ and $\textsc{Act}$ among the agents in $Ag$. $I \in \mathcal{L}$ is the initial KB, $\mathcal{G}$ is a set of possible goals $G \in \mathcal{L}$, and $O = o_1, ..., o_m$, is a sequence of observations. Each observation $o_j$ is a pair $(\alpha_i, \phi_i)$ comprising zero or one observed actions, $\alpha_i \in \mathcal{A}$, together with $\phi_i$, a conjunction of literals drawn from $\mathcal{P}$, or ~$\top$. \label{EPR} \end{definition} Given an EmPR problem, $R$, a sequence of actions $\pi$$=$$a_1,\ldots,a_n$ {\bf satisfies} observations $O =$ $(\alpha_1, \phi_1),$$\ldots,$$(\alpha_m, \phi_m)$ if there is a monotonic function $f$ mapping the observation indices $j$ $=$ $1,...,m$ into action indices $i$ $=$ $1,...,n$ such that $a_{f(j)}$ $=$ $\alpha_j$, and $prog(I,[a_1,\ldots,a_{f(j)}]) \models\phi_j$ for $j=1,\ldots,m$. Note that since both \textsc{Obs} and \textsc{Act} are explicitly modelled in $Ag$, $I$ could encode beliefs that \text{Act} holds about \text{Obs} which can facilitate reasoning in a host of settings. E.g., if \text{Obs} believes that \text{Act} believes that \text{Obs} has already eaten dinner, then \text{Obs} can infer that \text{Act} will not wait for her to eat. \begin{definition} Given an EmPR problem, $R$ $=$ $\langle Q, I, \mathcal{G}, O \rangle$, the \textbf{solution} is a plan, $\pi$, such that $\pi$ satisfies the sequence of observations, $O$, and $prog(I,\pi) \models G$ for some goal $G \in \mathcal{G}$. \label{EPR_solution} \end{definition} In the following sections, we use a simplified EmPR problem, where observations $o_j$ in the sequence $O$ are restricted to actions, $a \in \mathcal{A}$. $\textsc{Obs}$ is said to be \textit{maximally task-empathetic} wrt to \textsc{Act} and $R$ $=$ $\langle Q, I, \mathcal{G}, O \rangle$ and $prog(I^{\text{\textsc{ACT}}},\pi)$ progress (or are both undefined) through the same intermediate formulae for any $\pi$ that satisfies $O$ and achieves some $G \in \mathcal{G}$. This means that \textsc{Obs} needs to be empathetic `enough' to be able to generate, when taking \textsc{Act}'s perspective, all plans which \textsc{Act} can generate and that satisfy $O$ and achieve some $G \in \mathcal{G}$. Lastly, given an EmPR problem $R$ $=$ $\langle Q, I, \mathcal{G}, O \rangle$, \textsc{Obs} is maximally task-empathetic wrt to \textsc{Act} and $R$ if \textsc{Obs} empathizes with \textsc{Act}. \section{Empathetic Planning} \label{emp_plan} In this section, we define the EmP problem and its solution. We will make use of the notation \textsc{Obs} (observer) for the empathizer and \textsc{Act} (actor) for the empathizee throughout the paper; both are assumed to be in the set of agents $Ag$ in all definitions. To be helpful, an assistive empathetic agent should be able to reason about the \textit{preferences} of the empathizee. In general, agent preferences can be specified in various ways, including a reward function over states, as is done in a Markov Decision Process (MDP), or by encoding preferences as part of a planning problem (e.g., \cite{jorge2008planning}). Preferences (or rewards) can also be augmented with an emotional component which can encode an aversion to negative emotions, while optimizing for positive ones \cite{moerland2018emotion}. To simplify the exposition, we focus on plan costs as a proxy for agent preferences. We assume in this work that we have an accurate approximation of \textsc{Act}'s preferences over plans (in this work, the lower the cost, the better the plan), and do not focus on the problem of acquiring a faithful approximation of an agent's preferences. \begin{definition}[EmP] An empathetic planning problem is a tuple $Z$ $=$ $\langle Q, I, {G}_{\textsc{Act}} \rangle$, where $Q$ $=$ $\langle \mathcal{P}, \mathcal{A}, Ag \rangle$ is an MEP domain, $\mathcal{P}$, $\mathcal{A}$, and $Ag$ are sets of atoms, actions, and agents, respectively, $I \in \mathcal{L}$ is the initial KB, and ${G}_{\textsc{Act}} \in \mathcal{L}$ is \textsc{Act}'s estimated goal. \label{empathetic_planning} \end{definition} To illustrate, we partially model the example from Section \ref{intro} as an EmP problem (with Alice as \textsc{Act}). \begin{itemize} \item $I = $ $B_{\textsc{Obs}}$ \textit{at(\textsc{Act}, home)} \\$\land$ $B_{\textsc{Obs}}$ \textit{travelsBetween(alternativeBus, home, work)} \\ $\land$ $B_{\textsc{Obs}}$ \textit{crowded(alternativeBus)} \\ $\land$ $B_{\textsc{Obs}}$ $B_{\textsc{Act}} \lnot$ \textit{crowded(alternativeBus)} $\land$ ... \item ${G}_{\textsc{Act}} =$ \textit{at(\textsc{Act}, work)} \end{itemize} \begin{definition} Given an EmP problem, $Z$ $=$ $\langle Q, I, {G}_{\textsc{Act}}\rangle$, $\pi$ is an \textbf{assistive solution} to $Z$ \textit{iff} $\pi$ solves $\langle Q, I, {G}_{\textsc{Act}} \rangle$ and $\pi \in \Pi^{*}$ where $\Pi^{*}$ is the set of optimal solutions for $\langle Q, I, {G}_{\textsc{Act}}\rangle$. % % \label{empathetic_planning_solution} \end{definition} The solution to the EmP problem may vary if \textsc{Obs} is not trying to help \textsc{Act} achieve her goal (e.g., adversarial interaction as in \cite{freedman2017integration}). Throughout the paper, we focus on finding assistive solutions. We now formally define a pragmatic notion of empathy, defined wrt the EmP problem. To this end, we first discuss the notion of \textit{projection}, where an agent can reason from another agent's perspective. Let $\langle \langle \mathcal{P}, \mathcal{A}, Ag \rangle, I \rangle$ be \textsc{Obs}'s MEP domain and initial KB. $\mathcal{A}$ and $I$ encode \textsc{Obs}'s beliefs about the world, including, importantly, its beliefs about \textsc{Act}'s beliefs about the world. To enable \textsc{Obs} to reason from \textsc{Act}'s perspective, we wish to project $\mathcal{A}$ and $I$ wrt to $\textsc{Act}$. We define the \textbf{projection} of a formula $\phi$ with respect to an agent $i$, $proj(\phi,i)$. Given $\phi,\psi \in \mathcal{L}$, and assuming $\phi$ and $\psi$ are in NNF form, $proj(\phi,i)$ $=$ $\psi$ when $\phi = B_{i}\psi$ and is undefined otherwise. Both \cite{MuiseBFMMPS15} and \cite{engesser2017cooperative} similarly define projection operators, with \citeauthor{MuiseBFMMPS15}'s syntactic approach being similar to ours, while \citeauthor{engesser2017cooperative} define a semantic equivalent. We project $\mathcal{A}$ and the closure of $I$ (defined as $\{\psi \in \mathcal{L} \mid I \vDash \psi\}$) wrt \textsc{Act}. Note that the closure will be infinite but for any practical computation we will limit generation of closure to the relevant subset. We project every formula in the closure of $I$ and for every $a \in \mathcal{A}$ we project every precondition, and for every conditional effect of $a$ we project the condition and effect (we project the positive and negative results for sensing actions). We refer to the result of the projection operation wrt $\mathcal{A}$ and $I$ as $\mathcal{A}^{proj}$ and $I^{proj}$, respectively. Let $Z$ $=$ $\langle Q, I, {G}_{\textsc{Act}}\rangle$ be an EmP problem. Let $\Pi_{proj}^{*}$ and $\Pi_{\textsc{Act}}^{*}$ be the sets of optimal solutions among $\Pi_{proj}$ and $\Pi_{\textsc{Act}}$, respectively, where $\Pi_{proj}$ and $\Pi_{\textsc{Act}}$ are the sets of all solutions for $\langle \langle \mathcal{P}, \mathcal{A}^{proj}, Ag \rangle, I^{proj}, {G}_{\textsc{Act}}\rangle$ and $\langle \langle \mathcal{P}, \mathcal{A}^{\textsc{Act}}, Ag \rangle, I^{\textsc{Act}}, {G}_{\textsc{Act}}\rangle$, respectively. $\langle \mathcal{P}, \mathcal{A}^{\textsc{Act}}, Ag \rangle$ and $I^{\textsc{Act}}$ are \textsc{Act}'s true MEP domain and initial KB, which are typically not accessible to \textsc{Obs}.\eat{ We use $Q^{proj}$ as shorthand for $\langle \mathcal{P}, \mathcal{A}^{proj}, Ag \rangle$.} We say that $\textsc{Obs}$ is \textbf{\textit{selectively task-empathetic}} wrt to \textsc{Act} and $Z$ \textit{iff} $\Pi_{proj}^{*}$ $=$ $\Pi_{\textsc{Act}}^{*}$. That is, \textsc{Obs} needs to be empathetic `enough' in order to generate, when projecting to reason as \textsc{Act}, the optimal solutions that achieve ${G}_{\textsc{Act}}$ and which \textsc{Act} can generate on her own (using only her beliefs and capabilities). Importantly, if \textsc{Obs} is selectively task-empathetic wrt $Z$, she will generate a plan that is at least as `good' as the best solution \textsc{Act} can generate by herself, using her own beliefs and capabilities. \commentms{Possibly say: We prove this result in the appendix.} \eat{Since we are building assistive empathetic agents, $\pi$ should be \textit{executable} by \textsc{Act} (perhaps jointly with \textsc{Obs}).} \textsc{Obs}' solution could be better than \textsc{Act}'s solution if \textsc{Obs} has, for instance, additional knowledge or capabilities that \textsc{Act} lacks. In this case, a solution to the EmP problem, $\pi$, may solve $\langle \langle \mathcal{P}, \mathcal{A}, Ag \rangle, I, {G}_{\textsc{Act}}\rangle$ but not $\langle \langle \mathcal{P}, \mathcal{A}^{proj}, Ag \rangle, I^{proj}, {G}_{\textsc{Act}}\rangle$. Returning to our example, recall that \textsc{Act} avoids crowded buses and so will not board the crowded bus that goes from her home to work. Thus, the best plan \textsc{Act} can come up with is walking from home to work (assuming there is no alternative mode of transportation) since she believes the alternative bus is crowded. However, since \textsc{Obs} knows of an alternative bus that is relatively empty\eat{(assuming \textsc{Obs} is correct in its beliefs)}, a better plan would include \textsc{Act} taking the alternative bus. However, to make this plan executable in \textsc{Act}'s model, \textsc{Obs} must inform \textsc{Act} that the bus is empty (e.g., \textit{inform(\textsc{Obs}, \textsc{Act}, busInfo)}). In this case, \textsc{Act}'s goal of getting to work, while ontic, requires epistemic actions such as informing \textsc{Act} of the bus' status and the underlying MEP framework can facilitate reasoning about the required epistemic action(s) to achieve the goal. To contrast, consider Sympathetic \textsc{Obs}, who assumes that \textsc{Act} shares its model of the world. Thus, the optimal plan that solves $\langle Q, I, {G}_{\textsc{Act}} \rangle$ consists of \textsc{Act} taking the crowded bus, which is a plan that is not executable in her true model, due to her panic disorder.\eat{Alternatively, Sympathetic \textsc{Obs} could plan for \textsc{Act} to take the alternative bus without informing her that it is empty today, which might confuse \textsc{Act} and is hence a bad plan.} \eat{\textbf{It basically becomes an epistemic planning problem where the root agent is the empathizer - the goal is to get Alice to work - a plan could include Alice taking the crowded bus but it is not executable! There's another plan that includes an action by the empathizer, an explanatory action, followed by Alice's execution which is now possible} Define H($\pi$) relative to some cost which could be any combination of metrics or even a prediction by a learning model. \textbf{the solution maximizes some reward function that maps plan to number. could also be preferences over plans - ARE PREFERENCES also over plans that the agent cannot generate?? can I generalize preference relation so I know that taking alternative bus is good because it has high reward because of shorter time and no negative emotions triggered} \\ \textbf{Theorem: If we're adequately empathetic and assistive, then we will come up with plans that are greater or equal to reward of empathizee's plan - which is well-being} \\ \textbf{the agent's reward, which we need to learn/infer through empathy - sometimes we just know that a state will have a low reward because of consequences -, is determined based on emotions}\\ \textbf{we simplify here and talk about prefernces over plans (as determined by implicit reward), but in general we can talk about rewards of states - Most languages provide a means of referring to properties of a plan—generally that a property holds (or does not hold) in some or all intermediate states traversed during the execution of the plan, or in the final state of the plan. \cite{jorge2008planning} perhaps needs to be mentioned in the context of EPR}\\ \textbf{we focus here on solutions that are plans that need to be generated by the empathizee. However, we can also address setting where the empathizer forms a joint multi-agent plan. SINCE WE REPRESENT in MEP framework, we already have a multi-agent cooperative centraized setting!}\\ \textbf{We don't focus on HOW to generate explanations in order to make plan executable for agent, but this is an extremely important and this and this work is working on it}\\ \textbf{agent is trying to achieve some goal and thinks that it achieved it (because of false beliefs or different view of operators) - I can then achieve it for them or tell them}} \eat{ maximally helpful plan - H($\pi$) such that there does not exist a plan with higher H. It's a joint multi-agent plan? The solution to the human-aware planning problem is a joint plan ? by maximally beneficial we mean greatest distance (defined somehow) between the plan that the human would execute under their model and plan that empathizer can propose. We prove that we do empathetic planning wrt def of empathy since to find smallest distance we need to empathize with empathee wrt to their beliefs and knowledge relevant to task. We prove that to estimate the empathee's optimal plan (under their model) we need to know the beliefs and knowledge of ZEE which are relevant to the task, i.e., achieving ${G}_{\textsc{Act}}$ (so plan under approximated model should be the same as under true model $\pi^{G}_{M_{zee}} = \pi^{G}_{M_{zee}^{zer}}$) } \section{Empathy} In this section, we discuss the notion of empathy, contrast it with sympathy, and discuss possible characteristics of \textit{assistive empathetic agents}. As mentioned in Section \ref{intro}, inspired by the rich history of empathy and its philosophical foundations, we define empathy as \textit{the ability to understand and share the thoughts and feelings of another}. When taken to the extreme, where an empathizer knows every thought and feeling of an empathizee, the above definition embodies an idealized notion of empathy which necessitates \textit{omniscience}. We later discuss more pragmatic notions of empathy, which only require an empathizer to be empathetic `enough' and are defined wrt a specific task. To contrast, consider the Golden Rule, which asks us to treat others as \textit{we} would like to be treated. The rule assumes similarity, implying that others would like to be treated the same way we would and, therefore, does not allow for the existence of multiple perspectives, thus leading to \textit{sympathetic} behavior \cite{bennett1979overcoming}. Empathy, on the other hand, allows an \textit{empathetic agent} to experience the world from the perspective of the empathizee. In Section \ref{eval}, we conduct a study and compare an empathetic agent and a sympathetic agent. \eat{ This is because the belief consequences for their KBs will be equivalent.} \eat{Interestingly, we say that \textsc{Act} is \textit{self-understanding} $\iff$ \textsc{Act} empathizes with \textsc{Act} wrt to $I^{\textsc{Act}}$ and $I_{true}^{\textsc{Act}}$ (\textsc{Act}'s so-called ground truth KB, that may not be accessible to \textsc{Act}).} \subsubsection*{Affect} As mentioned, cognitive empathy includes both cognitive and affective components. If Emily empathizes with Alice, she should be able to reason about Alice's affective state. There is an extremely rich body of work on theories of affect (e.g., \cite{lazarus1966psychological}) and on the incorporation of these theories into computational models of affect (e.g., \cite{gratch2000emile}) Further, previous work has formalized logics of emotion for intelligent agents. E.g., \citeauthor{steunebrink2007logic} [\citeyear{steunebrink2007logic}] defined a formal logic within a BDI framework while \citeauthor{lorini2011logic} [\citeyear{lorini2011logic}] use a fragment of \textsc{STIT} logic to formalize counterfactual emotions such as regret and disappointment. Both of these logics appeal to a notion of epistemics to formalize complex emotions which are predicated on the beliefs of agents. Previous work has also quantified emotional intensity using fuzzy logic \cite{el2000flame}. Thus, there exists a multitude of ways in which to integrate affect into our framework, and as part of future work we will experiment with various extensions of our approach. \subsubsection*{Assistive Empathetic Agents} Before formalizing the notion of EmP, we discuss some of the properties\eat{assumptions/postulates//desiderata} we believe should characterize an assistive empathetic agent. More accurately, these are agents who wish to empathize with another, as empathy is often thought of as an ongoing process (or mountain climb \cite{ickes1997empathic}). \textbf{i. Need for Uncertainty\quad}\eat{The computational approaches described in Section \ref{comp} assume that \textsc{Obs} empathizes with \textsc{Act}. However, when this is not the case, the quality of inferences may suffer. }\eat{ \citeauthor{hadfield2017off} [\citeyear{hadfield2017off}] propose a scenario where a robot seeks to maximize and align with human values, but is also uncertain about them. Thus, the robot has an incentive to keep its off-switch enabled as it reasons that it must be doing something `wrong' if it is being turned off. Similarly, } We posit that an agent who wishes to empathize with another should be uncertain about the empathizee's values (e.g., \cite{hadfield2017off}) and, importantly, about her true beliefs about the world. Since the quality of plans generated by an assistive empathetic agent is predicated on the veracity of the empathetic agent's model of the empathizee, the empathetic agent should unceasingly strive to align itself better with her. \textbf{ii. Benevolence\quad} An assistive empathetic agent should take it upon itself to benefit the empathizee in a way that is aligned with the latter's values. \textbf{iii. $\lnot\text{Machiavellianism}$\quad} As mentioned, empathy can facilitate malicious intent. Thus, an assistive empathetic agent should not be Machiavellian, i.e., use deception, manipulation, and exploitation to benefit its interests. Interestingly, empathy and Machiavellianism have been found to be negatively correlated \cite{barnett1985role} - i.e., the will to manipulate is present in Machiavellians, but the means by which to do so are often not. Relatedly, a study conducted by \citeauthor{botsLie2019} [\citeyear{botsLie2019}] showed that human participants were, in general, positive towards an AI agent lying, if it was done for the `greater good'. Such questions should be explored further. E.g., when interacting with humans who wish themselves (or others) harm. \section{Evaluation}\label{eval} In our preliminary evaluation, we set out to (1) expose the diversity of tasks that can be captured by EmP (2) demonstrate that existing epistemic planners can straightforwardly be used to solve EmP problems and (3) to evaluate the benefits of our approach as assessed by humans. To this end, we constructed and encoded a diversity of domains, ran them using an off-the-shelf epistemic planner and conducted a study with human participants. For all of our experiments, we used the latest version of the epistemic planner RP-MEP \cite{MuiseBFMMPS15} with the Fast Downward planner \cite{helmert2006fast} with an admissible heuristic. Note that various epistemic planners impose various restrictions on domain modeling and plan generation, and we will experiment with different planners in the future.\eat{ We first describe some of the scenarios .} The various scenarios used in our simulations and study represent a diversity of every-day situations which illustrate the potential benefits of our approach. Further, the scenarios involve Alice (as \textsc{Act}) and her virtual assistant (as \textsc{Obs}), including suggestions (automatically generated solutions to an EmP problem) given to Alice by \textsc{Obs}. We then present the results of the study. We encode all scenarios as EmP problems, including the beliefs of \textsc{Obs} and \textsc{Act} and \textsc{Act}'s goal, $G_{\textsc{Act}}$ (see example in Section \ref{emp_plan}). We run RP-MEP once to compute a solution to an EmP problem. \commentms{Refer to appendix for EmPR results?}\\ \commentms{Refer to appendix for SurveyMonkey questionnaire?} \textbf{Experimental Setup\quad} The study aims to evaluate both perceptions of the agent's empathetic abilities and perceptions of the agent's assistive capabilities, as assessed by humans. To test this, participants were presented with 12 planner-generated textual scenarios (some of which are presented below) of either empathetic or sympathetic agents and were asked to rate the following two claims pertaining to each scenario on a 5 point scale ranging from strongly disagree to strongly agree: (1) \textit{``The virtual assistant was able to successfully take Alice's perspective"} (reflecting our measure of participants' perceptions of the agent's empathetic abilities); and (2) \textit{``If I were Alice, I would find this virtual assistant helpful"} (reflecting our measure of participants' perceptions of the agent's assistive capabilities). Scenarios with empathetic agents and scenarios with sympathetic agents were identical, except for the EmP solution generated by the agent. The sympathetic agent assumes that Alice shares its model of the world when computing a solution to the EmP problem. We had a total of 40 individuals (28 female) participate, ranging from 18 to 65 years old. Participants were recruited and completed the questionnaire via an online platform, and had no prior knowledge about the study. \textbf{Scenario 1\quad} Alice is on a bus headed uptown but believes the bus is headed downtown. \textsc{Obs} suggests that Alice get off the bus and get on the correct one. As claimed in Section \ref{intro}, empathetic agents are well-suited for distinguishing between the underlying intent of the behavior and the actual performed behavior. In this scenario, \textsc{Obs} can infer that Alice's current plan (riding the wrong bus) will not achieve her goal of getting downtown, the underlying intent of her behavior\eat{ (her goal could have been inferred from, for instance, a text message she sent to a friend she is supposed to meet downtown)}. \textbf{Scenario 2\quad} Alice is visiting her 91-year-old grandmother, Rose. Rose cannot hear very well but feels shame when asking people to speak up. \textsc{Obs} detects that Alice is speaking softly and sends her a discreet message suggesting she speak louder. Alice's goal is for her grandmother to hear her. This goal could be achieved by Rose asking Alice to speak louder. However, this plan will have a higher cost (due to Rose's aversion to asking people to speak louder) than the plan involving \textsc{Obs} sending a discreet message to Alice. \textbf{Scenario 3\quad} This scenario models the example from Section \ref{intro}, where Alice is trying to get to work and avoids crowded buses. \textsc{Obs} knows about a relatively empty bus, which would save her time, and suggests that Alice take it to work (in the sympathetic case, \textsc{Obs} suggests the crowded bus). \eat{ \textbf{Scenario 4\quad} Inspired by \cite{evans2016learning}, Alice is headed to lunch at a new salad bar. The shortest route there passes next to a doughnut shop while the longer route avoids temptation. Alice prefers not to be tempted, especially when hungry.She asks \textsc{Obs} for directions and is recommended to take the longer route (in the sympathetic case, the shortest route is proposed).} \eat{\textbf{Scenario 4\quad} Alice is seen moving between rooms, turning drawers upside down, and moving furniture. Alice is usually on her way to work at this time. \textsc{Obs} informs Alice that her car keys are in her coat pocket, by the door.} \eat{\textbf{Scenario 5\quad} In this scenario, Bob, a 92-year-old, texts his friend that he will meet him soon at the gallery. \textsc{Obs} knows that Bob hasn't checked the forecast and so is not aware of the extremely icy conditions of the sidewalks. \textsc{Obs} suggests that Bob take a taxi to the gallery and offers to book it for him. }\eat{\textbf{Scenario 4\quad} Alice is waiting to pick up Eve from the bus station, but Eve is already 20 minutes late and isn't responding to messages. \textsc{Obs} informs Alice that the bus Eve was supposed to take is not running today and that perhaps she took the subway. It adds that since the subway is suffering from delays today, that might be why Eve is late.}\eat{it can do this by reasoning about Alice's view of the Eve's operators - maybe assuming theyre the same as eve's and then coming up with a plan to explain why she's late - no bus, then she goes to subway - subway delayed, so she's late}\eat{ \textbf{Scenario 5\quad} Alice going to restaurant but \textsc{Obs} knows it's closed today because it was posted on their social media page. }\textbf{Scenario 4\quad} Alice is trying to get to her friend's house and there are two ways leading there - one is well-lit and populated (but slower) while the other is dark and deserted. Alice prefers to feel safe when walking outside after dark. \textsc{Obs} suggests Alice take the well-lit route (compared to the dark route in the sympathetic case). \eat{Neither Rose nor Alice want to feel shame (other person) } \textbf{Results\quad} Across the 9 scenarios containing empathetic agents, 87\% of participants either strongly agreed or agreed with statement (1) and 82\% either strongly agreed or agreed with statement (2). Results comparing participants' perceptions of the agent's empathetic abilities demonstrated a statistically significant difference in ratings of scenarios containing empathetic agents (\textit{M}=4.21, \textit{SD}=1.01), compared to sympathetic agents (\textit{M}=1.72, \textit{SD}=0.73), \textit{t}(39)= 12.48, \textit{p} $<$ 0.01. \eat{\textbf{COMMENTS - maybe cite one} Really helpful knowing that not many people are riding the bus. Very helpful and keeps things very private which is good - WHICH SHOWS NEED FOR EPISTEMICS \textbf{model shame as disallowing actions that cause it, such as telling Rose. Then, the assistant reasons that Elaine cannot execute this action and will therefore }} \section{Introduction}\label{intro} Artificial Intelligence (AI) systems are increasingly required to interact with other agents (be they human or artificial), but are still lagging in their ability to empathize with them when reasoning about their behavior. In the context of AI planning (the problem of selecting a goal-leading plan based on a high-level description of the world), an empathetic agent should be able to construct a plan that is harmonious with the goals, beliefs, values, affective state, and overall perspective of a fellow agent. Further, we are interested in facilitating the creation of empathetic agents holding a wide spectrum of roles - from passive observers, to virtual agents that offer relevant advice or act on someone's behalf, all the way to embodied agents who can physically interact with the environment and other agents in it. To illustrate, consider Alice who lives with panic disorder and agoraphobia. Alice \textit{fears} crowded places that might trigger a panic attack, and avoids busy restaurants, malls, and buses. Thus, Alice would never use public transit to get to work, despite it being the fastest way to get there. Instead, the optimal plan for her to get to work (that she can come up with on her own) addresses her fear, and would typically require her to walk instead of taking public transit, regardless of how suboptimal it might seem to an AI planning system bent on minimizing cost and time. A plan involving a crowded bus would simply not be executable by Alice. An empathetic AI that knows of an empty bus going along a similar route (which Alice \textit{believes} is always crowded or simply does not know about), could recommend to Alice that she take it instead of walking, which would help her save time and would not place her on a crowded bus. To construct an empathetic AI that is able to empathize with Alice\eat{, understand her behavior,} and plan to assist her, we must provide it with a means of adopting her \textit{beliefs} and \textit{affective state}. To build towards this goal, our work brings together the notions of empathy and epistemic planning, which is an emerging field of research that combines AI planning and reasoning in the presence of knowledge and belief. \eat{ reasoning in the presence of knowledge and belief.\eat{. PR is the problem of inferring an agent's plan and goal given observations about its behavior} \textit{Epistemic planning}} We formalize the notion of \textit{Empathetic Planning} (EmP)\eat{and \textit{Empathetic Plan Recognition} (EmPR)} which builds on these concepts. EmP requires an empathizer to empathize with an empathizee in order to construct plans that are faithful to the empathizee's view of the world. Specifically, we posit that in order to empathize with another, one must have at her avail a sufficiently rich representation and understanding of the beliefs and affective state of the agent with whom she is empathizing. Thus, some of the settings we address, involving reasoning about belief and affect, cannot directly be modelled as classical planning problems. We therefore appeal to a rich epistemic logic framework to represent the agent's beliefs and affective state. Lastly, we propose an epistemic planning-based computational approach to solving the EmP problem, thereby enabling the use of off-the-shelf epistemic planning tools. Our approach enables a sufficiently empathetic agent to generate a plan that is at least as `good' as the best plan the empathizee can generate by herself, using her own beliefs and capabilities. Finally, it is important to consider that a human's behavior does not always expose their intentions due to misconceptions or computational limitations. We submit that empathetic agents are well-suited for distinguishing between the underlying intent of the behavior and the actual performed behavior. Empathy is often thought of as \textit{the ability to understand and share the thoughts and feelings of another} and has an extremely rich history, beginning with its philosophical foundations and leading to research in fields such as psychology, ethics, and neuroscience (e.g., \cite{coplan2011empathy,davis2018empathy}). Empathy has been found to have two components, an affective, low-level component, and a cognitive, high-level component, with the two being interconnected \cite{shamay2011neural}. The affective component allows one to share the emotional experiences of another via affective reactions to their affective states. The cognitive component utilizes cognitive and affective Theory of Mind (ToM) - the ability to represent the mental states of others - and allows one to take the perspective of another, thereby facilitating reasoning over their \textit{mental} or \textit{affective} state. We focus on the cognitive component of empathy, and work towards building empathetic agents that can reason about the mental and affective states of other agents. We submit that pro-social AI agents should be equipped with a means of reasoning about the affective state of humans. This type of reasoning will lead to more socially acceptable behavior, as highlighted by recent work \cite{mcduff2018designing}. While we do not focus on affect in this work\eat{(and our brief treatment of it does not do justice with the rich existing body of work)}, our framework can be flexibly extended with various models of affect. Lastly, we note that while we aim to build \textit{assistive} empathetic agents that are benevolent, empathy can also facilitate malicious (or simply self-serving) motivations through manipulation. As such, the introduction of EmP encourages further exploration and discussion of these important areas. There exists a large body of work on integrating empathy and ToM within intelligent agent systems in, e.g., psychological therapy, and intelligent tutoring \cite{mcquiggan2009modelling}. \cite{pynadath2005psychsim} created decision-theoretic ToM agents that can reason about the beliefs and affective states of other agents. However, this work has not appealed to the computational machinery of epistemic planning.\eat{ nor has it integrated planning and PR}\eat{ PR has also been researched extensively and was originally seen as an intersection of psychology and AI \cite{schmidt1978plan}.} Epistemic planning is an emerging field of research which is rapidly developing (e.g., \cite{baral2017epistemic}). For example, \cite{engesser2017cooperative} utilized epistemic planning and perspective taking to facilitate implicit coordination between agents. While the motivations driving their work and ours overlap, their work differs from ours both computationally and conceptually. Finally, the rich body of work on Belief-Desire-Intention (BDI) has studied affect and planning in the past (e.g., \cite{steunebrink2007logic}). However, BDI approaches have typically required agent plans to be specified in advance and we instead appeal to the flexibility of generative epistemic planning techniques to generate plans. Our approach is enabled by our combined knowledge of these fields of research and their decades-long development. The main contributions of this paper are: (1) a formalization of EmP; (2) a computational realization of EmP that enables the use of existing epistemic planning tools; (3) a study which demonstrates the potential benefits of EmP in a diversity of domains. \eat{Say in intro that empathy is also used for targeted helping and we wish to build assistive agents that can do the same - look at old paper for de waal paragraph MAYBE} \eat{*****failed to address the plan recognition task or to formulate the problem using a rich representational framework, *****.} \eat{\cite{lisetti2013can}, educational agents aimed at anti-bullying \cite{aylett2005fearnot}} \section{Preliminaries} \commentms{Any way we can cut here without revs attacking us for doing so? it's already very densely packed} In this section, we provide epistemic logic background and define the Multi-agent Epistemic Planning (MEP) problem\eat{ and describe some of the approaches to modelling it}.\eat{In the next section, we formally specify the notion of EPR, which will build upon the definitions in this section.}\eat{ We assume in the paper that agents act rationally (wrt their possibly false beliefs), i.e., they choose to perform actions which lead to an expected optimal result, where optimality is defined relative to some objective metric (in this work, the number of actions in a plan). Future work will explore various forms of limited reasoning.} We first present the multi-agent modal logic KD45$_{n}$ \cite{fagin2004reasoning} which we appeal to in our specification of EPR. Let $Ag$ and $\mathcal{P}$ be finite sets of agents and atoms, respectively.\eat{ We use $\phi$ and $\psi$ to represent formulae and $\top$ and $\bot$ to represent \textit{true} and \textit{false}, respectively.} The language $\mathcal{L}$ of multi-agent modal logic is generated by the following BNF: \begin{equation} \nonumber \varphi ::= p \mid \lnot\phi \mid \phi \land \psi \mid B_i{\phi} \end{equation} \noindent where $p \in \mathcal{P}$, $i \in Ag$, $\phi, \psi \in \mathcal{L}$ and $B_i{\phi}$ should be interpreted as \textit{``agent i believes $\phi$.''} We choose to represent the belief modality here so that we can model the false beliefs of agents. Using the equivalence $K_i{\phi} = B_i{\phi} \land \phi$, recent work on MEP has been able to capture both knowledge and beliefs. \eat{A frame is defined as a pair $(W, R)$, where $W$ is a nonempty set of possible worlds. Further, for each agent $i \in Ag$, $R_i$ is a binary relation on $W$, called the accessibility relation for $i$.} The semantics for formulae in $\mathcal{L}$ is given by Kripke models \cite{fagin2004reasoning} which are triplets, $M = \langle W, R, V \rangle$, containing a set of worlds, accessibility relations between the worlds for each of the agents ($R$ $=$ $\{R_i \mid i \in Ag\})$, and a valuation map, $V\colon W \to 2^{P}$\eat{, mapping worlds $w \in W$ to truth valuations}. When an agent $i$ is at world $w \in W$, $M$ determines, given the accessibility relations in $R_i$ pertaning to $w$, what worlds the agent considers possible.\eat{ A pointed Kripke model is a pair $s = (M, w)$, where $M$ is a Kripke model and $w$ is a world of $M$.} A formula $\phi$ is true in a world $w$ of a Kripke model $M = \langle W, R, V \rangle$, written $M,w \vDash \phi$, under these, inductively-defined conditions: $M, w \vDash p$ for an atom $p$ \textit{iff} $p$ $\in$ $V(w)$; $M, w \vDash \lnot\phi$ \textit{iff} $M, w \nvDash \phi$; $M, w \vDash \phi \land \psi$ \textit{iff} both $M, w \vDash \phi$; and $M, w \vDash \psi$, $M, w \vDash B_i{\phi}$ \textit{iff} $M, w' \vDash \phi \quad \forall w' \in W$ s.t. $R_{i}(w, w')$. We say that $\phi$ is satisfiable if there is a Kripke model $M$ and a world $w$ of $M$ s.t. $M, w \vDash \phi$. Further, we say that $\phi$ entails $\psi$, written $\phi \vDash \psi$, if for any Kripke model $M$, $M, w \vDash \phi$ entails $M, w \vDash \psi$. Next, we assume some constraints on the Kripke model, with particular properties of belief, as discussed in \cite{fagin2004reasoning}. Namely, we assume that the Kripke model is \textit{serial} ($\forall w\,\exists v\,R(w\,,v)$), \textit{transitive} ($R(w\,,v)\wedge R(v\,,u)\Rightarrow R(w\,,u)$) and \textit{Euclidean} ($R(w\,,v)\wedge R(w\,,u)\Rightarrow R(v\,,u)$), with the resulting properties of belief: i. $B_i{\phi} \land B_i{(\phi \Rightarrow \psi)} \Rightarrow B_i{\psi}$ (K - Distribution); ii. $B_i{\phi} \Rightarrow \lnot B_i{\lnot \psi}$ (D - Consistency); iii. $B_i{\phi} \Rightarrow B_i{B_i{\psi}}$ (4 - Positive Introspection); and iv. $\lnot B_i{\phi} \Rightarrow B_i{\lnot B_i{\psi}}$ (5 - Negative Introspection). These axioms, together, form the KD45$_n$ system where $n$ signifies multiple agents in the environment. Note that the formal mechanisms for planning are described in the respective papers of the various off-the-shelf epistemic planners (e.g., \cite{huang2018general})\eat{ which are able to compute solutions to the EmP problem}. We provide a logical specification of the multi-agent epistemic planning problem that is not tied to a particular planner but rather provides a logical specification without embodying any of the syntactic restrictions that have been adopted by various planners. \eat{\textbf{say this early one (yongmei mentions this in intro) and then reiterate after EPR def} The initial knowledge base (KB) and the goal, the preconditions and effects of actions can be arbitrary multi-agent epistemic formulas, progression of KBs wrt actions is achieved through higher-order belief revision or update based on effects of actions} As mentioned, we appeal to epistemic planning, which combines AI planning and reasoning over the beliefs and knowledge of agents, to formally specify EmP. We appeal to a syntactic approach to epistemic planning (as opposed to a semantic one such as \cite{bolander2011epistemic}) and represent the initial Knowledge Base (KB) and other elements of the problem as arbitrary epistemic logic formulae. Further, we appeal to a multi-agent setting in order to represent the beliefs of the empathizer, the empathizee, and possibly other agents in the environment. \begin{definition}[MEP] \label{EPDef} A multi-agent epistemic planning problem is a tuple $\langle Q, I, G \rangle$ where $Q = \langle \mathcal{P}, \mathcal{A}, Ag \rangle$ is the MEP domain comprising sets of atoms $\mathcal{P}$, actions $\mathcal{A}$, and agents $Ag$, together with the problem instance description comprising the initial KB, $I \in \mathcal{L}$, and the goal condition $G \in \mathcal{L}$. \end{definition} To define how an action $a \in \mathcal{A}$ updates the state of the world in the epistemic planning framework, we follow \cite{huang2018general} who manipulates the KB with belief revision and update operators (e.g., \cite{alchourron1985logic}), $\circ$ and $\diamond$, respectively. A deterministic action is a pair $\langle Pre,\{(\gamma_1,\epsilon_1),..., (\gamma_k,\epsilon_k)\}\rangle$, where $Pre \in \mathcal{L}$ is called the precondition of $a$, $\gamma_i \in \mathcal{L}$ is the condition of a conditional effect, and $\epsilon_i \in \mathcal{L}$ is called the effect of a conditional effect. A sensing action is a triplet $\langle Pre, pos, neg \rangle$, where $Pre, pos, neg \in \mathcal{L}$ are the precondition, the positive result, and the negative result, respectively. An action $a \in \mathcal{A}$ is executable wrt a KB $I \in \mathcal{L}$ if $I \vDash Pre(a)$. Suppose some deterministic action $a \in \mathcal{A}$ is executable wrt a formula $\phi \in \mathcal{L}$. \citeauthor{huang2018general} [\citeyear{huang2018general}] formally define the progression of $\phi$ wrt to a deterministic action $a \in \langle Pre, \{(\gamma_1,\epsilon_1),...,(\gamma_k,\epsilon_k)\}\rangle$ as follows: let \eat{$\{\gamma_i \mid \phi \vDash \gamma_i\}$} $\gamma_{i_{1}}, ..., \gamma_{i_{m}}$ be all the conditions of conditional effects s.t. $\phi \vDash \gamma_i$. Then $\phi'$, denoted by $prog(\phi,a)$, is a progression of $\phi$ wrt $a$ if $\phi' = ((\phi \diamond \epsilon_{i_{1}})...) \diamond \epsilon_{i_{m}}$, where $\epsilon_{i_{j}}$ is the effect corresponding to the condition $\gamma_{i_{j}}$.\eat{For example, let $p \in \mathcal{P}$, $i \in Ag$, $\mathcal{I} = \lnot p \land B_i{\lnot p}$ and $a \in \mathcal{A}$ where $\epsilon_{j}$, the effect of one of $a$'s conditional effects, is $p \land B_i{p}$. The update operation, $\mathcal{I} \diamond \epsilon_{j}$, will yield $\mathcal{I}' = p \land B_i{p}$.} The progression of $\phi \in \mathcal{L}$ wrt a sensing action $a \in \mathcal{A}$ and positive result (resp. negative) is defined as $\phi^{+} = \phi \circ pos(a)$ (resp. $\phi^{-} = \phi \circ neg(a)$). Let $\phi \in \mathcal{L}$ and $\pi = a_1,...,a_k$ a sequence of actions. The progression of $\phi$ wrt $\pi$ (with sensing results for sensing actions) is inductively defined as follows: $prog(\phi,\epsilon)=\phi$; $prog(\phi,(a;\sigma)) = prog(prog(\phi,a),\sigma)$ if $\phi \vDash Pre(a)$, and undefined otherwise. $\epsilon$ is an empty sequence of actions. A \textbf{solution} to an MEP problem is an action tree branching on sensing results, such that the progression of the initial KB, $I$, wrt each branch in the tree entails the goal $G$. \section{Related work}
{'timestamp': '2019-06-18T02:03:23', 'yymm': '1906', 'arxiv_id': '1906.06436', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06436'}
arxiv
\section{Public States and Subgames}\label{sec:public} \section{Bonus Exercise}\label{sec:exercise} \begin{figure}[htb] \centering \begin{tikzpicture} \unfairMP \unfairMPtext \end{tikzpicture} \caption{A classical model for the unfair variant of Matching Pennies.} \label{fig:unfair_mp} \end{figure} As an example illustrating the difficulties that one can encounter when defining augmented information sets and public states, we include a ``case study'' exercise. Consider the game defined by the following description: \begin{example}\label{ex:unfair_mp} Unfair Matching Pennies. \end{example} \noindent Two players are playing a real-life game of Matching Pennies for the prize of 10\,000 dollars. To ensure that none of them can cheat, they use a third person as a referee. At the start of the game, each player is in a separate room. The referee randomly chooses the player who acts first, goes to him, and asks him for his action. He then goes to the second player and asks him for his action. By default, the players do not get to know whether they are first or second. Now comes the twist: the referee really hates people who choose heads --- if the first player to choose picks heads, the referee will reveal this to the second player. (From some reason the players chose this referee even though they know this.) \medskip \begin{exercise} What is the minimal classical model corresponding to the game from Example~\ref{ex:unfair_mp}? How do (augmented) information sets and public states look like in this $M^\textnormal{cl}$? Can players tell whether they have been betrayed by the referee or not? Is $M^\textnormal{cl}$ a good underlying model for an observation-based model of this game? If not, what is the minimal well-behaved modification $M$ of $M^\textnormal{cl}$? \end{exercise} \section{Conclusion} We have pointed out several issues with the standard EFG model (Figures~\ref{fig:poker} and \ref{fig:coarse_infosets_fail_io}), as well as examples where augmented information sets necessarily behave undesirably or against our intuition (Figures~\ref{fig:sneaking_game_modification}, \ref{fig:thick_infosets} and \ref{fig:unfair_mp}). We described a model that is similar to EFG but uses observations to introduce imperfect information into an originally fully-observable environment. Any instance of this observation-based model can be turned into a compatible EFG (Conjecture~\ref{prop:obs_model_is_game}), and the converse is also true if one is willing to modify the underlying perfect-information model and observe some information late (Example~\ref{ex:coarse_model}). We have also shown that if one isn't willing to make these sacrifices, the task is impossible (Corollary~\ref{cor:impos} and Example~\ref{ex:no_finest_partit}). The EFG model has not been introduced with online play, decomposition, or observations in mind. After reviewing the difficulties that come up when attempting to extend EFGs by adding observations and staying consistent with the original model, we ultimately concluded that it is more productive to work in a model which contains observations natively. Therefore, we believe that for investigating sequential decision-making in multiagent settings with imperfect information, researchers should adopt a model based on partially-observable stochastic games (POSGs, see, e.g., \cite{hansen2004dynamic}), such as the Factored-Observation Game model described in \cite{FOG}. We predict this will benefit the researchers who are now working in the EFG formalism since POSGs will make decomposition easier, and simplify the transfer of ideas between game theory and multiagent RL (MARL) by using language with which the (more numerous) MARL community is more familiar. Moreover, POSG-based models offer several advantages over EFGs, such as compact representation of cyclic state-spaces, the ability to give feedback in non-terminal states, and natural modeling of simultaneous decisions. \subsection*{Acknowledgments} We are grateful to Tomas Gavenciak for discussions related to an earlier version of this paper. This work was supported by Czech science foundation grant no. 18-27483Y and RCI CZ.02.1.01/0.0/0.0/16 019/0000765. \section{Introduction}\label{sec:intro} The remainder of this paper operates under the assumption that the best way to fix the model we use to talk about imperfect information games is to extend the extensive-form game (EFG) model. While writing this text, we came to believe that a better solution is to adopt a model based on partially-observable stochastic games. For a definition of such a model and an overview of related literature, we invite the reader to see \cite{FOG}. \paragraph{Why do we need a new notation?} While the classical EFG formalism is very useful, it has grown outdated --- the recent algorithmic breakthroughs such as \cite{DeepStack} rely on decomposition, exploiting concepts such as augmented information sets and public states which aren't present in the classical EFG notation. Coincidentally, multiagent reinforcement learning (MARL) solves similar problems as the EFG community, but there hasn't been a lot of transfer of ideas between the two areas. Making the EFG literature more accessible to the MARL community would simplify this transfer, as well as making the \emph{thinking} about the connections more efficient. These two reasons lead us to believe it is time to revise the model we use to talk about imperfect information games. \paragraph{The goal of this text:} This text presents an analysis which should serve as an incremental step towards revising the model for imperfect information games. We focus on a narrower list of desiderata, aiming for notation which defines \begin{itemize} \item augmented information sets -- being able to talk about available information even when it isn't my turn (e.g., for the construction of resolving gadget \cite{Neil_thesis}), \item observations -- to analyze how players receive and handle information (mainly since the approach seems natural, interesting, and relevant). \end{itemize} We aim to do this in such a way that \begin{itemize} \item the new concepts fit together within one framework, \item the players get as much information as possible, as soon as possible (good for online play, leads to smaller subgames that are cheaper to solve), \item the resulting notation is familiar to people used to the classical notation. \end{itemize} \subsection{Specific arguments for why the current notation doesn't suffice} \begin{itemize} \item There are currently definitions of augmented information sets (\cite{CFR-D}), public states (\cite{accelerated_BR}) and subgames (\cite{CFR-D}) in the literature. However, they do not necessarily always fit together (at the very least, the relationship between the definitions from \cite{CFR-D} and \cite{accelerated_BR} is not obvious). \item These definitions currently do not behave as one would intuitively expect them to: \begin{itemize} \item One straightforward interpretation of the augmented information set definition from \cite{CFR-D} is ``$g,h\in \mathcal H$ belong to same $I\in \mathcal I^\textnormal{aug}_i$ if they have the sequence of $i$'s actions and classical information sets visited by $i$.'' \item One way of defining public states is as ``subsets of $\mathcal H$ closed under the membership within the elements of $\mathcal I_i^\textnormal{aug}$ for each $i$''. \item However, this means that players will group all nodes between their action and their next information set. This partitioning leads to a strange behavior (for example, in poker, see Figure~\ref{fig:poker}). \end{itemize} \end{itemize} \begin{figure} \centering \setlength{\nodesize}{2em} \begin{tikzpicture} \pokerHistory \pokerA \end{tikzpicture} \begin{tikzpicture} \pokerHistory \pokerB \end{tikzpicture} \begin{tikzpicture} \pokerHistory \pokerC \end{tikzpicture} \begin{tikzpicture} \pokerHistory \pokerD \end{tikzpicture} \caption{\textbf{Failure of the recent EFG definitions}. From left to right: (a): A subset of the public tree \emph{as we intuitively imagine it} in the game of limit Texas hold 'em, corresponding to a history where both players only placed the standard bet sizes, never folding or raising. (b) and (c): Classical (solid) and augmented (dashed) information sets of player 1 and player 2. (d): The public states \emph{actually} corresponding to these information partitions. As we can see, there are only five public states along this history, rather than 12 as one might intuitively expect, and they do \emph{not} even correspond to the rounds of the game (which might still be acceptable).} \label{fig:poker} \end{figure} \begin{itemize} \item We claim that the classical imperfect information EFG model is insufficient for some purposes and that the concepts such as augmented information sets either cannot be derived from it in a domain-independent way (Section~\ref{sec:ext_cl_model}). \item While the classical model of imperfect information in games answers the question of \emph{which} information a player has available; it is under-specified in that it doesn't explain \emph{when} the information becomes available. One way of interpreting the classical model is by assuming that the player receives no information when it isn't his turn. However, this is often an inaccurate way of modeling the actual situation -- when taken literally, this would correspond to each player only entering the room where the game is being played upon the start of his turn, being told the history of the game by a referee, taking his action, and then leaving the room again. Moreover, having to assume a player receives no information during his turn means he cannot use the time between his turns as effectively as he might otherwise. \end{itemize} In Section~\ref{sec:background}, we list the background relevant to the text that follows --- we use the perfect-information extensive-form game model as the ``underlying model'' and turn it into the ``classical'' imperfect information model by adding the ``classical'' information partitions. Section \ref{sec:observations} formalizes the concept of observations built on top of the underlying model. We start by discussing the setting where the players aren't able to remember the observations they receive, but we quickly modify it in favor of the approach where players have perfect recall with respect to observations and their actions. We define two variants of observation histories, depending on whether the players can tell where one observation ends and another begins or not. We also introduce information partitions corresponding to observations, and the dual notion of observations corresponding to information partitions. In Section~\ref{sec:obs_and_cl}, we present and discuss a list of technical desiderata for observations and the corresponding information partitions. We give examples of different ways in which these properties might fail to hold. We also investigate the limitations of defining observations based solely on the classical imperfect information model, without the guidance of the motivating real-life problem. Finally, Section~\ref{sec:augm_model} introduces the proposed observation-based model of imperfect-information games. It first analyzes the notion of deducing features from observations, studies the conditions under which observation-induced information partitions have the structure of a tree, and presents a construction called ``stable modification'' that ensures these conditions are met. This section proves that the observation-based model satisfies the technical desiderata listed earlier, and gives a canonical recipe for building a ``coarse'' observation-based model that corresponds to a given classical model. We also include an appendix, which briefly lists some ideas related to public states, common knowledge and subgames (but we do \emph{not} discuss this topic further). It also contains the description of a game of unfair matching pennies, which serves as an example of a ``tricky'' domain where some of the design proposals might be tested. We conclude with a long list of desiderata for a possible future notation. \vknote{Not all of the proofs are currently typed in, but I have most of them written on paper. For the remaining propositions I have strong intuitions that they either hold exactly as they are written or only require minor technical modifications.} \section{Observations and Perfect Recall}\label{sec:observations} Suppose we have a real-life problem $P$ that includes dealing with imperfect information, and all relevant actors have perfect recall. Optionally, we might already have a classical imperfect information model $\left< M^\textnormal{cl}, \mathcal I^\textnormal{cl} \right>$ of $P$. We use a (perfect information) EFG model $M$ to formally describe the underlying situation in $P$. Our goal is to formalize the notions of augmented information sets and public states in $M$ in such a way that is useful for some of the recent game-theoretic algorithms and maximally advantageous for online-play. In this section, we describe the observation formalism that shall be useful for discussing this topic. \subsection{Observations Without Recall} To introduce some of the ideas related to observations, we start with a brief discussion of the setting where the actors aren't able to remember their observations. Note that this setting \emph{can} be used to analyze perfect recall games since histories can be provided by the environment through observations. A secondary goal of this discussion is to allow for a comparison with the alternative proposed in Section~\ref{sec:obs_pr}. We add observations as an extension of the underlying model. An important assumption we make is that each player knows exactly how this model works and how the generation of observations works. At each state $h\in \mathcal H$, each player receives some observation. As an example, suppose player 1 observes the message ``Ugh!''. We assume the observations convey no meaning of themselves, so all that he can tell is that he is currently in one of the states which produce the observation ``Ugh!''\footnote{We could also assume that observations do convey some information about the current state of the game. This assumption would increase the ``learnability'' of $\left< M, \mathcal O\right>$ (see the list of desiderata in the appendix) at the cost of introducing another layer of notation.} (see the bottom left part of Figure~\ref{fig:no_memory_vs_pr}). Formally, this can be done by using the pair $\left<M,\mathcal O\right>$, where $M=M^\textnormal{cl}$ and $\mathcal O = (O_1, \dots, O_N)$ are the observation-generating functions $O_i : \mathcal H \rightarrow \mathbf{O}_\textnormal{no\_recall}$ for some set $\mathbf O_\textnormal{no\_recall}$ of all possible \emph{observations}. When the players have no memory, the information sets that correspond to these observations are \begin{align*} \{ g \in \mathcal H \, | \ O_i(g) = O_i(h) \}. \end{align*} \noindent In other words, all the information that has been observed is lost, and only the current observation is used to build the information set. \noindent Note that the corresponding information partition covers the whole $\mathcal H$ -- in particular, it covers the terminal nodes $\mathcal Z$. All ``non-classical'' information partitions presented in this text will have this property. While the information available in terminal nodes is usually not strategically important, this aspect of the game might sometimes be interesting, for example, when the game is played repeatedly. Most importantly, it comes at no additional cost to the complexity of the discussion. \begin{figure}[ht] \centering \setlength{\nodesize}{2.5em} \begin{tikzpicture} \perfRecallGame[1] \perfRecallInfosets \end{tikzpicture} \setlength{\nodesize}{2em} \begin{tikzpicture} \perfRecallGame[1] \perfRecallInfosetsA \end{tikzpicture} \begin{tikzpicture} \perfRecallGame[1.25] \perfRecallInfosetsB \end{tikzpicture} \caption{Observations of the maximizing player (top, denoted X, Y, Z, W) and the corresponding memory-less information partitions (bottom left) and perfect-recall (bottom-right) information sets.} \label{fig:no_memory_vs_pr} \end{figure} The following example shows how the classical model of imperfect information can arise as a particular case of this model. \begin{example}\label{ex:obs_cl_no_recall} Classical information sets coincide with those given by observing information-set labels. \end{example} \noindent Suppose that $\mathcal I_i^{\textnormal{cl}}$ is the ``classical'' information partition for player $i$ in a game $G = \left< M^\textnormal{cl}, \mathcal I^\textnormal{cl} \right>$. The ``classical'' observations tell $i$ the name\footnote{The understanding here is that the observation $O=I_i^\textnormal{cl}(h)$ gives $i$ the name (label, number, hash-code) of the current information set, and he then constructs $I$ himself via $I_i(O)$, using his knowledge of $\left<M,\mathcal O\right>$. Formally, it might be more precise to use some injective labeling mapping $l : \mathcal I_i^{\textnormal{cl}} \rightarrow \mathbb{N}$ and write $O_i(h) = l(I_i^\textnormal{cl}(h))$. We choose not to do this for brevity.} of the current information set whenever it is his turn to act: \begin{equation*} O^\textnormal{cl}_i(h) := \begin{cases} \textnormal{``Not your turn.''} & h \notin \mathcal H_i \\ I^\textnormal{cl}_i(h) & h \in \mathcal H_i. \end{cases} \end{equation*} Obviously, the information sets generated by $\mathcal O^\textnormal{cl}$ coincide with $\mathcal I^\textnormal{cl}_i$ in the sense that for each $h\in \mathcal H_i$, $\{ g \in \mathcal H \, | \ O_i(g) = O_i(h) \} = I^\textnormal{cl}_i(h)$. \medskip Note that since the agent has no memory, he relies on the observations to provide all required information. If the observations were provided verbally be a referee, he would have to repeat the whole history of the game on each turn. In practical terms, a typical element of $\mathbf O_\textnormal{no\_recall}$ in Chess would look like $O$ = ``Game started. White Pawn from B2 to B3. Black Pawn from B7 to B6. \dots White queen from C4 to E4. Captured black tower at E4. Your turn.''. While this is a reasonable assumption for some practical implementations, it does not give a deeper insight into how different augmented information sets arise in games. Since the understanding of augmented information sets is the goal of this text, we will now turn our attention to the more detailed model where the agent can keep track of the observation history for himself. \subsection{Observations with Perfect Recall}\label{sec:obs_pr} When the players have perfect recall, the situation is different. They can ``write down'' all of the observations they have received from the external environment so far together with all the decisions they have made, and potentially all kinds of other information (such as time-stamps for each observation, their thoughts/internal state upon making each decision, \dots). To keep the analysis as simple as possible, we shall only consider the situation where each agent $i$ takes the observations $(O_1, O_2, \dots, O_n )$ received so far together with the actions $(a_1, \dots, a_k)$ he has made and combines them into his observation history $\vec O_i$ in a yet-unspecified manner. The agent is then able to use $\vec O$, rather than $O_n$, to figure out where in the game tree he might currently be. (Alternative names for $\vec O$ might be $i$'s action-observation history, information history, memory, log. We will stick with ``observation history'' in this text, with the critical disclaimer that $\vec O$ contains not only observations but also memories of past decisions, and these are of a different type than observations.) It is surely possible to view observations as monolithic objects which cannot be further reduced (such as $O$ = ``White moved a Pawn from B2 to B3 and it is now your turn.'' without the ability to split the sentence in two). However, it will be useful to assume that there are two types of objects, elementary observations (such as $o_1$ = ``White moved a Pawn from B2 to B3.'' and $o_2$ = ``It is now your turn.'') and ``big'' observations received in a single state (such as $O = (o_1, o_2)$). Consider an alternative scenario where the above elementary observations $o_1$ and $o_2$ were instead made in two successive states (e.g., because the opponent pressed the button on the tournament clock 30 seconds after making his move) and suppose there is a strategic advantage to being able to tell the two scenarios apart. We need to decide whether we want our model to be such that the player can distinguish between the two scenarios \emph{based on the observations received}\footnote{Of course, we could add a third observation ``the opponent not doing anything for 30 seconds'', but that isn't the point.}? To analyze the situation better, we shall formalize both versions and compare them. We can go ahead and spoil the conclusion: each version has its advantages and disadvantages, and they are, in general, not equivalent. However, the domains where the two approaches differ have important undesirable properties, and should be avoided (or rather, slightly different $M$ needs to be chosen to serve as an underlying model for given ``problematic'' real-life problem $P$). \begin{definition}[Observation space]\label{def:obs_space} The \emph{space of possible observations} in $M$ can be an arbitrary non-empty set, and shall be denoted $\mathbf O$. \end{definition} \noindent In the Chess example, typical elements of $\mathcal O$ can be ``Game started.'', ``White Pawn from B2 to B3.'', ``Black tower at E4 has been captured.'', ``Check by white.'', ``Game ended.'', ``You won.''. Of course, there might be different (e.g., less verbose) ways of encoding these observations. Moreover, observations can transfer all information the players might be interested in, but they can also be sparser: Suppose black knows that the white queen is at C4, a black tower is at E4, and that it is white's turn. Then the message ``C4 to E4'' suffices for him to deduce that the queen took his tower, and he doesn't have to be told explicitly. The following ``set variant'' of observations captures the ``you can tell the difference'' approach. \begin{definition}[Observations, set variant] An \emph{observation function} is a vector $\mathcal O_{\{\}} = (\mathcal O_{\{1\}}, \dots, \mathcal O_{\{N\}})$, where $\mathcal O_{\{i\}} : h\in \mathcal H \mapsto O_{\{i\}}(h) \subset \mathbf O$. The set $O_{\{i\}}(h)$ is called \emph{$i$'s observation at $h$}. \end{definition} By $X^* := \{ (x_1, \dots, x_n)\,|\ n\in \mathbb{N}\cup\{0\} ,\, x_i\in X\}$ we denote the set of all finite sequences in $X$ (including the empty sequence $\emptyset$). \begin{definition}[Observation histories, set variant] We define the player $i$'s \emph{observation history} function $\vec{\mathcal O}_{\{i\}} : h\in \mathcal H \mapsto \vec O_{\{i\}}(h) \in (\mathcal P(\mathbf O) \cup \mathcal A)^*$ as follows. We set $\vec{O}_{\{i\}}(\emptyset) := (\, O_{\{i\}}(\emptyset) \, )$ for $h=\emptyset$ ($\vec{O}_{\{i\}}(\emptyset) := \emptyset $ when $O_{\{i\}}(\emptyset) = \emptyset$). Otherwise, we have $h=h'a$, $a\in \mathcal A(h')$ and $\vec{O}_{\{i\}}(h') = ( X_1, \dots, X_n )$ for some $X_j \in \mathcal P(\mathbf O) \cup \mathcal A$. For non-empty $O_{\{i\}}(h)$ we set \begin{equation*} \vec O_{\{i\}}(h) := \begin{cases} \left(\, X_1, \, \dots, \, X_n , \, a, \, O_{\{i\}}(h) \,\right) & h'\in \mathcal H_i \\ \left(\, X_1, \, \dots, \, X_n , \, O_{\{i\}}(h) \,\right) & h'\notin \mathcal H_i . \end{cases} \end{equation*} Empty observations are ignored, i.e. for $O_{\{i\}}(h) = \emptyset$ we set \begin{equation*} \vec O_{\{i\}}(h) := \begin{cases} \left(\, X_1, \, \dots, \, X_n , \, a \, \right) & h'\in \mathcal H_i \\ \left(\, X_1, \, \dots, \, X_n \, \right) = \vec O_{\{i\}}(h') & h'\notin \mathcal H_i \end{cases} . \end{equation*} \end{definition} To formalize the approach where it doesn't have to be possible to tell where one observation ends and another begins, we define the ``sequence variant'' of the above notation. \begin{definition}[Observation, sequence variant] An \emph{observation function} is a vector $\mathcal O_{()} = (\mathcal O_{(1)}, \dots, \mathcal O_{(N)})$, where $\mathcal O_{(i)} : h\in \mathcal H \mapsto O_{(i)}(h) \in \mathbf O^*$. The set $O_{(i)}(h)$ is called \emph{$i$'s observation at $h$}. \end{definition} \begin{definition}[Observation histories, sequence variant] We define the player $i$'s \emph{observation history} function $\vec{\mathcal O}_{(i)} : h\in \mathcal H \mapsto \vec O_{(i)}(h) \in (\mathbf O \cup \mathcal A)^*$ as follows. For $h=\emptyset$ we set $\vec{O}_{(i)}(h) := O_{(i)}(h) $. Otherwise, we have $h=h'a$, $a\in \mathcal A(h')$ and $\vec{O}_{(i)}(h') = ( x_1, \dots, x_n )$ for some $x_j \in \mathbf O \cup \mathcal A$. For $O_{(i)}(h) = (o_1,\dots,o_k)$ we set \begin{equation*} \vec O_{(i)}(h) := \begin{cases} \left(\, x_1, \, \dots, \, x_n , \, a, \, o_1, \, \dots, \, o_k \,\right) & h'\in \mathcal H_i \\ \left(\, x_1, \, \dots, \, x_n , \, o_1, \, \dots, \, o_k \,\right) & h'\in \mathcal H_i . \end{cases} \end{equation*} \end{definition} \noindent Note that in the sequence variant, empty observations are ignored naturally. When there is no danger of confusion, we omit the brackets and simply write $\mathcal O = (\mathcal O_1, \dots, \mathcal O_N)$, $O_i(h)$ and $\vec O_i(h)$. When we don't want to specify whether a given observation has the set or sequence form, we shall denote it as $O_i(h) := a,b,c$ --- with the understanding that it can be turned into either $\{a,b,c\}$ or $(a,b,c)$ by writing $O_{\{i\}}(h)$ or $O_{(i)}(h)$. With the help of observation histories, players can partition $\mathcal H$ into information sets: \begin{definition}[Information sets and partitions] The \emph{information partitions} corresponding to an observation function $\mathcal O$ are defined as $\mathcal I^{\mathcal O} = (\mathcal I_1^{\mathcal O}, \dots, \mathcal I_N^{\mathcal O} )$, $\mathcal I^{\mathcal O}_i := \{ I_i^\mathcal{ O}(h) \, | \ h\in \mathcal H \}$, where \[ I_i^\mathcal{ O}(h) := I_i^\mathcal{ O} \left( \vec O_i(h) \right) := \{ g \in \mathcal H \, | \ \vec O_i(g) = \vec O_i(h) \} . \] \end{definition} \medskip Note that we do not need to use the perfect-recall model to reason about actors who have perfect recall. Indeed, the perfect-recall model can be turned into a memory-less model by replacing $\mathcal O_i$ by $\vec{\mathcal O_i}$ with $\mathbf O_{no\_memory} := (\mathbf O \cup \mathcal A)^*$, and the resulting model would be equally good. We do not claim that the memory-less model is worse --- rather, we claim that it only makes sense to consider memory-less models that arise in the just described manner. \medskip So far, we have shown how to generate information partitions from observations. However, information sets are, in a sense, dual to observations, and there is a canonical way of going in the opposite direction: \begin{example}\label{ex:obs_I} Observations corresponding to an information partition. \end{example} \noindent Consider an arbitrary collection of partitions $\mathcal I = (\mathcal I_1, \dots, \mathcal I_N)$ of $\mathcal H$ and, writing either $h=\emptyset$ or $h=h'a$ for $h\in \mathcal H$ as in Notation~\ref{not:h'}, define \begin{equation*} O_i^{\mathcal I}(h) := \begin{cases} I_i(h) & h=\emptyset \lor I_i(h) \neq I_i(h') \\ \emptyset & I_i(h) = I_i(h') . \end{cases} \end{equation*} \noindent To extend the definition to collections $\mathcal I_i$ which only cover some subset of $\mathcal H$, we could replace $h'$ in the above formula by ``the longest prefix of $h$ that belongs to $\bigcup \mathcal I_i$'' and set $O^{\mathcal I}_i(h) := \emptyset$ for $h\notin \bigcup \mathcal I_i$. \section{Technical Desiderata and Related Obstacles}\label{sec:obs_and_cl} When constructing an observation-based model $\left< M, \mathcal O \right>$ of $P$ in the (optional) presence of a classical model $\left< M^\textnormal{cl}, \mathcal I^\textnormal{cl} \right>$, it is natural to consider the following properties: \begin{itemize} \item[\namedlabel{it:noCH}{($\neg$CH)}] No changes to $M^\textnormal{cl}$ -- the underlying model shouldn't be modified in any way, i.e. $M=M^\textnormal{cl}$. \end{itemize} \noindent To simplify the the notation, we will henceforth assume that \ref{it:noCH} holds unless explicitly stated otherwise. \begin{itemize} \item[\namedlabel{it:cons}{(CONS)}] Consistency with $\left< M^\textnormal{cl}, \mathcal I^\textnormal{cl} \right>$ -- the information sets generated by $\mathcal O$ should coincide with $\mathcal I^\textnormal{cl}$: \begin{equation*}\label{eq:coinc_on_H_i} \mathcal I^{\mathcal O}_i |_{\mathcal H_i} = \mathcal I^\textnormal{cl}_i \textnormal{ -- in other words, we have } \left( \forall h\in \mathcal H_i \right) : I_i^\mathcal{ O}(h) \cap \mathcal H_i = I_i^\textnormal{cl}(h) . \end{equation*} \item[\namedlabel{it:sep}{(APS)}] Acting-player separation -- each player should be able to tell whether it's currently his turn to act or not: \begin{equation*} \left(\forall h \in \mathcal H_i \right) \left(\forall g \in \mathcal H_{-i} \right) : I_i^\mathcal{ O}( h ) \neq I_i^\mathcal{ O}( g ) . \label{eq:separate} \end{equation*} \item[\namedlabel{it:iso}{(ISO)}] Immediate self-observation -- additionally to \emph{remembering} their own actions, the players should also be able to \emph{observe} their own actions as soon as they are made. \item[\namedlabel{it:io}{(IO)}] Immediate observation -- more generally, if an event is visible to an actor in $P$, then the corresponding player in $\left<M,\mathcal O\right>$ should observe the corresponding piece of information as soon as the event happens. \item[\namedlabel{it:tip}{(TSIP)}] Tree-structured information partitions -- each $\mathcal I_i^{\mathcal O}$ should form a tree when endowed with the partial order $I \sqsubset J \iff (\exists g \in I) (\exists h\in J) : g \sqsubset h$.\footnote{Without \ref{it:tip}, public states cannot serve as roots of subgames. Showing this requires, e.g., the game from Figure~\ref{fig:sneaking_game_modification}, and definition of public states and subgames (which aren't presented in this text at all).)} \end{itemize} \noindent As we will see in Lemma~\ref{lem:stab}, \ref{it:tip} is equivalent to the following stability condition. \begin{itemize} \item[\namedlabel{it:stab}{(STAB)}] Stability -- the observations generated by $\mathcal I^{\mathcal{ O}}$ should be equivalent to $\mathcal O$: \begin{equation*}\label{eq:stable} \mathcal I^{\mathcal{ O}} = \mathcal I^{\mathcal{ O^\star}}, \textnormal{ where } \mathcal O^\star := \mathcal O^{\mathcal I^{\mathcal{ O}}} . \end{equation*} \end{itemize} We make the following observations and remarks: \begin{itemize} \item Most of the above conditions speak about the properties of $\mathcal I^{\mathcal O}$. In this sense, the following text speaks about how to design well-behaved augmented information sets, and observations are only used as a useful formal language for the discussion. \item This notation allows for a simple-yet-formal definition of perfect recall in the classical model: \begin{definition}[Perfect recall]\label{def:perf_rec} Players in $\left< M^\textnormal{cl}, \mathcal I^\textnormal{cl} \right>$ have \emph{perfect recall} if $\mathcal O^{\mathcal I^\textnormal{cl}}$ satisfies \ref{it:cons}. \end{definition} \item We do not claim that it is necessary to satisfy the condition \ref{it:iso}. Rather, our understanding is that the model shouldn't break when it is included. For example, we might wish to include the action in a public observation that is visible to everyone, and hence also to the player who has made the action. \item \ref{it:stab} can be viewed as a stronger version of consistency of $\mathcal O^{\mathcal I^{\mathcal O}}$ with $\mathcal I^{\mathcal O}$ (in the sense of \ref{it:cons}). \end{itemize} \subsection{Observations and the Classical Model} \begin{example}[Classical observations]\label{ex:cl} Observations corresponding to $\mathcal I^\textnormal{cl}$ satisfy \ref{it:cons} and \ref{it:sep}, but fail \ref{it:io} and \ref{it:iso} (and \ref{it:stab}). \end{example} \noindent The classical information partitions are ``thin'' in the sense that it is impossible for $h=h'a$ and $h'$ to belong to the same $I\in \mathcal I^\textnormal{cl}_i$. It follows that $\mathcal O^{\mathcal I^\textnormal{cl}}$ can also be written as \begin{equation*} O_i^\textnormal{cl}(h) := \begin{cases} \emptyset & h \notin \mathcal H_i \\ I^\textnormal{cl}_i(h) & h \in \mathcal H_i . \end{cases} \end{equation*} \noindent These observations are consistent with $\mathcal I^\textnormal{cl}$ (tautologically) and satisfy \ref{it:sep} (since $h$ belongs to $\mathcal H_i$ iff $\vec O_i(h)$ ends with an information set). However, they fail \ref{it:iso} --- indeed, for example in a two-player game without chance where players take one turn each, if player 1 didn't remember his action $a_1$ at some $h\in \mathcal H_1$, he would only learn about it through observing the next information set $I_1(h a_1 a_2)$ where he acts (and not already during the opponent's turn at $h a_1$). More generally, $\mathcal O^{\mathcal I^\textnormal{cl}}$ fails \ref{it:io} as soon as a visible action of another player leads to some $g \notin \mathcal H_i$ (e.g. in any two-player perfect-information game with chance). Later (Example~\ref{ex:iso}) we will see that $\mathcal O^{\mathcal I^\textnormal{cl}}$ also sometimes fails \ref{it:stab}. \medskip To simplify the notation, we introduce the notion of adding two observation functions together: \begin{notation} Let $\mathcal O$ and $\mathcal O'$ be two observation functions in $M$. By $\mathcal O + \mathcal O'$ we denote the observation function defined, for $O_i(h) = o_1,\dots, o_n$ and $O'_i(h) = o'_1,\dots, o'_k$, as $O^+_i(h) := o_1, \dots, o_n, o'_1, \dots, o'_k$. \end{notation} The observations from Example~\ref{ex:cl} can be modified to get \ref{it:iso}. However, this comes at a cost: \begin{example}[Immediate self-observation]\label{ex:iso} Enforcing \ref{it:iso} together with \ref{it:noCH} and \ref{it:sep} can destroy \ref{it:cons} when the set approach is adopted. Enforcing \ref{it:noCH} together with \ref{it:cons} and \ref{it:sep} can destroy \ref{it:stab}. \end{example} \noindent Consider the observations $\mathcal O^\textnormal{iso}$ which let each player observe his action $a$ in the history immediately following the one where he took $a$: \begin{equation*} O_i^\textnormal{iso}(h) := \begin{cases} \emptyset & h = \emptyset \lor h' \notin \mathcal H_i \\ a & h' \in \mathcal H_i . \end{cases} \end{equation*} Combining these with the classical observations into $\mathcal O^\textnormal{iso+cl} := \mathcal O^\textnormal{iso} + \mathcal O^\textnormal{cl}$ yields observations which satisfy \ref{it:iso} (by definition) and \ref{it:sep} (by Example~\ref{ex:cl}). However, as the game in Figure~\ref{fig:sneaking_game_modification} illustrates, $\mathcal O^\textnormal{iso+cl}_{\{\}}$ can be inconsistent because the player can now always tell whether he acts two times in a row or not. The sequence version $\mathcal O^\textnormal{iso+cl}_{()}$ will remain consistent, but it will be unstable. In fact, the only partition, of $M^\textnormal{cl}$ from Figure~\ref{fig:sneaking_game_modification}, satisfying both \ref{it:cons} and \ref{it:sep} is the one depicted in therein. Since this partition is unstable, we get the second part of the claim. Adding a single dummy node (Figure~\ref{fig:sneaking_game_modification}, right) leads to both $\mathcal O^\textnormal{iso+cl}_{\{\}}$ and $\mathcal O^\textnormal{iso+cl}_{()}$ satisfying \ref{it:cons}, \ref{it:sep}, \ref{it:iso} and \ref{it:stab}, at the cost of modifying the domain (i.e. failing \ref{it:noCH}). \begin{figure}[htb] \centering \begin{tikzpicture}[scale=1] \node(middle){}; \sneakingGamePartition \sneakingGameModification \end{tikzpicture} \caption{Sneaking game where the skill of one player determines whether the other will detect him, and different ways of subsequent attacking are effective in each scenario (left). This is a domain where set-like observations together with immediate self-observation are inconsistent. (Credit to Tomáš Gavenčiak for realizing this might be possible.) Even without \ref{it:iso}, the augmented information states are unstable (middle), but a stable modification can be constructed by adding one dummy node (right).} \label{fig:sneaking_game_modification} \end{figure} Example~\ref{ex:iso} yields the following corollary: \begin{corollary}[A case against \ref{it:noCH}]\label{cor:impos} In general, it is impossible to simultaneously achieve \ref{it:cons}, \ref{it:sep} and \ref{it:stab} unless \ref{it:noCH} is dropped. \end{corollary} In some sense, the underlying model of the sneaking game counterexample is anomalous. The following lemma characterizes those domains which do not have to be modified in order to make $\mathcal O^\textnormal{iso+cl}$ work: \begin{lemma}[Well-behaved domains]\label{lem:consist_domain} If the condition \ref{it:wb} holds for $\left< M^\textnormal{cl}, \mathcal I^\textnormal{cl} \right>$, then $\mathcal O^{\textnormal{cl+iso}}$ satisfies \ref{it:cons}, \ref{it:sep}, \ref{it:iso} and \ref{it:stab} without having to drop \ref{it:noCH}. \begin{itemize} \item[\namedlabel{it:wb}{(WBD)}] $\ \ \ \ \left( \forall I \in \mathcal I_i^\textnormal{cl} \right) \left( \forall g,h \in I \right) \left( \forall a \in \mathcal A(I) \right) : \left( ha \in \mathcal H_i \ \& \ ga \in \mathcal H_i \right) \lor \left( ha \notin \mathcal H_i \ \& \ ga \notin \mathcal H_i \right)$ . \end{itemize} \end{lemma} \begin{proof} As noted in Example~\ref{ex:cl}, $\mathcal O^{\textnormal{cl}}$ satisfies \ref{it:cons}. If $\left< M^\textnormal{cl}, \mathcal I^\textnormal{cl} \right>$ has perfect recall, adding $\mathcal O^{\textnormal{iso}}$ adds no new information at $\mathcal H_i$, so consistency is preserved. \ref{it:sep} holds since $\vec O_i(h)$ ends in an infoset if and only if $h$ belongs to $\mathcal H_i$ (thanks to $\mathcal O^{\textnormal{iso}}$, it ends in an action for $h\notin \mathcal H_i$). \ref{it:iso} trivially holds thanks to $\mathcal O^{\textnormal{iso}}$. To prove \ref{it:stab}, note that stability can only fail if there are two clasical infosets $I\sqsubset J$ of player $i$, such that there is no classical infoset of $i$ between $I$ and $J$, and $i$ receives a different sequence of observations between $I$ and $J$ depending on which path they take. For $\mathcal O^{\textnormal{cl+iso}}$, this can only happen because of $\mathcal O^{\textnormal{iso}}$. Moreover, this can only happen if some path from $I$ leads immediately to $J$, while another path first visits an augmented infoset where $i$ doesn't act. This implies the result since \ref{it:wb} ensures that such a situation cannot occur. \end{proof} \noindent This lemma also serves as a guide for modifying those domains where $\mathcal O^\textnormal{iso+cl}$ would be unstable or inconsistent. Indeed, the obvious way of meeting the assumption \ref{it:wb} is to add a dummy chance node with a single noop action below each player node. However, we typically do not have to go so far, as it suffices to add dummy nodes after those actions in $\mathcal A(I)$ which sometimes lead directly to $\mathcal H_i$ and sometimes not. We believe that Corollary~\ref{cor:impos} is a strong argument\footnote{However, the argument is not decisive since there might still be other ways of modeling observations that avoid this issue.} against the ``no modifying of $M^\textnormal{cl}$'' requirement. We explain that some underlying models weren't constructed with online-play in mind, and thus, one shouldn't expect every such model to be reasonable for modeling real-time decision-making. Luckily, this is not a major limitation, as the modification suggested by Lemma~\ref{lem:consist_domain} makes close to no changes to $\mathcal H$ in typical cases, and doubles the size of $\mathcal H$ in the worst case. The last example of this section is related to the immediate observation property. \begin{example}[Observations are domain specific]\label{ex:obs_are_dom_spec} Whether \ref{it:io} holds depends not only on $\mathcal I^\textnormal{cl}$, but also on the original problem $P$. \end{example} \noindent We have seen that there are domains where $\mathcal O^{\textnormal{iso+cl}}$ satisfies \ref{it:noCH}, \ref{it:cons}, \ref{it:sep}, \ref{it:iso} and \ref{it:stab}. However, it will often fail the more general \ref{it:io} property. Indeed, consider a trivial betting game which starts by the referee randomly drawing and revealing one card (either A or B), then player 1 has one second to decide whether to bet 1 dollar or give up, and then player 2 has an additional one second to decide whether to bet 1 dollar or give up. If the revealed card was A, then player 1 wins all bets. If it was B, then player 2 wins all bets. According to the description above, player two should have two seconds to think -- one during the first player's move, and one during his move. Importantly, he should know the value of the A/B card for the whole period. However, according to $\mathcal O^{\textnormal{iso+cl}}$, he will only have this information for one second, during his turn. However, we could modify the game definition such that player two now has to have his eyes closed until his turn begins. In this case, the classical model of the game would remain the same but $\mathcal O^{\textnormal{iso+cl}}$ would be the correct description of the situation. The takeaway from these two examples is that when defining augmented information sets (or observations) in a specific imperfect information game, one should make design decisions based on the original problem, rather than on its classical model $\left< M^\textnormal{cl}, \mathcal I^\textnormal{cl} \right>$. \subsection{Extending the Classical Model in the Absence of \texorpdfstring{$P$}{P}} \label{sec:ext_cl_model} Sometimes we might want to apply an algorithm such as \cite{CFR-D} or \cite{MCCR} to an imperfect information game for which we only have the classical model $G=\left< M^\textnormal{cl}, \mathcal I^\textnormal{cl} \right>$. To do this, we need to define augmented information sets in $\mathcal H$ that are consistent with $G$. Moreover, in resolving it is cheaper to resolve smaller subgames, so it is desirable to observe as much information as possible (and thus have smaller augmented information sets and public states). While \ref{it:io} is ill-defined in this case (as shown in Example~\ref{ex:obs_are_dom_spec}), it might still be beneficial to have some automatic way of generating augmented information sets that are reasonably small. An easy-to-define candidate are the ``coarse'' augmented information sets corresponding to $\mathcal O^{\textnormal{iso+cl}}$ (first introduced in \cite{CFR-D}\notetoself{Was it there first?}). Unfortunately, $\mathcal O^{\textnormal{iso+cl}}$ fails \ref{it:io} even in the case of perfect information games (Figure~\ref{fig:coarse_infosets_fail_io}), so a different solution is required. A natural approach would be to find the ``most informative'' observations consistent with $\mathcal I^\textnormal{cl}$. However, as shown in Example~\ref{ex:no_finest_partit}, there might be several such observations functions, without a definite candidate for the ``correct'' answer. \begin{figure}[ht] \centering \begin{tikzpicture}[scale=1] \setlength{\nodesize}{2.25em} \ISOfail \end{tikzpicture} \caption{A perfect information game illustrating that the information partitions corresponding to $\mathcal O^\textnormal{iso+cl}$ are sometimes too ``coarse'' to satisfy the immediate observation property \ref{it:io}.} \label{fig:coarse_infosets_fail_io} \end{figure} \begin{example}[No canonical finest partition]\label{ex:no_finest_partit} For some games, there is no single finest partition of $\mathcal H$ satisfying \ref{it:cons}. \end{example} \noindent The games in Figure~\ref{fig:no_finest_partition} illustrate that there doesn't always exist a unique solution to the problem of finding information partitions that are ``maximally informative'' (i.e. anything finer would fail either \ref{it:stab} or \ref{it:cons}). On the left side of Figure~\ref{fig:no_finest_partition}, we see a trivial example of a domain with this property. The domain on the right is a more sophisticated example that shows that sometimes a choice has to be made about which information to reveal. It follows that it is impossible to find a general formula for ``the most informative $\mathcal O$''. \begin{figure} \centering \setlength{\nodesize}{1.5em} \begin{tikzpicture} \noFinestPartitionTrivial \end{tikzpicture} \begin{tikzpicture} \noFinestPartitionTrivial \augInfosetDeprecated(UL,UR) \augInfosetDeprecated(M,BR) \end{tikzpicture} \begin{tikzpicture} \noFinestPartitionTrivial \node(dummy)[missing] at ($(B)!0.5!(B-1)$) {}; \augInfosetDeprecated(UL,dummy) \augInfosetDeprecated(BL,BR) \end{tikzpicture} \begin{tikzpicture} \noFinestPartitionTrivial \node(dummy)[chance] at ($(B)!0.5!(B-1)$) {}; \augInfosetDeprecated(UL,UR) \augInfosetDeprecated(M,dummy) \augInfosetDeprecated(BL,BR) \end{tikzpicture} \hfill \begin{tikzpicture}[scale=1] \noFinestPartitionExample \noFinestPartitionExampleA \end{tikzpicture} \hfill \begin{tikzpicture}[scale=1] \noFinestPartitionExample \noFinestPartitionExampleB \end{tikzpicture} \caption{Domains where the finest partition isn't unique. Classical information sets are solid, the augmented information sets are dashed.} \label{fig:no_finest_partition} \end{figure} This leaves us with three options (of which we prefer the last one). \begin{enumerate} \item Considering \emph{one of} the information partitions that cannot be refined further without failing \ref{it:cons}. In general, finding such a partition might be hard. \item Designing a heuristic that finds some reasonable refinement. This might not be worth spending time on. Note that the "let players know which information sets they might encounter next during their turn" approach is good in perfect information games and simultaneous move games, but fails already in Poker. \item Ignore the problem, arguing that the correct approach is to consider domain-specific observations. \end{enumerate} \section{The Observation-based Model of Imperfect Information}\label{sec:augm_model} In this section, we discuss the role of observation in the absence of the classical model of imperfect information. We formalize the notion of feature-deduction features and discuss stable modifications for general observation-functions. We define the ``official'' version of the proposed observation-based model and prove its basic properties. \subsection{Stability and Deduction from Observations}\label{sec:features} A \emph{feature} in $M$ is any function $f : D \to X$, where $X$ is an arbitrary set and $D =: \textnormal{dom}(f) \subset \mathcal H$ is the domain of $f$. Examples of features are utility $u_i : \mathcal Z \to \mathbb{R}$, the player function $P : \mathcal H \setminus Z \rightarrow \{1,\dots,N,c\}$, the ``Is it my turn?'' function $\mathbf{1}_{\mathcal H_i} : \mathcal H \rightarrow \{0,1\}$, or the list of available actions $h\in \mathcal H \setminus Z \mapsto \mathcal A(h) \subset \mathcal A$. \begin{definition} Let $f$ be a feature in $M$ and $H\subset \mathcal H$. We say that the player $i$ can \emph{deduce from observations $\mathcal O$ the value of $f$ at $H$} if for each $h\in \mathcal H \cap \textnormal{dom}(f)$ the whole $I_i(h) \cap H$ is contained in $\textnormal{dom}(f)$ and we have $f(g)=f(h)$ for each $g \in I_i^{\mathcal O}(h) \cap H$. \end{definition} \noindent For brevity, we will say that ``$i$ can deduce $f$ at $H$'' when the context is clear, and omit the ``at $H$'' part when $H=\mathcal H$. Features allows us to formulate the following characterization of stability: \begin{lemma}[Equivalent formulations of stability]\label{lem:stab} The pair $\left< M, \mathcal O \right>$ satisfies \ref{it:tip} if and only if it satisfies \ref{it:stab}. This is further equivalent the conjunction of \ref{it:wb} and each player $i$ being able to deduce $\mathcal O_i$. \end{lemma} \noindent In particular, if $M$ satisfies \ref{it:wb}, then any $\mathcal O_{\{\}}$ in $M$ satisfies \ref{it:stab}. This isn't the case for $\mathcal O_{()}$: While each player $i$ can, by definition of $\mathcal I^{\mathcal O}$, deduce $\vec{\mathcal O}_{(i)}$, he might not always be able to deduce $\mathcal O_{(i)}$. Apart from the above lemma, this is illustrated by, for example, the sneaking game (Figure~\ref{fig:sneaking_game_modification}). \begin{proof} \ref{it:tip} implies that any two histories in the same infoset have the same observation sequences, which immediately gives \ref{it:stab}. Conversely, the only way the stability condition can fail is when some two histories from the same infoset have different $\vec O_i(\cdot)$-s, which contradicts \ref{it:tip}. Similarly, if \ref{it:tip} doesn't hold, then, for some player $i$, there must exist two different $\vec O_i(\cdot)$-s which, upon transitioning to successor histories, become identical. This can only happen if either $i$ cannot deduce $\mathcal O_i$ at the successor infoset, or if one transition adds an action and the other doesn't -- in other words, if \ref{it:wb} doesn't hold. Conversely, \ref{it:wb} and being able to tell the most-recent observation imply that observation sequences that once diverged will never become the same, which yields \ref{it:tip}. \end{proof} As mentioned above, the obvious solution to the problem of stability is ``just use $\mathcal O_{\{\}}$''. However, there is an alternative solution related to Lemma~\ref{lem:consist_domain}. By adding dummy chance nodes, each domain can be modified in such a way that it satisfies \ref{it:stab} even with $\mathcal O_{()}$. An example of how this can be done in practice is in Figure~\ref{fig:stable_modif}. These nodes can be interpreted as a sequence of auxiliary nodes where the game-engine (or referee) processes the consequences of the latest action and optionally sends elementary observations to players. \begin{figure}[htb] \centering \setlength{\nodesize}{2em} \begin{tikzpicture} \noFinestPartitionGeneral \noFinestPartitionInfosetsA \end{tikzpicture} \begin{tikzpicture} \noFinestPartitionArrow \end{tikzpicture} \begin{tikzpicture} \noFinestPartitionGeneral \noFinestPartitionInfosetsB \end{tikzpicture}\caption{A domain with unstable observations (left) and the corresponding stable modification (right). Maximizer's observations are next to each history.} \label{fig:stable_modif} \end{figure} \begin{lemma}[Stable modification]\label{lem:modif_M} For each $\left< M, \mathcal O \right>$ there exists a modification $\left< \widetilde M, \widetilde{\mathcal O} \right>$ such that the original structure of $\mathcal I^{\mathcal O}$ is preserved, $\widetilde{\mathcal O}_{()}$ satisfies \ref{it:stab}, and we have $|\widetilde{\mathcal H}| \leq |\mathcal H| + |\mathcal H||\mathcal I^{\mathcal O}|$. \end{lemma} \begin{proof}[Proof sketch]\hspace{-0.25em}\footnote{Given our preference to replace EFGs by the model from \cite{FOG}, this proof is only presented as proof sketche, and the properties of the observation-based model in Section~\ref{sec:augm_mod_def} are only formulated as a conjecture.} Note that typically, the increase in size will be much smaller than the worst-case bound. However, the bound is asymptotically tight, as illustrated in Figure~\ref{fig:stable_modif_worst_case}. The idea is that in the most pessimistic scenario, we can split each $h$ that generates, say, an observation $O_i(h) = (a,b,c)$ into nodes $h_1$, $h_2$, $h_3$ with $O_i(h_1) = a$, $O_i(h_2)=b$, $O_i(h_3)=c$. Since the length of observations is independent of the size of $M$, this leads to a potentially unbounded increase in size. However, we can remove those new states $\tilde h$ where $\vec O(\tilde h)$ doesn't correspond to any original observation history $\vec O(h)$, $h\in \mathcal H$ (and there are at most $| \mathcal I(\mathcal O)|$ of those). This proof-sketch can be formalized by embedding $\mathcal H$ into the space of sequences in $\mathbf O$. \end{proof} \begin{figure}[htb] \centering \setlength{\nodesize}{2.25em} \paddingBefore \paddingAfter \caption{A domain with unstable observations (left) where the smallest stable modification (right) increases the size of $M$ from linear ($3N+1$) to quadratic ($N^2 + N +1$). A text next to a node denotes the observation received there.} \label{fig:stable_modif_worst_case} \end{figure} \subsection{The Proposed Definition of the Observation-Based Model}\label{sec:augm_mod_def} \begin{definition}[Observation-based model]\label{def:obs_model} The pair $G = \left< M, \mathcal O \right>$ is said to be an \emph{observation-based model} (of an imperfect information game) if $M$ satisfies \ref{it:wb}, $\mathcal O$ is an observation function in $M$, and each player $i$ can deduce \begin{itemize} \item his own observations \hfill (the observation function ``feature'' $\mathcal O_i : h \mapsto O_i(h)$), \item whether he is the acting player \hfill (the player function $P$ on $\mathcal H_i$ or, equivalently, the feature $\mathbf{1}_{\mathcal H_i}$), \item his own available actions \hfill (the ``feature'' $h\in\mathcal H \mapsto \mathcal A(h) \in \mathcal P(\mathcal A)$ on $\mathcal H_i$), \item whether the game has ended \hfill (the feature $\mathbf{1}_{\mathcal Z}$) \item and his own utility \hfill (the utility function $u_i : \mathcal Z \to \mathbb{R}$). \end{itemize} \end{definition} Whether an observation-based model satisfies \ref{it:io} depends on whether the choice of $\mathcal O$ is suitable for the specific real-life problem $P$ that $\left< M, \mathcal O \right>$ is supposed to model. However, all of the remaining technical desiderata from Section~\ref{sec:observations} are satisfied: \begin{conjecture}[Observation-based model gives a well-defined game]\label{prop:obs_model_is_game} Any observation-based model $\left< M, \mathcal O \right>$ has the following properties, independently of whether the set or sequence approach is adopted: \begin{enumerate}[label=(\roman*)] \item $\left< M, \mathcal O \right>$ satisfies \ref{it:sep}, \ref{it:tip} and \ref{it:stab}; \item $\mathcal O' := \mathcal O + \mathcal O^\textnormal{iso}$ satisfies \ref{it:iso} while being equivalent to $\mathcal O$ (i.e. we have $\mathcal I^{\mathcal O'} = \mathcal I^{\mathcal O}$); \item The definition $\mathcal I'_i := \{ I_i \cap \mathcal H_i \, | \ I_i \in \mathcal I_i^{\mathcal O} \} \setminus \{\emptyset\}$ produces a well-defined classical imperfect information game $\left< M, \mathcal I' \right>$ with perfect recall. Moreover, $\left< M, \mathcal O \right>$ satisfies \ref{it:noCH} and \ref{it:cons} with respect to $\left< M, \mathcal I' \right>$. \end{enumerate} \end{conjecture} As for how an observation-based model can be constructed in practice, consider the following examples: adding ``Your turn!'' to $O_i(h)$ for $h\in \mathcal H_i$ ensures that $i$ can tell whether he is the acting player and adding the pair $(\textnormal{``Your utility''}, \, u_i(z) )$ to $O_i(z)$ for $z\in \mathcal Z$ ensures that $i$ can tell his own utility. As a side effect, this automatically lets the player deduce whether the game has ended. It is not always necessary to specify features explicitly --- since the players have access to $M$, it would suffice to for example add $(\textnormal{``Game ended at terminal node''}, \, z)$ to $O_i(z)$ for $z\in \mathcal Z$, and then $i$ can deduce the necessary utility himself. However, if we want to ensure that a feature $f$ can be deduced at $H\subset \mathcal H$, we can always do the following: \begin{enumerate} \item add the pair $(f,f(h))$ to $O_i(h)$ upon first encountering a node $h$ from $H\cap \textnormal{dom}(f)$, \item add the pair $(f,f(h))$ whenever the current node $h$ belongs to $H\cap \textnormal{dom}(f)$ and $f(h)$ differs from the value last encountered in $H \cap \textnormal{dom}(f)$, and \item not add any ``false'' observations, i.e. if $g\in H$ satisfies $f(h)\neq f(g)$, then $(f,f(h)) \notin O_i(g)$. \end{enumerate} \noindent An alternative is to repeat the observation $(f,f(h))$ for every $h\in H \cap \textnormal{dom}(f)$ (cf. the Frame problem \cite{frameProblem_wiki}). Definition~\ref{def:obs_model} lists some features that players can deduce in every imperfect information game. Actually -- as shown by Remark~\ref{rem:non-ded_feats} -- Definition~\ref{def:obs_model} summarizes \emph{all} of the ``standard''\footnote{The authors realize that ``standard feature'' is not a well-defined notion. We apologize to any reader who finds our list incomplete.} features that the players can be allowed to deduce, because for each standard $f$ not listed in Definition~\ref{def:obs_model}, there is a counterexample domain where players cannot be consistently allowed to deduce $f$. This is, in fact, good news, since our formalism allows us to say, for example, ``consider an observation-based model where each player can deduce X'', and thus elegantly avoid a specific class of pathological domains. \begin{figure}[htb] \centering \begin{tikzpicture} \setlength{\nodesize}{2em} \thickInfosets \end{tikzpicture} \caption{An example of a game where augmented information sets of the maximizer (dashed) necessarily have to be ``thick'' in order to be both stable and consistent with the classical information sets.} \label{fig:thick_infosets} \end{figure} \begin{remark}[Non-deductible features]\label{rem:non-ded_feats} For some classical imperfect information games $\left< M^\textnormal{cl}, \mathcal I^\textnormal{cl} \right>$ there is no observation-based model satisfying \ref{it:noCH} and \ref{it:cons} for which the players can deduce \begin{enumerate}[label=(\roman*)] \item the player function on the whole $\mathcal H \setminus \mathcal Z$ \textnormal{(e.g. when the opponent might, or might not, lose control of his actions and be replaced by chance)}, \item available actions on the whole $\mathcal H \setminus \mathcal Z$, \textnormal{i.e. those of the opponent or chance (e.g. most card games)}, \item history length $|h|$ \textnormal{(e.g. the game from Figure~\ref{fig:thick_infosets} or phantom variants of perfect information games, when the ``illegal move'' observations are private; in such games, information sets not belonging to the acting player might contain some $h$ together with its parent $h'$)}. \end{enumerate} \end{remark} The following example shows a canonical way of extending a classical model into a consistent observation-based model. This approach is domain-agnostic, but this comes at the cost of \ref{it:io}. The new model can be further refined in order to get \ref{it:io}, but such a modification necessarily has to be domain specific (as noted in Example~\ref{ex:obs_are_dom_spec} and \ref{ex:no_finest_partit}). \begin{example}[Coarse observation-based model]\label{ex:coarse_model} For every classical model $\left< M^\textnormal{cl}, \mathcal I^\textnormal{cl} \right>$ of $P$, there exists $\left< M, \mathcal O \right>$ that satisfies \ref{it:cons}, \ref{it:sep}, \ref{it:iso} and \ref{it:stab}, but might fail \ref{it:noCH} and \ref{it:io}. \end{example} \noindent For a fixed $\left< M^\textnormal{cl}, \mathcal I^\textnormal{cl} \right>$, we first construct $M \supset M^\textnormal{cl}$ by adding dummy nodes (chance nodes with a single noop action) after some of the player nodes, in such a way that \ref{it:wb} holds. We then define $O_i(h)$ as the observation that contains the elements enforced by the following conditions, and no others. \begin{itemize} \item $O_i(h) \ni (\textnormal{``Current information set: '', } I) \iff h \in \mathcal I^\textnormal{cl}_i, \ I = \mathcal I^\textnormal{cl}_i(h)$ \item $O_i(h) \ni (\textnormal{``Available actions: '', } \mathcal A(h)) \iff h \in \mathcal H_i$ \item $O_i(h) \ni (\textnormal{``Your last action: '', } a) \iff h = h'a, \ h'\in \mathcal H_i, \ a \in \mathcal A(h')$ \item $O_i(z) \ni (\textnormal{``Game ended. Utility gained: '', } u_i(z)) \iff z \in \mathcal Z$ \end{itemize} With the exception of the ``$i$ can tell $\mathcal O_i$'' condition, it is straightforward to verify that $\left< M, \mathcal O \right>$ satisfies the definition of an observation-based model. The ``$i$ can tell $\mathcal O_i$'' condition follows from \ref{it:wb}. It remains to show that it is consistent with $\left< M^\textnormal{cl}, \mathcal I^\textnormal{cl} \right>$, i.e. that $\mathcal I' = \mathcal I^\textnormal{cl}$. This can be proven along the lines of ``isn't consistent $\implies$ fails \ref{it:wb}''. \section{Background}\label{sec:background} \subsection{The Underlying Model}\label{sec:seq_model} We can use the sequential model of EFGs, where a state in the game is represented by sequences of actions (of the players and -- if present -- chance) that lead to it being reached. The ingredients of such $M = \left< \mathcal A, \mathcal H, N, P, \sigma_c, u \right>$ are the following: \begin{itemize} \item $\mathcal A$ is a finite set of all \emph{actions} available in the game. \item $\mathcal H \subset \left\{ a_1 a_2 \cdots a_n | \ a_i \in \mathcal A, \, n\in \mathbb{N} \cup \{0\} \right\}$ is the set of \emph{histories} legal in the game. We assume that $\mathcal H$ forms a non-empty finite tree\footnote{Recall that in the context of sequences, a tree is a set closed under initial segments, e.g. we have $a_1\cdots a_n \in \mathcal H \implies a_1 \cdots a_k \in \mathcal H$ whenever $k\leq n$.}. \begin{itemize} \item We use $g \sqsubset h$ to denote that $h$ \emph{extends} $g$. This is \emph{not} the strict version of extension, i.e. we have $h\sqsubset h$ for each $h$. \item The \emph{root} of $\mathcal H$ is the empty sequence $\emptyset$. The set of leaves of $\mathcal H$ is denoted $\mathcal Z$ and its elements $z$ are called \emph{terminal histories}. The set of non-leaf elements of $\mathcal H$ are $\mathcal H \setminus \mathcal Z$ and its elements $h$ are called \emph{non-terminal histories}. \item By $\mathcal A(h) := \{ a\in \mathcal A \, | \ ha\in \mathcal H \}$ we denote the set of actions available at $h$. \end{itemize} \item The players in the game are $\{ 1, \dots, N , c\}$, where $c$ denotes the \emph{chance} (sometimes also called \emph{nature}). \item $P : \mathcal H \setminus \mathcal Z \rightarrow \{ 1, \dots, N, c \}$ is the \emph{player function} which controls who acts in a given history. \begin{itemize} \item We use $i$ to denote elements of the player set $\{ 1, \dots, N , c\}$. \item Denoting $\mathcal H_i := \{ h \in \mathcal H \setminus \mathcal Z | \ P(h) = i \}$, we partition the histories as $\mathcal H = \mathcal H_1 \cup \dots \cup \mathcal H_N \cup \mathcal H_c \cup (\mathcal H \setminus \mathcal Z)$. \end{itemize} \item $\sigma_c$ is the \emph{chance strategy} defined on $\mathcal H_c$. For each $h\in \mathcal H_c$, $\sigma_c(h)$ is a probability distribution over $\mathcal A(h)$. \item $u = (u_i)_{i=1}^N$ contains the \emph{utility functions}, where $u_i : \mathcal Z \rightarrow \mathbb{R}$. \end{itemize} The understanding here is that the game starts in the state $h_0 = \emptyset$, then the player $P(h_0)$ picks an action $a_1\in \mathcal A(h_0)$ (or $a_0 \sim \sigma _c(h_0)$ is picked randomly when $P(h_0)=c$), and the game transitions to a new state $h_1 = h_0 a_1$. This continues until the game reaches some terminal state $z = a_0 \cdots a_n$. Once this happens, each player $i \in \{1,\dots,N\}$ receives the reward $u_i(z)$. The goal of each player is to choose actions in a way that maximizes $u_i(z)$. \begin{remark} Modifying EFGs formally is cumbersome. \end{remark} \vspace{-0.5em} \noindent In the underlying model where ``elements of $\mathcal H$ = sequences of actions'', some game-modifying operations are ill-defined or at least cumbersome to do. Examples: a) creating a subgame by replacing the upper part of the tree by a single chance node b) inserting a dummy node. The model that uses an arbitrary set $\mathcal H$ and transition function $\mathcal T : (\mathcal H \setminus \mathcal Z) \times \mathcal A \to \mathcal H$, such as POSG, would be better for this (but perhaps worse for other things). \begin{notation}\label{not:h'} For $\emptyset \neq h \in \mathcal H$ we will use the convention of rewriting $h$ as $h=h'a$, where $h'\in \mathcal H$, $a\in \mathcal A(h')$. \end{notation} \subsection{The Classical Definition of Imperfect Information}\label{sec:imp_inf} The standard way of introducing imperfect information into EFGs is to define (classical) information sets. These group together all the histories that the player cannot tell apart. Formally, a \emph{classical information partition} for player $i$ is any partition of $\mathcal H_i$ s.t. whenever two histories $g,h\in \mathcal H_i$ belong to the same element of the partition, they necessarily have $\mathcal A_i(g) = \mathcal A_i(h)$. \begin{notation} We use $\mathcal I^\textnormal{cl} = \left( \mathcal I^\textnormal{cl}_1, \dots, \mathcal I^\textnormal{cl}_N \right)$ to denote the classical information partitions (i.e. those that are always defined on $\mathcal H_i$ only). For $h\in \mathcal H_i$ we denote by $I_i^\textnormal{cl}(h)$ the element of $\mathcal I_i^\textnormal{cl}$ that contains $h$. \end{notation}
{'timestamp': '2019-06-17T02:17:08', 'yymm': '1906', 'arxiv_id': '1906.06291', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06291'}
arxiv
\section{Introduction} \ignore{ Despite the widespread success of recurrent architectures such as LSTMs \cite{hochreiter_97} in language processing tasks, recent work has highlighted the shortcomings of LSTM language models (LMs) in capturing complex syntactic dependencies \cite{marvin_2018}. To address this problem, injecting syntactic information into language models at training time---with the goal of improving structural generalisation---remains an active area of research. Existing methods largely fall into two categories: (i) \emph{multi-task learning} with syntactic objectives as auxiliary losses \cite{nadejde_2017,enguehard_2017,marvin_2018} and (ii) \emph{syntactic language models} that jointly generate surface strings ($\boldsymbol{x}$) and tree structures ($\boldsymbol{y}$) \cite[\emph{inter alia}]{baker-79,charniak_2001}. } Language models (LMs) based on sequential LSTMs~\citep{hochreiter_97} have numerous practical applications, but it has also been shown that they do not always develop accurate syntactic generalisations~\citep{marvin_2018}. Thus, one strategy for improving LSTMs is to change their biases to facilitate more linguistically valid generalisations. This paper introduces a scalable method for introducing syntactic biases to LSTMs (and indeed, to any left-to-right language model trained with a cross-entropy objective) by distilling knowledge~\citep{bucila:2006,dark_knowledge} from recurrent neural network grammars \cite[RNNGs]{rnng}. RNNGs have been shown to successfully capture non-local syntactic dependencies \cite{kuncoro_2018}, achieve excellent parsing performance \cite{kuncoro-2017,fried_17}, and correlate well with encephalography signals \cite{hale_2018}. Unfortunately, these benefits come at the expense of \emph{scalability}, since the hierarchical constituent composition process (\S\ref{sec:rnng}) within RNNGs means that the structure of the computation graph for a sentence varies according to its tree structure. Even with the help of automatic dynamic batching \cite{dynet,neubig_2017}, RNNGs can be ten times slower to train than a comparable LSTM as they benefit less from specialised hardware like GPUs. As such, RNNGs are an impractical alternative to computationally convenient architectures that are used to build language models from massive corpora~\citep{peters_2018,howard_2018,devlin_2019,radford_2019}. As RNNGs are hard to scale, we instead use the predictions of an RNNG \emph{teacher model} trained on a small training set, to guide the learning of syntactic structure in a sequential LSTM \emph{student model}, which is trained on the training set in its entirety. We denote the resulting lanugage model (i.e., the student LSTM) as a \emph{distilled syntax-aware} LSTM LM (\textbf{DSA-LSTM}). Intuitively, the RNNG teacher is an expert on syntactic generalisation, although it lacks the opportunity to learn the relevant semantic and common-sense knowledge from a large training corpus. By learning from both, the DSA-LSTM therefore learns from a signal that is informative for syntactic generalisation, but without sacrificing the semantic richness contained in a large corpus. Since the DSA-LSTM differs from a conventional LSTM only in its training loss, it has the same hardware-friendly computational structure as a conventional LSTM, and is therefore much faster to train. On targeted syntactic evaluations, it achieves better accuracy than: (i) a strong LSTM LM which, through careful hyperparameter tuning, performs much better than previously thought (\S\ref{sec:replication}); (ii) the teacher RNNG that exploits a hierarchical inductive bias but lacks scalability (\S\ref{sec:rnng}); and (iii) a born-again network \cite{furlanello_18} that similarly learns from KD, albeit without a hierarchical bias from the teacher. We analyse the DSA-LSTM's internal representation through the syntactic probe \cite{shi_16,adi_2017} of \newcite{blevins_2018}, and find that the learned representations encode hierarchical information to a large extent, despite the DSA-LSTM lacking direct access to syntactic annotation. While not directly comparable, on subject-verb agreement both the teacher RNNG and student DSA-LSTM outperform BERT \cite{devlin_2019,goldberg_2019}, which benefits from bidirectional information and is trained on 30 times as much data. Altogether, these findings suggest that structural biases continue to play an important role, even at massive data scales, in improving the linguistic competence of LMs. \section{Replication of Targeted Syntactic Evaluations of LSTM LMs}\label{sec:replication} In this section, we replicate the targeted syntactic evaluations reported by \newcite{marvin_2018}, which assess LMs' ability to assign higher probability in grammatical/ungrammatical minimal pairs within a variety of complex syntactic structures. This will serve as our primary evaluation instrument in this paper. The following example illustrates the \emph{subject-verb agreement across an object relative clause (no complementiser)} construction: \vspace{-2mm} \begin{itemizesquish} \item The farmer the parents love \underline{swims}/$^{*}$\underline{swim}. \end{itemizesquish} \vspace{-2mm} \noindent An LM succeeds on each example iff it assigns a higher probability to the grammatical sentence. \newcite{marvin_2018} report that LSTMs, even with multi-task syntactic supervision, on aggregate still lag far behind human performance \vspace{-2mm} \paragraph{Experimental settings.} Following \newcite{marvin_2018}, we use LSTMs with 650 hidden units trained on the Wikipedia corpus of \newcite{gulordava_18}. Hyperparameters are optimised based on a grid search and can be found in the Appendix. As the targeted syntactic evaluations are based on individual sentences, our LSTM models each sentence separately.\footnote{By modelling each sentence separately, our setup is consistent with that of \newcite{marvin_2018} but differs from those with cross-sentential context \cite{mikolov:2010}.} \vspace{-2mm} \paragraph{Discussion.} We present our findings in Table \ref{tab:replication} ({\bf ``Ours''}); for all our models we report mean and standard deviation of 10 identical models from different random seeds. Our LSTM LM achieves much better perplexity than the LSTM LM (32\% ppl.\ reduction) and even the multi-task LSTM (12\% reduction) of \newcite{marvin_2018}. As our LSTM has the same number of hidden units, we attribute this gap to differences in optimisation and codebases. On aggregate, our LSTM LM outperforms the LSTM multi-task model from \newcite{marvin_2018} that exploits explicit CCG annotations, and is able to match or exceed human performance on 7 out of all 15 constructions, thus confirming earlier findings that neural language models are able to acquire complex syntactic generalisation without explicit syntactic supervision \cite{gulordava_18,goldberg_2019}. Despite the small variance in perplexity (stdev 0.16 ppl.), the trained LMs exhibit large variance in accuracy for some constructions (up to stdev 0.12 for NPI across a relative clause). This observation is consistent with earlier findings that models with similar perplexity may exhibit different patterns of syntactic generalisation \cite{kuncoro_2018,tran_2018}, and serves as a caution against reporting results based on single runs. \begin{table*}[t] \centering \resizebox{\textwidth}{!}{% \begin{tabular}{l|r|r|r||r|r||r} & \multicolumn{2}{c|}{\textbf{Marvin \& Linzen models}} & \multicolumn{1}{c||}{\textbf{Ours}} & \multicolumn{2}{c||}{\textbf{Ours (small training)}} & \\ \hline & \textbf{M\&L-LSTM} & \textbf{M\&L-Multi} & \textbf{Our LSTM} & \textbf{Small LSTM}$^{\dagger}$ & \textbf{RNNG}$^{\dagger}$ & \textbf{Humans} \\ \hline\hline \newcite{gulordava_18} \textbf{test perplexity} & 78.65 & 61.10 & \textbf{53.73} ($\pm$0.16) & 94.54 ($\pm$0.21) & \textbf{92.30} ($\pm$0.27) & N/A \\ \hline \hline \multicolumn{7}{c}{SUBJECT-VERB AGREEMENT} \\ \hline Simple & 0.94 & \textbf{1.00} & \textbf{1.00} ($\pm$0.00) & 0.89 ($\pm$0.03) & \textbf{0.99} ($\pm$0.01) & 0.96 \\ In a sentential complement & \textbf{0.99} & 0.93 & 0.97 ($\pm$0.02) & 0.89 ($\pm$0.01) & \textbf{0.93} ($\pm$0.02) & 0.93 \\ Short VP coordination & 0.90 & 0.90 & \textbf{0.96} ($\pm$0.02) & 0.90 ($\pm$0.03) & \textbf{0.96} ($\pm$0.02) & 0.94 \\ Long VP coordination & 0.61 & 0.81 & \textbf{0.82} ($\pm$0.05) & 0.78 ($\pm$0.03) & \textbf{0.94} ($\pm$0.03) & 0.82 \\ Across a prepositional phrase & 0.57 & 0.69 & \textbf{0.89} ($\pm$0.02) & 0.83 ($\pm$0.02) & \textbf{0.95} ($\pm$0.01) & 0.85 \\ Across a subject relative clause & 0.56 & 0.74 & \textbf{0.87} ($\pm$0.02) & 0.81 ($\pm$0.04) & \textbf{0.95} ($\pm$0.03) & 0.88 \\ Across an object relative clause & 0.50 & 0.57 & \textbf{0.77} ($\pm$0.11) & 0.54 ($\pm$0.08) & \textbf{0.95} ($\pm$0.03) & 0.85 \\ Across an object relative clause (no \emph{that}) & 0.52 & 0.52 & \textbf{0.70} ($\pm$0.05) & 0.55 ($\pm$0.07) & \textbf{0.93} ($\pm$0.02) & 0.82 \\ In an object relative clause & 0.84 & 0.89 & \textbf{0.90} ($\pm$0.03) & 0.79 ($\pm$0.05) & \textbf{0.96} ($\pm$0.01) & 0.78 \\ In an object relative clause (no \emph{that}) & 0.71 & 0.81 & \textbf{0.86} ($\pm$0.05) & 0.72 ($\pm$0.03) & \textbf{0.96} ($\pm$0.02) & 0.79 \\ \hline \textbf{Average of subject-verb agreement} & 0.71 & 0.79 & \textbf{0.87} ($\pm$0.02) & 0.77 ($\pm$0.02) & \textbf{0.95} ($\pm$0.01) & 0.86 \\ \hline \hline \multicolumn{7}{c}{REFLEXIVE ANAPHORA} \\ \hline Simple & 0.83 & 0.86 & \textbf{0.91} ($\pm$0.01) & \textbf{0.93} ($\pm$0.01) & 0.83 ($\pm$0.02) & 0.96 \\ In a sentential complement & \textbf{0.86} & 0.83 & 0.81 ($\pm$0.02) & \textbf{0.77} ($\pm$0.03) & 0.46 ($\pm$0.05) & 0.91 \\ Across a relative clause & 0.55 & 0.56 & \textbf{0.64} ($\pm$0.02) & 0.63 ($\pm$0.02) & \textbf{0.82} ($\pm$0.02) & 0.87 \\ \hline \textbf{Average of reflexive anaphora} & 0.75 & 0.75 & \textbf{0.79} ($\pm$0.01) & \textbf{0.78} ($\pm$0.01) & 0.70 ($\pm$0.02) & 0.91 \\ \hline \hline \multicolumn{7}{c}{NEGATIVE POLARITY ITEMS} \\ \hline Simple & 0.40 & 0.48 & \textbf{0.96} ($\pm$0.04) & \textbf{0.93} ($\pm$0.06) & 0.28 ($\pm$0.05) & 0.98 \\ Across a relative clause & 0.41 & 0.73 & \textbf{0.75} ($\pm$0.12) & \textbf{0.82} ($\pm$0.09) & 0.78 ($\pm$0.06) & 0.81 \\ \hline \textbf{Average of negative polarity items} & 0.41 & 0.61 & \textbf{0.86} ($\pm$0.06) & \textbf{0.88} ($\pm$0.05) & 0.53 ($\pm$0.04) & 0.90 \\ \hline \hline \textbf{Average of all constructions} & 0.68 & 0.75 & \textbf{0.85} ($\pm$0.02) & 0.79 ($\pm$0.02) & \textbf{0.85} ($\pm$0.02) & 0.88 \end{tabular}} \caption{Replication of \newcite{marvin_2018} results. M\&L-Multi is the \newcite{marvin_2018} LSTM trained on LM and CCG supertagging \cite{bangalore_1999,clark-curran-2007-wide} losses with an interpolation factor of 0.5. We report our LSTM LM, small LSTM$^{\dagger}$, and RNNG$^{\dagger}$ performance ($^{\dagger}$smaller training data; \S\ref{sec:rnng}) in the format of \emph{mean ($\pm$standard deviation)} of 10 identical models from different seeds. Results in bold denote the best among models trained on similar amounts of training data } \label{tab:replication} \vspace{-4mm} \end{table*} \vspace{-2mm} \section{Syntactic Evaluation with RNNG}\label{sec:rnng} \vspace{-2mm} \emph{To what extent can a model that leverages syntactic bias and annotation do well on targeted syntactic evaluations, even when trained on less data?} Here we briefly describe and assess the performance of the stack-only RNNG \cite{kuncoro-2017} that we use as the teacher. Our choice of RNNG is motivated by its excellent number agreement performance on the \newcite{linzen-2016} dataset,\footnote{While BERT \cite{devlin_2019} achieves even better number agreement performance \cite{goldberg_2019}, the results are not directly comparable since BERT operates non-incrementally and was trained on 500 times as much data. The current state of the art among models trained on the \newcite{linzen-2016} training set is the adaptive universal transformer model \cite{dehghani_19}.} achieving 92.9\% for four attractors under purely incremental decoding \cite{kuncoro_2018}. \subsection{Recurrent Neural Network Grammars} An RNNG defines the joint probability of surface string $\boldsymbol{x}$ and phrase-structure tree $\boldsymbol{y}$, denoted as $t(\boldsymbol{x}, \boldsymbol{y})$. The model generates phrase-structure trees in a top-down, left-to-right manner through a series of action sequences in a process reminiscent of shift-reduce parsing. At any given state, the decision over which action to take is parameterised by a stack LSTM~\citep{stack_lstm} encoding partially-completed constituents. Let $\mathbf{h}_t$ be the stack LSTM hidden state at time $t$. The next action $a_t \in \{ \textsc{gen}, \textsc{nt}, \textsc{reduce}\}$ is sampled according to a categorical distribution defined by an affine transformation and a softmax \vspace{-2mm} \begin{equation*} a_t \sim \softmax(\mathbf{W_a}\mathbf{h}_t + \mathbf{b_a}). \end{equation*} \vspace{-9mm} \begin{itemizesquish} \item If $a_t \in \{ \textsc{gen}, \textsc{nt}\}$, the model samples a terminal $x$ or a non-terminal $n$ from each respective categorical distribution as the next input: \end{itemizesquish} \vspace{-6mm} \begin{align*} x \sim \softmax(\mathbf{W_x}\mathbf{h}_t + \mathbf{b_x}), \\ n \sim \softmax(\mathbf{W_n}\mathbf{h}_t + \mathbf{b_n}). \end{align*} \vspace{-9mm} \begin{itemizesquish} \item If $a_t = \textsc{reduce}$, the topmost stack elements going back to the last incomplete non-terminal are popped, and a \emph{composition function} (here a bidirectional LSTM) is executed to represent the completed phrase on the stack. This recursive composition function constitutes a primary difference with the syntactic LM of \newcite{choe:2016} that operates sequentially, and has been found to be crucial for achieving good number agreement \cite{kuncoro_2018} and correlation with brain signals \cite{hale_2018}. \end{itemizesquish} \vspace{-3mm} The stack LSTM, composition function, lookup embeddings, and pairs of affine transformation weights and biases $\{\mathbf{W}, \mathbf{b}\}$ are model parameters. \subsection{Experiments} Here we outline the experimental settings and present our RNNG findings. \vspace{-2mm} \paragraph{Experimental settings.} We implement the RNNG with DyNet and enable autobatching on GPU. Predicted phrase-structure trees for the training and validation sets of the \newcite{gulordava_18} Wikipedia dataset are obtained with a pre-trained Berkeley parser \cite{petrov:2007}. Since training the RNNG on the full training set with the same number of hidden units as the LSTM would take more than a month,\footnote{We tested the speed of RNNGs and LSTMs with similar capacity (40 million parameters) on DyNet. Both models ran on a single Quadro P4000 GPU with automatic batching turned on and a batch size of 20 sentences.} we train the RNNG on $\sim20\%$ of the training set (600,000 sentences), and use a smaller hidden state size of 256 (vs. 650 for the full LSTM). As the dataset is pre-processed, we select this subset such that all word types occur at least once in this smaller training set. \vspace{-2mm} \paragraph{Incremental decoding and marginal probability.} To preserve incrementality constraints, at test time we use a word-synchronised beam search \cite{fried_17} with fast-tracking \cite{stern_17}, using word and action beam sizes of $k=50$ and $k \times 10=500$, respectively. As exact inference of $t(\boldsymbol{x})$ is intractable, we evaluate with a lower bound of the marginal probability by summing over the top $k$ hypotheses $\boldsymbol{y}^{b(\boldsymbol{x})}_1, \ldots, \boldsymbol{y}^{b(\boldsymbol{x})}_k$ on the beam $b(\boldsymbol{x})$ once parsing finishes: \vspace{-2mm} \begin{align*} t(\boldsymbol{x}) = \sum_{\boldsymbol{y'} \in \mathcal{T}(\boldsymbol{x})} t(\boldsymbol{x}, \boldsymbol{y'}) \geq \sum_{i=1}^k t(\boldsymbol{x}, \boldsymbol{y}^{b(\boldsymbol{x})}_i), \end{align*} where $\mathcal{T}(\boldsymbol{x})$ denotes the set of all possible phrase-structure trees for a sentence $\boldsymbol{x}$. On targeted syntactic evaluations, the model succeeds iff $\log t(\boldsymbol{x}_{\text{correct}}) > \log t(\boldsymbol{x}_{\text{incorrect}})$. \vspace{-2mm} \paragraph{Discussion.} We present the results in Table \ref{tab:replication} (sixth column: \textbf{``RNNG''}), and compare with LSTMs trained on: (i) the full dataset (fourth column: \textbf{``Our LSTM''}), and (ii) the same (smaller) training set as the RNNG (fifth column: \textbf{``Small LSTM''}). Our findings clearly reaffirm the benefits of \emph{both} hierarchical bias and data scale. In terms of hierarchical bias, an RNNG that leverages syntactic annotations and explicit composition operators outperforms a comparable small LSTM on 11 out of 15 constructions, and on aggregate improves accuracy on targeted syntactic evaluations from 79\% to 85\% (29\% error reduction), thus matching the aggregate performance of the full LSTM trained on 5 times as much data, although we remark that their success and failure modes appear to be different. In terms of data scale, the LSTM LM trained on the full training set substantially outperforms the LSTM trained on the smaller training set. In particular, the performance difference between the small and full LSTMs sheds light on which constructions are sensitive to variations in the amount of data. For instance, agreement across an object relative clause exhibits large variations across the two training regimes (77\% to 54\%), suggesting that LSTMs require a large amount of data to learn these constructions well. Our finding on the importance of data scale for LM training is consistent with the success of recent LM pre-training approaches \cite[\emph{inter alia}]{peters_2018,devlin_2019} and earlier work on noisy channel models for tasks such as machine translation and speech recognition \cite[\emph{inter alia}]{jelinek_1998,rosenfeld_2000,koehn_2010}. Despite its smaller training set, the RNNG performs extremely well on subject-verb agreement, substantially outperforming both the full LSTM and a pre-trained BERT \cite[Table~\ref{tab:dsa-lstm}]{devlin_2019} trained on 150 times as much data, although it still lags behind the full LSTM on reflexive anaphora and NPI. \vspace{-2mm} \section{Syntax-Aware Language Model}\label{sec:synaware} \emph{Given the trade-off between hierarchical operations and scalability, how can we design LMs that can better capture complex syntactic dependencies \textbf{and} be easily scalable at the same time?} \vspace{-2mm} \subsection{Knowledge Distillation (KD)} The goal of KD is to find a set of student model parameters $\hat{\theta}_{\text{KD}}$ that would minimise the Kullback–Leibler (KL) divergence between the teacher RNNG's marginal probability $t(\boldsymbol{x}) = \sum_{\boldsymbol{y'} \in \mathcal{T}(\boldsymbol{x})} t(\boldsymbol{x}, \boldsymbol{y'})$ and the LSTM student $q_{\theta}(\boldsymbol{x})$. Expanding the KL term and removing terms that do not depend on $\theta$ yields: \vspace{-2mm} \begin{align} \hat{\theta}_{\text{KD}} &=\argmin_{\theta} D_{\mathrm{KL}} \left(t(\boldsymbol{x}) \,\,|| \,\, q_{\theta}(\boldsymbol{x}) \right), \\ &= \argmin_{\theta} -\sum_{\boldsymbol{x} \in \Sigma^{\mathbf{*}}} t(\boldsymbol{x}) \log q_{\theta}(\boldsymbol{x}), \label{eq:kd_intractable} \\ &= \argmin_{\theta} - \mathbb{E}_{\boldsymbol{x} \sim t(\boldsymbol{x})} \log q_{\theta}(\boldsymbol{x}), \label{eq:kd_intractable_exp} \end{align} where $\Sigma$ denotes the set of all word types in the vocabulary, and $\Sigma^{\mathbf{*}}$ the set of all possible sentences. As Eq.~\ref{eq:kd_intractable} involves an intractable summation over the set of all possible sentences, one alternative is to approximate this expectation with Monte Carlo sampling to obtain $K$ sentences $D' = \{\boldsymbol{x}'^{(1)}, \ldots, \boldsymbol{x}'^{(K)}\}$ from $t(\boldsymbol{x})$,\footnote{While an RNNG estimates $t(\boldsymbol{x}, \boldsymbol{y})$, a simple way of sampling surface strings $\boldsymbol{x}$ from the RNNG is to sample pairs of $(\boldsymbol{x}^{(k)}, \boldsymbol{y}^{(k)}) \sim t(\boldsymbol{x}, \boldsymbol{y})$ and ignore all non-terminals $\boldsymbol{y}^{(k)}$.} and train a student LSTM LM on these sampled sentences as opposed to ground-truth LM data: \vspace{-3mm} \begin{align*} \mathbb{E}_{\boldsymbol{x} \sim t(\boldsymbol{x})} \log q_{\theta}(\boldsymbol{x}) \approx \dfrac{1}{K} \sum_{\boldsymbol{x}' \in D'} \sum_{j=1}^{|\boldsymbol{x}'|} \log q_{\theta}(x'_j | \boldsymbol{x}'_{<j}), \label{eq:sampling_rnng} \end{align*} although our preliminary experiments suggest that this procedure performs poorly due to high variance.\footnote{This procedure of training a student LSTM LM on string samples from the RNNG with $K \approx 3,000,000$ yields a high validation perplexity of above 1,000, due to the enormity of the sample space and the use of discrete samples.} We instead approximate Eq.~\ref{eq:kd_intractable_exp} by minimising the KL at the \emph{local word-level}: \vspace{-2mm} \begin{align*} &\mathbb{E}_{\boldsymbol{x \sim t(\boldsymbol{x})}} \log q_{\theta}(\boldsymbol{x}) \approx\\ & \mathbb{E}_{\boldsymbol{x^{*}} \sim p^{\mathbf{*}}(\boldsymbol{x})}\, \sum_{j=1}^{|\boldsymbol{x^{\mathbf{*}}}|} D_{\mathrm{KL}} \left( t(w \mid \boldsymbol{x^{\mathbf{*}}}_{<j}) \,\,|| \,\, q_{\theta}(w \mid \boldsymbol{x^{\mathbf{*}}}_{<j}) \right), \end{align*} where $\boldsymbol{x^{\mathbf{*}}}$ is sampled from the empirical distribution $p^{\mathbf{*}}(\boldsymbol{x})$, rather than from the teacher RNNG. Here $t(w \mid \boldsymbol{x^{\mathbf{*}}}_{<j})$ and $q_{\theta}(w \mid \boldsymbol{x^{\mathbf{*}}}_{<j})$ respectively parameterise the (marginal) probability of generating the next-word continuation $w \in \Sigma$, given the ``ground-truth'' conditioning context $\boldsymbol{x^{\mathbf{*}}}_{<j}$, under the teacher and student models. For a dataset of sentences $D = \{\boldsymbol{x^{\mathbf{*}}}^{(1)}, \ldots, \boldsymbol{x^{\mathbf{*}}}^{(|D|)} \}$ characterising the empirical distribution $p^{\mathbf{*}}(\boldsymbol{x^{\mathbf{*}}})=\frac{1}{|D|}$ when $\boldsymbol{x^{\mathbf{*}}} \in D$ (i.i.d. assumption), the word-level objective is: \vspace{-2mm} \begin{align*} &\hat{\theta}_{\text{KD}} \approx \argmin_{\theta} - \dfrac{1}{|D|} \sum_{\boldsymbol{x^{\mathbf{*}}} \in D} \ell_{\text{KD}}(\boldsymbol{x^{\mathbf{*}}}; \theta), \\ &\ell_{\text{KD}}(\boldsymbol{x^{\mathbf{*}}}; \theta) = \sum_{j=1}^{|\boldsymbol{x^{\mathbf{*}}}|} \sum_{w \in \Sigma} t(w \mid \boldsymbol{x^{\mathbf{*}}}_{<j}) \log q_{\theta}(w \mid \boldsymbol{x^{\mathbf{*}}}_{<j}). \end{align*} In earlier work, this local word-level approximation to the KD objective for sequence models has been shown to work surprisingly well in the case of neural machine translation\footnote{While \newcite{seq-distillation} proposed a technique for sequence-level KD for machine translation through beam search, the same technique is not directly applicable to LM, which is an unconditional language generation problem.} \cite{seq-distillation} and language modelling \cite[Born-Again Networks]{furlanello_18}. \vspace{-2mm} \paragraph{Interpolation.} As the teacher RNNG is trained on a smaller training set, the DSA-LSTM should not only aim to emulate the RNNG's predictions and risk being upper-bounded by the teacher's performance, but also learn from the correct next word $x^{*}_j$ to fully exploit scalability.\footnote{Recall that $\ell_{\text{KD}}(\boldsymbol{x}; \theta)$ does not depend on the true next word $x^{*}_j$.} We thus interpolate the distillation (left) and LM (right) losses: \vspace{-5mm} \begin{align*} &\hat{\theta}_{\alpha\text{-int}} = \argmin_{\theta} -\dfrac{1}{|D|} \sum_{\boldsymbol{x^{\mathbf{*}}} \in D} \\ & \left[ \alpha \ell_{\text{KD}}(\boldsymbol{x^{\mathbf{*}}}; \theta) + (1 - \alpha) \sum_{j=1}^{|\boldsymbol{x^{\mathbf{*}}}|} \log q_{\theta}(x^{*}_j \mid \boldsymbol{x^{\mathbf{*}}}_{<j}) \right], \end{align*} where $\alpha$ is the interpolation coefficient. We illustrate the effect of this interpolation in Fig.~\ref{fig:distillation}. Furthermore, computing $\ell_{\text{KD}}(\boldsymbol{x^{\mathbf{*}}}; \theta)$ requires the RNNG's estimate of $t(w\mid\boldsymbol{x^{\mathbf{*}}}_{<j})$, which necessitates an expensive marginalisation over all tree prefixes that generate $w$ conditional on $\boldsymbol{x^{\mathbf{*}}}_{<j}$. For efficiency, we approximate this using the one-best predicted tree from a pre-trained Berkeley parser,\footnote{We use the same pre-trained Berkeley parser to obtain training and validation trees in \S\ref{sec:rnng}.} denoted as $\hat{\boldsymbol{y}}^{\text{berk}}(\boldsymbol{x^{\mathbf{*}}})$, as follows: \vspace{-2mm} \begin{align*} t(w \mid \boldsymbol{x^{\mathbf{*}}}_{<j}) &\approx t(w \mid \boldsymbol{x^{\mathbf{*}}}_{<j},\,\, \hat{\boldsymbol{y}}^{\text{berk}}_{<j}(\boldsymbol{x^{\mathbf{*}}})), \end{align*} where $\hat{\boldsymbol{y}}^{\text{berk}}_{<j}(\boldsymbol{x^{\mathbf{*}}})$ are all the non-terminals in $\hat{\boldsymbol{y}}^{\text{berk}}(\boldsymbol{x^{\mathbf{*}}})$ that occur before $x^{*}_j$. In other words, we first parse the sentence with a Berkeley parser, and use the resulting tree prefix as conditioning context to compute the probability of generating $w \in \Sigma$ under the RNNG. While this means that the teacher's predictions are not derived from a purely incremental process,\footnote{The resulting syntactic prefix $\hat{\boldsymbol{y}}^{\text{berk}}_{<j}(\mathbf{x})$ for approximating $t(w \mid \boldsymbol{x^{\mathbf{*}}}_{<j})$ under the RNNG is obtained from a Berkeley parser that has access to yet unseen words $\boldsymbol{x}_{>j}$.} the student DSA-LSTM still operates strictly incrementally. This interpolated objective is similar to label smoothing \cite{szegedy_2016,pereyra_2017}, with the softmax distribution of the RNNG as the smoothing factor as opposed to the uniform distribution. \begin{figure*}[t] \centering \includegraphics[scale=0.48]{distillation.pdf} \vspace{-2mm} \caption{Example of the KD target (top), the standard LM target (middle), and the interpolated target used to train the DSA-LSTM (bottom) with $\alpha=0.5$, for a prefix (showing only the terminals) \emph{Parts of the river valley}, where the correct continuation is \emph{\underline{have}} due to the plural subject \emph{parts}. \label{fig:distillation} \vspace{-4mm} \end{figure*} \vspace{-2mm} \paragraph{Intuition.} In Fig.~\ref{fig:distillation}, we provide an intuition about why the interpolation of the distillation and LM losses could inject hierarchical bias into a sequential model. We consider the interpolated target with $\alpha=0.5$ for a prefix (suppressing non-terminals) \emph{Parts of the river valley}, where the correct continuation is \emph{have} since the agreement controller \emph{parts} is plural. The standard LM loss is zero only when all word types other than the correct one are assigned zero probability mass, and it is only in expectation (across training contexts) that syntactic regularities are inferred. In contrast, the interpolated target assigns a minimum probability of 0.5 to the correct label, but crucially contains additional information about the \emph{plausibility} of every alternative based on the teacher RNNG's predictions. Under this objective, the plural verbs \emph{are} and \emph{meander} are assigned relatively high probability mass since they fit both the syntactic and semantic constraints (e.g. Parts of the river valley often meander), while the set of singular verbs \emph{has}, \emph{meanders}, and \emph{is} are assigned much lower probability mass since they are syntactically illicit. Thus, as long as the RNNG makes the accurate structural generalisations (and we have shown that it largely does in \S\ref{sec:rnng}), every training instance provides the student LSTM with a wealth of information about all the possible legitimate continuations according to the predictions of the hierarchical teacher, thereby making it easier for the student to learn the appropriate hierarchical constraints and generalisations. \ignore{In contrast, the singular verbs \emph{salutes} and \emph{trains} are assigned low probabilities as they violate the syntactic constraint despite semantic plausibility, while other words such as the adjective \emph{green} are assigned negligible probabilities since they fit neither the syntactic nor semantic constraints. When the teacher model is correct and perfectly confident (i.e. $t(x^{*}_j\mid\boldsymbol{x^{\mathbf{*}}}_{<j}) = 1.0$), the loss reduces to a standard LM loss.} \vspace{-2.5mm} \paragraph{Differences with other KD work.} Our approach departs from the predominant view of distillation primarily as a means of \emph{compressing} knowledge from a bigger teacher or an ensemble to a compact student \cite[\emph{inter alia}]{ba_et_al_14,seq-distillation,liu_2018} in two important ways. First, here the teacher and student models are different in character, and not just in size: we transfer knowledge from a teacher that models the joint probability of strings and phrase-structure trees through hierarchical operations, to a student that only models surface strings through sequential operations. This setup presents an interesting dynamic since the DSA-LSTM has to mimic the predictions of the RNNG, which conditions on syntactic annotation to guide hierarchical operations, even though the DSA-LSTM itself has no direct access to any syntactic annotations at all. Second, distillation thus far has mostly been applied in settings where the teacher and student models are trained on the same data. For scalability reasons, we train the RNNG on a subset of the data, and obtain its soft predictions on the rest. We hypothesise that the predictions of the hierarchical teacher---although they come from a model trained on a smaller dataset---can nevertheless encourage the LSTM to develop structurally sensitive representations of the larger dataset it observes. \vspace{-2.5mm} \paragraph{Born-Again Networks (BA).} In practice, the interpolated distillation objective above can be applied to any teacher and student models. Recently, \newcite{furlanello_18} surprisingly finds perplexity improvement in a \emph{born-again} setup that trains an LSTM LM on the gold data, and then uses the resulting model as a teacher to a student LSTM that shares the same architecture as the teacher. To better understand the importance of learning from a hierarchical teacher (which is not the case in a BA-LSTM since the teacher model is also sequential), we present experiments comparing the DSA-LSTM with a BA-LSTM. \subsection{Experiments} Here we describe our experimental settings and present our findings. \vspace{-2mm} \paragraph{Computational challenge. The KD loss necessitates computing the teacher RNNG's predictive softmax distribution for each token in the training set, but pre-computing these for the \newcite{gulordava_18} training set leads to a prohibitive memory footprint.\footnote{Pre-computing the RNNG's predictions necessitates storing $N \times |\Sigma|$ numbers, where $N$ is the number of tokens. For the \newcite{gulordava_18} training set ($\sim$80M tokens), this requires storing 4 trillion floating points, or 25 terabytes.} To save space, we instead pre-compute the teacher RNNG's hidden state $\mathbf{h}_t \in \mathcal{R}^M$ for every token $x_t$ in the training set ($M \ll |\Sigma|$), and compute the teacher's softmax on-the-fly with an affine transformation and a softmax, which presents minimal computational overhead \vspace{-2.5mm} \paragraph{Experimental settings.} The DSA-LSTM has an identical architecture to the LSTM LM (\S\ref{sec:replication}), although the learning rate is optimised independently (Appendix). We select the final model based on validation LM perplexity, with targeted syntactic evaluations only applied at test time \paragraph{Training speed.} Since the DSA-LSTM operates sequentially, it is amenable to batching operations and is five times faster to train than a comparable RNNG. Despite this significant speed-up, training the DSA-LSTM in our basic implementation is still half as fast as the standard LM objective. We attribute this difference to the additional computational overhead associated with the distillation objective, such as I/O operations and computing the cross-entropy between the teacher and student models for the entire vocabulary. These operations, however, only apply at training time; at test time there is no overhead of inferring $q_{\hat{\theta}_{\alpha\text{-int}}}(\boldsymbol{x})$ under the DSA-LSTM. \paragraph{Baselines.} The DSA-LSTM benefits from three main components: (i) a KD objective, which in itself has been shown to be a good regulariser \cite{furlanello_18}, (ii) the scalability of the sequential architecture, and (iii) a hierarchical bias, which here comes from the teacher RNNG. To understand the benefit of each component, we compare DSA-LSTM with these baselines: \begin{itemizesquish} \item a strong LSTM LM (\S\ref{sec:replication}) that is scalable but lacks a hierarchical bias (\textbf{``Full LSTM''}); \item the teacher RNNG trained on a 20\% subset of the training set (\S\ref{sec:rnng}), which benefits from a hierarchical bias but lacks scalability (\textbf{``RNNG''}); \item a DSA-LSTM trained on the same smaller subset as the teacher RNNG (\textbf{``S-DSA-LSTM''}). This baseline isolates the importance of scalability, since it still benefits from a KD objective and a hierarchical bias from the teacher RNNG; \item a born-again LSTM that benefits from KD and scalability, though it lacks a hierarchical bias due to the sequential teacher (\textbf{``BA-LSTM''}). \end{itemizesquish} \begin{table*}[!htb] \centering \resizebox{\textwidth}{!}{% \begin{tabular}{l|r|r|r||r|r|r||r||r} & \multicolumn{3}{c||}{\textbf{Small Training Set}} & \multicolumn{3}{c||}{\textbf{Full Training Set}} \\ \hline & \textbf{Small LSTM}$^{\dagger}$ & \textbf{S-DSA-LSTM}$^{\dagger}$ & \textbf{RNNG}$^{\dagger}$ & \textbf{Full LSTM} & \textbf{BA-LSTM} & \textbf{DSA-LSTM} &\textbf{BERT} & \textbf{Humans} \\ \hline\hline \newcite{gulordava_18} \textbf{test ppl.} & 94.54 & 93.95 & \textbf{92.30} & \textbf{53.73} & 54.64 & 56.74 & N/A & N/A \\ \hline \hline \multicolumn{9}{c}{SUBJECT-VERB AGREEMENT} \\ \hline Simple & 0.89 & 0.96 & \textbf{0.99} & \textbf{1.00} & \textbf{1.00} & \textbf{1.00} & 1.00 & 0.96 \\ In a sentential complement & 0.89 & \textbf{0.98} & 0.93 & 0.97 & \textbf{0.98} & \textbf{0.98} & 0.83 & 0.93 \\ Short VP coordination & 0.90 & 0.88 & \textbf{0.96} & 0.96 & 0.95 & \textbf{0.99} & 0.89 & 0.94 \\ Long VP coordination & 0.78 & 0.74 & \textbf{0.94} & \textbf{0.82} & 0.80 & 0.80 & 0.98 & 0.82 \\ Across a prepositional phrase & 0.83 & 0.88 & \textbf{0.95} & 0.89 & 0.89 & \textbf{0.91} & 0.85 & 0.85 \\ Across a subject relative clause & 0.81 & 0.87 & \textbf{0.95} & 0.87 & 0.87 & \textbf{0.90} & 0.84 & 0.88 \\ Across an object relative clause & 0.54 & 0.69 & \textbf{0.95} & 0.77 & 0.81 & \textbf{0.84} & 0.89 & 0.85 \\ Across an object relative clause (no \emph{that}) & 0.55 & 0.61 & \textbf{0.93} & 0.70 & 0.74 & \textbf{0.77} & 0.86 & 0.82 \\ In an object relative clause & 0.79 & 0.87 & \textbf{0.96} & 0.90 & 0.91 & \textbf{0.92} & 0.95 & 0.78 \\ In an object relative clause (no \emph{that}) & 0.72 & 0.88 & \textbf{0.96} & 0.86 & 0.83 & \textbf{0.92} & 0.79 & 0.79 \\ \hline \textbf{Average of subject-verb agreement} & 0.77 & 0.84 & \textbf{0.95} & 0.87 & 0.88 & \textbf{0.90} & 0.89 & 0.86 \\ \hline \hline \multicolumn{9}{c}{REFLEXIVE ANAPHORA} \\ \hline Simple & \textbf{0.93} & 0.90 & 0.83 & 0.91 & \textbf{0.92} & 0.91 & 0.94 & 0.96\\ In a sentential complement & 0.77 & \textbf{0.78} & 0.46 & 0.81 & 0.81 & \textbf{0.82} & 0.89 & 0.91 \\ Across a relative clause & 0.63 & 0.67 & \textbf{0.82} & 0.64 & 0.64 & \textbf{0.67} & 0.80 & 0.87 \\ \hline \textbf{Average of reflexive anaphora} & \textbf{0.78} & \textbf{0.78} & 0.70 & 0.79 & 0.79 & \textbf{0.80} & 0.88 & 0.91 \\ \hline \hline \multicolumn{9}{c}{NEGATIVE POLARITY ITEMS} \\ \hline Simple & 0.93 & 0.84 & 0.28 & 0.96 & \textbf{0.98} & 0.94 & N/A & 0.98 \\ Across a relative clause & 0.82 & 0.73 & 0.78 & 0.75 & 0.70 & \textbf{0.91} & N/A & 0.81 \\ \hline \textbf{Average of negative polarity items} & \textbf{0.88} & 0.79 & 0.53 & 0.86 & 0.84 & \textbf{0.92} & N/A & 0.90 \\ \hline \hline \textbf{Average of all constructions} & 0.79 & 0.82 & \textbf{0.85} & 0.85 & 0.86 & \textbf{0.89} & N/A & 0.88 \end{tabular}} \caption{Experimental findings of the \textbf{``DSA-LSTM''}. For each column, we report the mean of 10 identical models trained from different random seeds; standard deviation values are reported in the Appendix. \textbf{``S-DSA-LSTM''} indicates the DSA-LSTM trained on the smaller RNNG training set, while \textbf{``BA-LSTM''} is the born-again model where the teacher is the full LSTM LM. We also compare with the syntactic generalisation of \textbf{``BERT''} Base \cite{devlin_2019,goldberg_2019}, which is not strictly comparable since it is trained on 30 times as much data. $^{\dagger}$ indicates models trained on the smaller 20\% training set (\S\ref{sec:rnng}). Results in bold denote the best among those trained with the same amounts of data.} \label{tab:dsa-lstm} \vspace{-4mm} \end{table*} \vspace{-4mm} \paragraph{Discussion.} To avoid clutter, for each model variant we present only the mean performance of 10 identical models from different random seeds; results with standard deviations are in the Appendix. We present our findings in Table~\ref{tab:dsa-lstm}, based on which we derive several observations. \vspace{-2mm} \begin{itemizesquish} \item Of the three models trained on the small subset, the S-DSA-LSTM outperforms the small LSTM trained on standard LM objective, improving overall acccuracy from 0.79 to 0.82 (14\% error reduction), even though both models share the same architecture and training set size (i.e. only the training objective is different). On subject-verb agreement, the S-DSA-LSTM successfully narrows the gap with the slower teacher RNNG, which benefits from syntactic bias and annotation. These findings confirm our hypothesis that the KD approach constitutes an efficient way to inject hierarchical bias into sequential models. \vspace{-1mm} \item The born-again model (BA-LSTM) outperforms the LSTM LM, albeit by a small margin. This finding suggests that KD helps improve the syntactic competence of LSTMs, even when the teacher model lacks explicit hierarchical bias and shares the same architecture as the student. \vspace{-1mm} \item In terms of perplexity, both BA-LSTM and DSA-LSTM perform slightly worse than the full LSTM LM trained without KD loss. We attribute this gap to the smoother target distribution when using KD, which effectively penalises high probabilities on the correct next word $x^{*}_j$ unless the teacher model is extremely confident. This observation is consistent with earlier findings on label smoothing in machine translation \cite{pereyra_2017,vaswani_2017}, which often results in better BLEU at the expense of slightly worse likelihood. \vspace{-1mm} \item Despite identical architectures, on aggregate the DSA-LSTM substantially improves over the full LSTM (85\% to 89\%), constituting a 27\% error rate reduction and a new state of the art. Our findings suggest that the DSA-LSTM combines the best of both hierarchical bias and data scale: on subject-verb agreement, the DSA-LSTM improves over the LSTM baseline and narrows the gap with the teacher RNNG, while at the same time performing well on reflexive anaphora and NPI, on which the teacher RNNG (but not the full LSTM) fails to achieve a good performance \vspace{-1mm} \item While not directly comparable, the DSA-LSTM outperforms a pre-trained BERT \cite{devlin_2019,goldberg_2019}\footnote{\newcite{goldberg_2019} applies an additional pre-processing step, removing sentences in which the focus verb does not appear as a single word in the word piece-based vocabulary; hence, the evaluation sentences are slightly different.} on subject-verb agreement. Since BERT benefits from bidirectionality and was trained on 30 times as much data as the DSA-LSTM, this finding suggests that, at least in terms of syntactic competence, structural biases continue to be relevant even as the current generation of sequential LMs is able to exploit increasingly large amounts of data. \end{itemizesquish} \vspace{-2mm} \subsection{Probing for Hierarchical Information} Having established the advantages of the DSA-LSTM on targeted syntactic evaluations, we turn to the question of analysing how its internal representation differs from that of a standard LSTM LM. To this end, we adopt the method of \newcite{blevins_2018} and use a probe \cite[\emph{inter alia}]{shi_16,adi_2017,belinkov_2017a,conneau_2018,hewitt_2019} that predicts the \emph{grandparent constituent} of a word token $x_t$, based on its encoding $\mathbf{h}_t$ under the pre-trained LSTM. Under this framework, the accuracy of the probe on a held-out set can be understood as an indication of how well the hidden states encode the relevant syntactic information required to succeed in this task. We use a linear classifier for the probe and obtain the predicted grandparent constituent label using the same pre-trained Berkeley parser (\S3) that we used to obtain predicted phrase-structure trees to train the RNNG. For the probing experiment, we randomly select sentences from each respective training, validation, and test set of the \newcite{gulordava_18} dataset to yield $\sim$300,000 words for training and $\sim$10,000 words for each of validation and test sets. For the probe features, we use a concatenation of the LSTM hidden state at the current and next words,\footnote{Our probing feature set thus slightly differs from that of \newcite{blevins_2018}, who concatenated the hidden states of a left-to-right and right-to-left LSTM language models.} i.e. $[\mathbf{h}_t; \mathbf{h}_{t+1}]$, where $;$ denotes the concatenation operation. Recall that the DSA-LSTM operates only on word sequences and has no access to the Berkeley parse during training. We summarise the probing result in Fig.~\ref{fig:probe}. Overall, the syntactic probing accuracy for the DSA-LSTM is much higher than for the LSTM LM (83\% to 74\%; a 34\% error rate reduction), suggesting that the means by which the DSA-LSTM achieves better syntactic competence is by tracking more hierarchical information during sequential processing. \begin{figure}[t] \centering \includegraphics[scale=0.38]{probe_result.pdf} \vspace{-2mm} \caption{Probing accuracy on the test set. We analyse the hidden states of the LSTM and DSA-LSTM to analyse the structural information encoded in each respective model's hidden state. \label{fig:probe} \vspace{-4mm} \end{figure} \section{Related Work} Augmenting language models with syntactic information and structural inductive bias has been a long-standing area of research. To this end, syntactic language models estimate the joint probability of surface strings and some form of syntactic structure \cite{jurafsky_1995,chelba:2000,roark:2001,henderson:2004,emami:2005,buys:2015a,mirowski_2015,rnng,kim_2019}. In contrast to these approaches, the DSA-LSTM only models the probability of surface strings, albeit with an auxiliary loss that distills the next-word predictive distribution of a syntactic language model. Earlier work has also explored multi-task learning with syntactic objectives as an auxiliary loss in language modelling and machine translation \cite{luong_2016,eriguchi_2016,nadejde_2017,enguehard_2017,aharoni_2017,eriguichi_2017}. Our approach of injecting syntactic bias through a KD objective is orthogonal to this approach, with the primary difference that here the student DSA-LSTM has no direct access to syntactic annotations; it does, however, have access to the teacher RNNG's softmax distribution over the next word. Our approach is also closely related to recent work that introduces structurally-motivated inductive biases into language models. \newcite{chung_2016} segmented the hidden state update of an RNN through a multi-scale hierarchical recurrence, thereby providing a shortcut to the gradient propagation of long-range, hierarchical dependencies. \newcite{yogatama:2018} introduced a stack-structured memory to encourage hierarchical modelling in language models, where the resulting model successfully outperforms standard LSTM variants in number agreement \cite{linzen-2016} evaluation. \newcite{shen_2019} imposed a hierarchical bias on the LSTM cell-updating mechanism, based on the intuition that larger constituents contain information that changes more slowly across the sequence. Our proposed method is orthogonal and can be applied on top of these recent approaches. \ignore{ \begin{abstract} As language exhibits hierarchical structure, we address the problem of designing language models that benefit from hierarchical bias and can capture complex syntactic dependencies to a large extent, albeit without introducing much overhead in terms of scalability. To this end, we employ knowledge distillation (KD) as a means of injecting hierarchical bias from a slow syntactic language model that leverages syntactic information, to a more scalable student LSTM that operates sequentially. While we find that LSTM language models are able to achieve better syntactic generalisation than previously thought, our proposed combination of hierarchical bias and scalability improves over this strong baseline and yields a new state of the art on targeted syntactic evaluations. Analysis suggests that, compared to LSTM language models, our approach has better sample complexity for capturing complex syntactic constructions and encodes hierarchical information to a large extent, despite lacking direct access to syntactic annotation. \end{abstract} } \section{Conclusion} \vspace{-2mm} In this paper, we introduce a distilled syntax-aware LSTM (DSA-LSTM), which combines scalability with structural biases. We achieve this by distilling the predictions about upcoming words in a large training corpus made by a (computationally complex) hierarchical language model trained on a small subset of the data. While we find that LSTM language models achieve better syntactic generalisation than previously thought, on targeted syntactic evaluations our approach improves over this strong baseline, yields a new state of the art, compares favourably to a language model trained on much more data, and results in a language model that encodes hierarchical information to a large extent despite its sequential architecture. Our approach is a general one that can be applied to other student model architectures, such as Transformers \cite{vaswani_2017}. These findings suggest that the question of structural biases continues to be relevant for improving syntactic competence, even in scalable architectures that can benefit from ever-growing amounts of training data. \section*{Acknowledgments} We would like to thank Rebecca Marvin and Tal Linzen for their help in answering questions regarding data preparation. We also thank Dani Yogatama, John Hale, and the three anonymous reviewers for their helpful suggestions.\\
{'timestamp': '2019-06-18T02:03:26', 'yymm': '1906', 'arxiv_id': '1906.06438', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06438'}
arxiv
\section{Inductive Bias} \label{app:ib} As stated in Claim 1, SDA with inductive bias Eq. (\ref{eq:agg_ib}) generalizes many models that have been proposed in the discrete choice literature. Below, we summarize the specific choices of $w$, $r$ and $\mu$ in each paper. \begin{table*}[ht!] \centering \scalebox{1}{ \begin{tabular}{cllll} Type & Extends & $w$ & $r$ & $\mu$ \\ \toprule - & MNL (\cite{mcfadden1973conditional}) & one & zero & identity \\ \midrule \multirow{4}[2]{*}{SDW} & \cite{tversky1969intransitivity} & (max-min)$^\rho$ & zero & identity \\ & \cite{mcfadden1978modeling} & linear & log $\sum$ exp & log \\ & \cite{kalai2002rationalizing} & softmax & zero & identity \\ & \cite{orhun2009optimal} & linear & w. average & kinked lin. \\ \midrule \multirow{3}[2]{*}{SDE} & \cite{kaneko1979nash} & sum & min & log \\ & \cite{kivetz2004alternative} (LAM) & sum & (max+min)/2 & kinked lin. \\ & \cite{kivetz2004alternative} (CCM) & sum & min & power$(\rho)$ \\ \midrule \multirow{1}[2]{*}{SDA} & \cite{kivetz2004alternative} (NCCM) & max-min & min & norm. pow$(\rho)$ \\ & SDA (ours) & set-nn & set-nn & kinked tanh \\ \bottomrule \end{tabular}% }% \label{tbl:gen_agg} \caption{Discrete choice models as set-aggregation models.} \end{table*} As discussed in Sec. \ref{sec:experiments}, we chose our specification of SDA based on set neural networks and a 'kinked' tanh function. In Appendix \ref{app:spec}, we describe each part of our model in further detail. \section{Approximation Error} \label{app:approx} \input{decomp_proof} \section{Estimation Error} \label{app:est} \input{smplcmplx_proof} \section{Experiments} \label{app:experiments} \subsection{Datasets} \label{app:datasets} For Expedia and Outbrain, the preprocessed data used to train the models can be found here\footnote{https://drive.google.com/file/d/1G0Rmsa9M1D5NKbryY4mTmZCX9i6MuY2F/view}. For Amadeus, the data is not publicly available. Please contact the authors of \cite{mottini2017deep} for the data. Note that we did not conduct any feature engineering on Amadeus dataset. Here are the details of the features and the preprocessing steps of each dataset. \begin{enumerate} \item Amadeus: Each item is a recommended flight itinerary, and user clicks one. Key features include flight origin/destination, price and number of transfers. User features are excluded from the original dataset due to privacy concerns. We did not coduct any feature engineering, and used the dataset from \cite{mottini2017deep}. \item Expedia: Each item is a recommended hotel, and user clicks one. Key features include hotel price, rating, length of stay, booking window, user's average past ratings and visitor's location. We applied the following standard preprocessing steps for different variable types: \begin{itemize} \item continuous: depending on the distribution, log or square root transform to make the distribution look Gaussian. \item ordinal: one-hot encode. \item datetime: get week and month to capture seasonality of hotel pricing. \item categorical: one-hot encode. For those with too many categories, group unpopular ones as "others". \item new features: we created one new feature, popularity score, based on a popular blog post on this dataset\footnote{https://ajourneyintodatascience.quora.com/Learning-to-Rank-Personalize-Expedia-Hotel-Searches-ICDM-2013-Feature-Engineering}. \end{itemize} \item Outbrain: Each item is a news article, and user clicks one. When users see an article, they also see these recommended articles at the bottom of the page. Key features include article category, advertiser ID, and geo-location of the views. For preprocessing steps, we followed one of the leading solutions in the Outbrain click preidiction Kaggle competition\footnote{Up to Step 5 of https://github.com/alexeygrigorev/outbrain-click-prediction-kaggle}. \end{enumerate} Table \ref{tbl:data} includes further details. \begin{table}[h!] \centering \fontsize{8.5pt}{10pt}\selectfont \caption{Dataset description} \begin{tabular}{lccccc} Dataset & $m$ & $|{\cal{X}}|$ & $\max(n)$ & $\avg(n)$ & $d$ \\ \midrule Amadeus & 34K & 1.0M & 50 & 32.1 & 17 \\ Expedia & 199K & 129K & 38 & 25 & 8 \\ Outbrain & 16.8M & 478K & 12 & 5.2 & 10 \\ \end{tabular}% \label{tbl:data}% \end{table}% \subsection{Baselines} \label{app:baselines} As shown in Claim \ref{lemma:multiself}, SDA generalizes many known variants of MNL. Our implementation of SDA is capable of running these specific instances of MNL variants. MNL as well as all the models in Figure \ref{fig:extra} (center) are implemented within our framework. \begin{itemize} \item MNL: our implementation. \item SVMRank: used an open source code on GitHub\footnote{https://gist.github.com/coreylynch/4150976/1a2983d3a896f4caba33e1a406a5c48962e606c0}, with minor modifications. \item RankNet: used learning2rank library open sourced on GitHub\footnote{https://github.com/shiba24/learning2rank}. \item MixedMNL: our implementation. \item AdaRank: used an open source code on GitHub\footnote{https://github.com/rueycheng/AdaRank}. \item DeepSets: used source code provided by the authors\footnote{https://github.com/manzilzaheer/DeepSets}. \end{itemize} For neural network based models SDA, RankNet, DeepSets, the number of parameters are $816+784d$, $525312+1024d$, $196864+256d$, respectively, where $d$ is the number of features in a dataset. For a reasonable range of $d$, the number of SDA parameters is significantly lower than that of other models. This further illustrates how SDA reduces model complexity by incorporating inductive bias in clever ways. \subsection{Setup} \label{app:setup} \textbf{Implementation} All code was implemented in Python, using Tensorflow\footnote{\raggedright\url{https://www.tensorflow.org/}}. The source code can be found here\footnote{\raggedright\url{https://drive.google.com/file/d/1KZVbqfVR6QNIpv38y4e8ptzVdbi_GQH4/view}}. \textbf{Evaluation Metrics Definition} \begin{itemize} \item top-1 accuracy: the conventional accuracy. $1$ if the model choice prediction is the same as the chosen item, $0$ otherwise. \item top-5 accuracy: $1$ if the model's 5 highest probability choice predictions include the chosen item, $0$ otherwise. \item mean reciprocal rank (MRR): a rank-based measure commonly used in the information retrieval literature. Let $\text{rank}_i$ to indicate the rank of the chosen item in our prediction (by probability). Then, $\text{MRR} = \frac{1}{m} \sum_{i=1}^m \frac{1}{\text{rank}_i}$. Because we want the rank of the model prediction to be higher (and thus the reciprocal rank to be lower), the lower MRR the better. \end{itemize} \textbf{Hyperparameters} For all methods, we tuned regularization, dropout, and learning rate (when applicable) using Bayesian optimization using an open source library Optuna\footnote{\url{https://optuna.org/}}. We tuned the hyperparameters on the validation set for 100 trials of Bayesian optimization. The range of hyper-parameters considered is as follows: \begin{itemize} \item learning rate: log uniformly sample from 1E-05 \textasciitilde 1E-03 \item weight decay: log uniformly sample from 1E-10 \textasciitilde 1E-03 \item dropout keep probability: uniformly sample from 0.5 \textasciitilde 1.0 \end{itemize} For exponential decay, we used decay rate of 0.95 with decay step of 10 for all models. For batch size, we used 128 for all models. Finally, we applied early stopping to all models based on the validation accuracy with an early stop window of 25 epochs. \textbf{Computing Infrastructure} We optimized the hyperparameters and trained our model on Slurm Worklord Manager\footnote{\url{https://slurm.schedmd.com/documentation.html}}. All the training was done on CPUs, and the CPU core type we used are AMD "Abu Dhabi" and Intel "Broadwell". \subsection{Ablation Study} \label{app:ablation} \textbf{Details on Model Specification} \label{app:spec} Recall that SDA is of the form: $${g}(x,s;w,{\varphi}} %{{\bm{\varphi}}) = \inner{w(s), {\varphi}} %{{\bm{\varphi}}(x,s)}$$ We further introduced the general form of inductive bias: $$w(s) = w({F}} %{{\bm{f}}(s)), \qquad {\varphi}} %{{\bm{\varphi}}(x,s) = {\mu} \big({F}} %{{\bm{f}}(x) - \r({F}} %{{\bm{f}}(s)) \big)$$ In this section, we first elaborate on the different components of ${g}$ to supplement Sec. \ref{sec:model}, then justify our choices of $w$, $r$ and $\mu$ described in Sec. \ref{sec:experiments}. For a single dimension $i \in [\ell]$ in the embedded space, items are first evaluated using some $f_i(x) \in {\cal{F}}$. Then, a ``reference'' valuation is constructed via a set function $r_i(s)$. Next, $r_i(s)$ is subtracted from $f_i(x)$ to ``standardize'' the scores with respect to this reference. As noted in \ref{sec:experiments}, we have found it useful to generalize this by letting $f_i$ and $r_i$ be vector valued, and taking their inner product instead. The item-reference relation is then fed into an a-symmetric non-linearity ${\mu}(\cdotp)$. Finally, all $\ell$ valuations are aggregated using set-dependent weights $w(s)$. Eq. \eqref{eq:agg_ib} injects inductive bias inspired by the following key principles in behavioral choice theory: \begin{enumerate}[label=\textbf{P\arabic*}:,ref=P\arabic*] \setlength\itemsep{0.2em} \item \label{p:nonlin} \textbf{Asymmetry.} Losses and gains are perceived in an a-symmetric, non-linear manner. This is the hallmark of Kahneman and Tversky's Prospect Theory \cite{kahneman1979prospect,tversky1992advances}. \item \label{p:r} \textbf{Relativity.} Valuations are relative, and are considered with respect to a mutual (and possibly hypothetical) referral item (e.g., \cite{tversky1991loss}). \item \label{p:w} \textbf{Integrability.} Subjective value is multi-dimensional, and context determines how valuations are integrated into a single choice (e.g., \cite{tversky1969intransitivity, tversky1993context}). \end{enumerate} \begin{proposition} $g(x,s)$ in Eq. \eqref{eq:agg_ib} satisfies \ref{p:nonlin}, \ref{p:r}, and \ref{p:w}. \end{proposition} To see this, note that for each dimension $i$, item scores $f_i(x)$ are compared to a mutual set-dependent reference point $r_i(s)$ via $d$, satisfying \ref{p:r}. Using a pointwise a-symmetric non-linearity for ${\mu}$ gives \ref{p:nonlin}. Finally, in accordance with \ref{p:w}, valuations are aggregated in ${g}$ via ${w}} %{\bm{{w}}(s)$. We now describe our specific choice of components in Sec. \ref{sec:experiments}. We model $w(s)$ and $r(s)$ as set neural networks \cite{zaheer2017deep}. These are general neural networks whose architecture guarantees permutation invariance, meaning that permuting $s$ will not change the output. For the scalar function ${\mu}$, we have found it useful to use a kinked tanh function: \[ {\mu}(z) = c \tanh(z) \cdotp \one{z<0} + \tanh(z) \cdotp \one{z\ge0}, \quad c>1 \] which is inspired by the s-shaped utility functions used in prospect theory \cite{maggi2004characterization}. Since all four elements of ${g}$ are differentiable, ${g}$ can be optimized over any appropriate loss function (i.e., cross entropy) using standard gradient methods. The learned parameters include the weights in $w$ and in $r$, and $c$ for ${\mu}$. We have noted in Sec. \ref{sec:model} that Eq. \eqref{eq:agg_ib} encompasses several models from the multi-self literature. Since these are usually designed for mathematical tractability, they do not always include explicit functional forms, and use simple non-parametric set operations for $w$ and $r$. The predictive advantage of our parametrized model is demonstrated empirically in Sec. \ref{sec:experiments}. \textbf{Ablation Study} We now investigate the contribution of each component of SDA in an ablation study. In \ref{sec:model}, we motivated our model choice from the behavioral decision theory perspective. To motivate our design decisions also from a machine learning point of view, we conducted an ablation study. In particular, we decomposed SDA into $F$, $\ell$, $w$, $\varphi$ (which can consist of $r$, $\mu$), removed each component, and analyzed the performance. The full set of ablation models is detailed in Table \ref{tbl:ablation_details} and the experimental results are presented in Table 5. The experiment setup is exactly the same as Sec. \ref{sec:experiments}. \begin{table}[h] \centering \caption{Specification of all ablated models} \scalebox{0.9}{ \begin{tabular}{|l|lrllll|} \cline{1-7} & F & \multicolumn{1}{l}{$\ell$} & $w$ & $\varphi$ & r & $\mu$ \bigstrut\\ \hline SDA & linear & 24 & Set NN & $\langle F(x), r(s) \rangle$ & Set NN & kinked tanh \bigstrut[t]\\ SDA with $g=tanh$ & linear & 24 & Set NN & $\langle F(x), r(s) \rangle$ & Set NN & tanh \\ SDA with no $g$ & linear & 24 & Set NN & $\langle F(x), r(s) \rangle$ & Set NN & - \\ SDA with $w$ vector variable & linear & 24 & vector variable & $\langle F(x), r(s) \rangle$ & Set NN & kinked tanh \\ SDE & linear & 24 & vector variable & Set NN & - & kinked tanh \\ SDW & linear & 24 & Set NN & F(x) & - & - \\ MNL with $w$ setnn & linear & 1 & Set NN & F(x) & - & - \\ MNL \cite{mcfadden1973conditional} & linear & 1 & Scalar vector & F(x) & - & - \bigstrut[b]\\ \hline \end{tabular}% } \label{tbl:ablation_details}% \end{table}% \include{ablation_results_table} \subsection{Full Result} \label{app:fulltbl} We ran our experiments for the following number of maximum items: \begin{enumerate} \item Amadeus: 10, 20, 30, 40, 50 \item Expedia: 10, 20, 30, 40 \item Outbrain: 12 \end{enumerate} The result is shown in Table 6. \include{results_table_all} \end{appendices} \section{Conclusions} \label{sec:conclusions} In this paper we proposed a method for accurately predicting choice. Human choice follows complex and intricate patterns, and capturing it requires models that on the one hand are sufficiently expressive, but on the other are specific enough to be learned efficiently. Our goal in this paper was to show that aggregation strikes a good balance between expressivity and specificity, in theory and in practice. Our work is motivated by the growing need for methods that are accurate and scalable. Aggregation is a good candidate for two main reasons. First, aggregation accounts for general violations without imposing any structural assumptions. This is important since accurately predicting choice is likely impossible within the confines of IIA or of targeted forms of violation. Second, it provides a simple template into which differential components can be cast. Aggregators can therefore capitalize on the success of discriminative learning and neural architectures to efficiently optimize predictive accuracy. There are two main avenues in which our work can extend. First, our theoretical results explore the connection between generalization and violation of IIA. We conjecture that this connection runs deeper, and that a properly defined ``violation complexity'' can be useful in giving exact characterizations of learnability. Second, our work focused on a rudimentary choice task: choosing an item from a set. There are, however, many other important choice tasks, such as sequential or subset selection, posing interesting modeling challenges which we leave for future work. \subsection{Definitions and lemmas from \cite{ambrus2015rationalising}} As in many works in economics, \cite{ambrus2015rationalising} use the concept of item \emph{utility functions} $u$, mapping each item to a scalar representing its utility. From our point of view, a score function $f$ correspond to a utility function if it is \emph{fully parameterize}, i.e., has one parameter for every item that represents its utility. We will think of $u$ either as functions $u(x)$ or vectors $u_x$ in appropriate context. We use $\u$ to define a collection of utilities $u_i$ in the same way that ${F}} %{{\bm{f}}$ represents a collections of score functions $f_i$, and accordingly define $g_\u$ as an aggregator of utilities $\u$. It will be useful to notationally differentiate the \emph{aggregation mechanism} ${M}$, which is the functional form defining how individual score functions are combined, from aggregator classes ${\cal{G}}$, which include the actual aggregators (i.e., functions), whose form is given by ${M}$. \begin{definition}[Triple basis, \cite{ambrus2015rationalising}] Let ${M}$ be an aggregation mechanism and $k \in {\cal{N}}$, then $\u = \{u_i\}_{i=1}^k$ with $u_i \in {\mathbb{R}}^3$ is a \emph{\textbf{triple basis}} for $T=(x_1,x_2,x_3)$ under ${M}$ if: \begin{enumerate} \item $g_u(x_1,\{x_1,x_2\}) > g_u(x_2,\{x_1,x_2\})$, and \item $g_u(x,s') = g_u(x',s') \,\, \forall s' \neq \{x_1,x_2\}, x,x' \in s'$. \end{enumerate} \label{def:tb} where $g_\u$ denotes an aggregation with item values given by $\u$. \end{definition} When used in an aggregator, triple bases serve two purposes: they determine the choice from $\{x_1,x_2\}$, but make sure this does not effect choices in other choice sets. Triple bases can be extended to handle \emph{set-triples} $(x,s,t)$, $x \in {\cal{X}}$, $s,t \subseteq {\cal{X}}$ with $x \in s$, where $x$ plays the role of $x_1$, subsets $s' \subseteq s$ the role of $x_2$, and subsets $t' \subseteq t$ the role of $x_3$: the triple bases will choose $x$ from $s'$ (when $x \in s'$) and will be indifferent otherwise. The following excerpt from the main proof of \cite{ambrus2015rationalising} (stated here as a lemma) formalizes this notion. As we now consider multiple items, it will be useful to think of utilities $u$ as mappings from items to scalar utilities, $u:{\cal{X}} \rightarrow {\mathbb{R}}$,\footnote{While $u$ is a mapping of items, for notational clarity we write it as a function of (observed) features.} and we will use both representations of utilities (as vectors and as functions) interchangeably. \begin{lemma}[Triple basis for sets, \cite{ambrus2015rationalising}] Let $\u = \{u_i\}_{i=1}^k$ with utilities $u_i:{\cal{X}}\rightarrow {\mathbb{R}}$, and consider some set-triple $(x,s,t)$ with $x \in {\cal{X}}$, $s,t \subseteq {\cal{X}}$ and $x \in s$. If each $u_i(z)$ is the same for all $z \in s \setminus \{x\}$ and is also the same for all $z \in t$, then if $\u$ is a triple-basis for some $(x_1,x_2,x_3)$, it is also a \emph{set} triple basis for $(x,s,t)$, in the sense that: \begin{enumerate} \item $x$ is chosen from any $s' \subseteq s \cup \{x\}$ with $x \in s'$, and \item $\u$ is indifferent on all other choice sets, i.e., those without $x$ or that include items from $t$. \end{enumerate} \label{lemma:tb_sets} \end{lemma} Triple bases serve as the main building block in \cite{ambrus2015rationalising}. The surprising finding in \cite{ambrus2015rationalising} is that once a triple basis is known for an arbitrary triplet $(x_1,x_2,x_3)$, using Lemma \ref{lemma:tb_sets}, it can be applied to any violating set $s$ by setting $x=y$ and $t={\cal{X}} \setminus s$. Hence, the existence of a triple basis is a property of \emph{the aggregation mechanism}, and not specific to certain items or choice sets (and in our case, to score function classes or the distribution). The authors of \cite{ambrus2015rationalising} provide explicit constructions of triple bases for several aggregation (a.k.a. `multi-self') models from the literature, as well as a general recipe that applies to a large class of aggregation mechanisms that satisfy, in addition to certain natural axioms (e.g., Neutrality and Consistency), the property of \emph{scale invariance}: \begin{definition}[Scale invariance, \cite{ambrus2015rationalising}] An aggregator $g_u$ is scale invariant if there exists an invertible and odd function $\Phi$ such that for every $\alpha>0$, $g_{\alpha u}(x,s) = \Phi(\alpha) g_u(x,s)$ for all $x \in {\cal{X}}, s \in {\mathbb{X}}} % \mathfrak{X$. \label{def:scale_inv} \end{definition} Hence, for any aggregation mechanism that satisfies Def. \ref{def:scale_inv} there exists some triple basis $\u$. Furthermore, the authors show that $\u$ includes at most $k=5$ utilities. Scale invariance simply means that the ranking over items (and hence prediction) induced by the aggregator do not depend on the scale of their internal score functions, and hence, scaling these does not change predictions. Accordingly, and following \cite{ambrus2015rationalising}, our results herein apply to such mechanisms, for which we assume the existence of a corresponding triple basis. The authors of \cite{ambrus2015rationalising} show that all of their results follow through when exact triple bases are replaced with approximate triple basis, where the equalities hold only up to some precision $\epsilon$. This will also be the case in our proof. \subsection{Comparing our setting and results to those of \cite{ambrus2015rationalising}} Before proceeding with our proof, we describe the differences between our result and those of \cite{ambrus2015rationalising}, thus highlighting some of the challenges encountered while proving our result. The setting of \cite{ambrus2015rationalising} differs from ours in three crucial aspects. First, they focus on a realizable setting: they assume the existence of a choice function $c: {\mathbb{X}}} % \mathfrak{X \rightarrow {\cal{X}}$ designating choices $y = c(s) \in s$ for all $s \in {\mathbb{X}}} % \mathfrak{X$, and aim to recover it from the class of all choice functions. We, on the other hand, focus on the agnostic setting, where labels (i.e., choices) $y$ are not necessarily generated from a function within the class we consider (and in fact, can be sampled from an unknown conditional distribution $D_{Y|S}$). Second, \cite{ambrus2015rationalising} provide worst case results for the successful reconstruction of $c$ from any collection of labeled examples. In contrast, we focus on a statistical setting where a sample set of alternatives and choices are drawn from some unknown distribution. We are interested in minimizing the expected loss, i.e., the probability of correctly predicting choice from choice sets drawn from the same distribution. Finally, and perhaps most importantly, \cite{ambrus2015rationalising} assume that all items can be given arbitrary scores (which they refer to as `utilities'). In other words, score functions are fully parameterized and can assign any value to any item. This of course means that the number of parameters required \emph{for each score function} (of which there can be many in the context of aggregation) is equal to the number of items, which in practice can be rather large, and in principle can be unbounded. In contrast, we focus on the parametric settings common in machine learning, where items are described by features (e.g., vectors), and score functions are parametric functions of those features. Critically, without the assumption of full parameterization, the results of \cite{ambrus2015rationalising} break down, as they require the ability to assign arbitrary values to each item. \subsection{Proof of Theorem \ref{thm:err_decomp}} Let ${M}$ be a scale-invariant aggregation mechanism as in \cite{ambrus2015rationalising}, and let $\u$ be a corresponding triple basis of size $k$, which we assume fixed throughout the proof. As noted in Sec. \ref{sec:apx_err}, proof requires that the class of aggregators ${\cal{G}}$ be defined over a class of score functions that is slightly more expressive ${\cal{F}}$, denoted ${{\cal{F}}_+}$. Specifically, ${{\cal{F}}_+}$ includes combinations of pairs of score functions from ${\cal{F}}$, given by ${{\cal{F}}_+} = \{a(b(x), b'(x)) \,:\, a \in {\mathcal{N}}, b,b' \in {{\cal{F}}} \}$ where ${\mathcal{N}}$ is a class of small neural networks (2 inputs, 2 layers with 2 units each, sigmoid activations) whose precise definition will be given in the proof. Note that by construction we will have ${\cal{F}} \subset {{\cal{F}}_+}$. To reduce notational clutter we will use $\err{*}{{\cal{D}}}(\cdot) = \err{*}{}(\cdot)$ for the minimal expected error and $\err{*}{A}(\cdot)=\err{*}{}(\cdot|A)$ for the minimal expected error conditioned on the event $s \in A$. We can now restate a slightly tighter variant of Theorem \ref{thm:err_decomp} in finer detail: \begingroup \def\ref{thm:err_decomp}{\ref{thm:err_decomp}} \begin{theorem} Let ${M}$ be a scale-invariant aggregation mechanism as in \cite{ambrus2015rationalising} with a triple basis $\u$ of size $k$. Let ${\cal{G}} = {\cal{G}}^{(\ell)}_{{\cal{F}}_+}$ be a corresponding class of aggregators of dimension $\ell$ defined over the class of item score functions ${{\cal{F}}_+}$. Then: \begin{equation} \err{*}{{\cal{D}}}({\cal{G}}) \le p_{U}} %{{\Viol_{\varnothing}} \, \err{*}{{U}} %{{\Viol_{\varnothing}}}({{\cal{F}}_+}) + \min_{B \in {{\cal{F}}}^{\ell'}} \sum_{b \in B} p_{{\Delta}_b} \, \err{*}{{\Delta}_b}({{\cal{F}}}) + p_{{V} \setminus {\Delta}_B} \label{eq:err_decomp_appendix} \end{equation} where ${\Delta}_B = \cup_{b \in B} {\Delta}_b$, $\ell' \le (\ell-1)/k$, and $p_A=P(s \in A)$. \end{theorem} \addtocounter{theorem}{-1} \endgroup Before giving the proof, we state a practical corollary of Theorem \ref{thm:err_decomp}. \begin{corollary} Let ${\mathcal{N}}^{N,K}$ be a class of neural networks with $N \ge 2$ fully connected layers with $K \ge 2$ units each and with sigmoidal activations (i.e., multilayer perceptrons). Then if ${\cal{G}}$ is defined over score functions ${\mathcal{N}}^{N,K}$, the bound in Eq. \ref{eq:err_decomp_appendix} holds for ${\cal{F}} = {\mathcal{N}}^{N-2,K/2}$. \end{corollary} The corollary shows how for fully-connected neural networks, the error on each violating region is bounded by the error of slightly less expressive neural networks. The result holds since ${{\cal{F}}_+} \subseteq {\mathcal{N}}^{N,K}$. \begin{proof} We begin with two useful definitions. \begin{definition}[Implementation] Let ${F}} %{{\bm{f}} \in ({{\cal{F}}_+})^k$, then if ${F}} %{{\bm{f}}(x')=\u(x')$ for all items $x'$ appearing in a (set-)triple $T$, we say that ${F}} %{{\bm{f}}$ \emph{\textbf{implements}} $T$. Similarly, if ${F}} %{{\bm{f}}(x') \approx \u(x')$ for all $x'$, we say that ${F}} %{{\bm{f}}$ approximately-implements $T$. \label{def:implement} \end{definition} \begin{definition}[Isolation] Let $s \in {\mathbb{X}}} % \mathfrak{X$, then if ${F}} %{{\bm{f}}$ (approximately) implements the set-triple $(z,s,{\Gamma}(s))$ for some $z \in s$ and for ${\Gamma}(s)={\mathbb{X}}} % \mathfrak{X \setminus s$, we say that ${F}} %{{\bm{f}}$ (approximately) \emph{\textbf{isolates}} $s$. \label{def:isolate} \end{definition} Implementation simply states that the values of items in the triple-basis under ${F}} %{{\bm{f}}$ are (approximately) those under $\u$. Isolation considers the implementation of triple bases for which the choice set is $s$ (but the actual choice $z$ does not matter). As we will see, aggregation will target certain choice sets $s$ by ``isolating'' them from others, letting some of the aggregated score functions effect $s$, but guaranteeing that others are indifferent to it. Note that implementation and isolation, as well as separation (Def. \ref{def:separation}), are inherited properties, i.e., that if they hold for $s$, they also hold for any $s' \subseteq s$. For our next lemma, we will make explicit the class ${\mathcal{N}}$. Each $a \in {\mathcal{N}}$ is a neural networks taking as input vectors of size two and outputing a single scalar. The networks have two fully-connected hidden layers, each with two units, and sigmaoidal activations. The final layer is a 2-to-1 linear layer. We parameterize units using $r(\cdotp;\alpha,\beta)=\inner{\alpha,\cdotp}+\beta$ with $\alpha \in {\mathbb{R}}^2$, $\beta \in {\mathbb{R}}$. and use $\theta \in \Theta$ to denote all of the network's parameters. A network $a \in {\mathcal{N}}$ with parameters $\theta$ is denoted $a_\theta$. We assume w.l.o.g. that sigmoidal activations ${\sigma}$ are scaled to $[0,1]$. Recall that each function ${\bar{f}} \in {{\cal{F}}_+}$ is composed of a pair $b,b' \in {{\cal{F}}}$ whose outputs are combined via some $a \in {\mathcal{N}}$, given by ${\bar{f}}_\theta(x;b,b') = a_\theta(b(x),b'(x))$. We further denote: \[ {F}} %{{\bm{f}}_{\bm{\theta}}(x;b,b') = (f_{\theta_1}(x;b,b'),\dots,f_{\theta_k}(x;b,b')), \quad {\bm{\theta}} = (\theta_1,\dots,\theta_k) \] The next lemma shows how functions in ${{\cal{F}}_+}$ can implement triple bases when separation holds. \begin{figure}[!t] \begin{center} \includegraphics[width=0.8\columnwidth,trim=0 0 4cm 0,clip]{nn_viz} \caption{The auxiliary class ${\mathcal{N}}$} \label{fig:nn_viz} \end{center} \end{figure} \begin{lemma}[Neural implementation of triple bases] Let $T=(x_1,x_2,x_3)$, and let $b,b' \in {{\cal{F}}}$ be such that $b$ separates $x_1,x_2$ from $x_3$ and $b'$ separates $x_1$ from $x_2$, i.e., $\{x_1,x_2\} \succarg{b} x_3$ and $x_1 \succarg{b'} x_2$.\\ Then, there exists ${\bm{\theta}} \in \Theta^k$ for which ${F}} %{{\bm{f}}_{\bm{\theta}}(x;b,b')$ (approximately) implements $T$. \label{lemma:nn_imp_tb} \end{lemma} \begin{proof} We give a general recipe for constructing ${\bm{\theta}}$. Assume w.l.o.g. that ${\sigma}$ maps to $[0,1]$. The idea is to choose $\alpha,\beta$ such that ${\sigma}$ will give items on the r.h.s. and l.h.s. of the separation operator $\succ$ values that are arbitrarily close to 0 and 1, respectively. We now construct each unit of the the neural network (see diagram in Fig. \ref{fig:nn_viz}). \begin{itemize} \item Since $\{x_1,x_2\} \succarg{b} x_3$, there exist $\alpha,\beta$ such that $r((b(x),b'(x));\alpha,\beta) \approx 1$ for $x=x_1,x_2$ and 0 for $x=x_3$. This is because ${\sigma}$ is a sigmoidal, and hence $\alpha$ and $\beta$ simply shift and scale the sigmoid so that the higher-valued $x_1,x_2$ are ``pushed'' towards 1 and the lower-valued $x_3$ towards 0. We denote this unit by $r_1$. \item Since $x_1 \succarg{b'} x_2$, there exist $\alpha,\beta$ such that $r((b(x),b'(x));\alpha,\beta) \approx 1$ for $x=x_1$ and 0 for $x=x_2$. We denote this unit by $r_2$. Note that the values for $x=x_3$ are arbitrary but bounded in $[0,1]$. \item There exist $\alpha,\beta$ such that $r((r_1(x),r_2(x));\alpha,\beta) \approx 1$ for $x=x_1$ and 0 for $x=x_2,x_3$. This is because $r_1$ and $r_2$ contribute 1 to $x_1$, while $x_2$ and $x_3$ never get 1 from $r_1$ and $r_2$. We denote this unit by $r_3$. \item Because ${\sigma}$ is sigmoidal, there exist $\alpha=(\epsilon,0)$ with small enough $\epsilon$ such that with $\beta=0$, $r$ approximates the identity function on the first input.\footnote{ Alternatively, ${\mathcal{N}}$ can be defined with only one unit in the second layer.} We denote this unit by $r_4$. \end{itemize} Note that measuring the outputs of $r_3$ and $r_4$ when plugging $x_1,x_2,x_3$ into $b,b'$ gives: \begin{equation} \label{eq:linear_basis} r_3 \begin{pmatrix} x_1 \\ x_2 \\ x_3 \end{pmatrix} \approx \begin{pmatrix} 1 \\ 0 \\ 0 \end{pmatrix}, \qquad r_4 \begin{pmatrix} x_1 \\ x_2 \\ x_3 \end{pmatrix} \approx \begin{pmatrix} 1 \\ 1 \\ 0 \end{pmatrix} \end{equation} which together with the vector $e=(1,1,1)$, form an (approximate) linear basis for ${\mathbb{R}}^3$. This means that any utility $u_i \in \u$ when applied to $x_1,x_2,x_3$ can be expressed as a linear combination of $r_3,r_4$, and $e$. Specifically, there exist $\alpha, \beta$ such that the linear layer ($r_5$) gives $\inner{\alpha,(r_3(x),r_4(x))}+\beta = u_i(x)$ for all $x \in \{x_1,x_2,x_3\}$. Altogether, we get that there exist $\theta_i$ with $f_{\theta_i}(x;b,b')=u_i$ for all $i$, giving ${\bm{\theta}} = \{\theta_i\}_{i=1}^k$ as required. \end{proof} \begin{corollary} \label{corr:nn_imp_tb_sets} Lemma \ref{lemma:nn_imp_tb} applies to set-triples $(x,s,t)$ when $s \succarg{b} t$ and $x \succarg{b'} s$. \end{corollary} \begin{proof} According to Lemma \ref{lemma:tb_sets}, it suffices to ensure that scores for all $z \in s \setminus \{x\}$ and for all $z' \in t$ are the same. Since the construction in Lemma \ref{lemma:nn_imp_tb} applies to arbitrary separable triples, the above can be achieved by choosing parameters (i.e., scaling and shifting) such that the properties of each $r_i$ hold for all $x \in s,t$. \end{proof} Lemma \ref{lemma:nn_imp_tb} give a ``template'' for generating set-triple bases from a pair of score functions $b,b'$, where $b$ determines the choice set $s$ (by separating $s$ from $t$), and $b'$ determines the choice $x \in s$ (by separating $x$ from $s$). This notion is formalized in the next result relating separation and isolation. \begin{lemma}[Separation entails isolation] If $b$ separates $s$, then for any $b' \in {{\cal{F}}}$, we have that ${F}} %{{\bm{f}}_{\bm{\theta}}(x;b,b')$ isolates $s$. Furthermore, the prediction is determined by $b'$, i.e., \[ h_{g_{_{F}} %{{\bm{f}}}}(s) = \argmax_{x \in s} b'(x) \] \label{lemma:sep2iso} \end{lemma} \begin{proof} Let $z = \argmax_{x \in s} b'(x)$, then instantiate Lemma \ref{lemma:nn_imp_tb} for $b,b'$ on $T=(z,s,{\Gamma}(s))$. \end{proof} Note that ${\bm{\theta}}$ is determined by the aggregation mechanism ${M}$ (this is because $\u$ is determined by ${M}$). Hence, once ${\bm{\theta}}$ is fixed, the triple-basis template is fixed, and learning can focus on targeting choice sets (by optimizing $b$) and predicting within those choice sets (by optimizing $b'$). In the remainder of the we will use ${\bm{\theta}}$ to denote the template parameters corresponding to $\u$ (note that Lemma \ref{lemma:nn_imp_tb} implies that such ${\bm{\theta}}$ exists for any triple basis). Because the approximation in Eq. \eqref{eq:linear_basis} can be made arbitrarily small (i.e., by scaling the appropriate $\alpha$-s), the approximate-indifference of the implemented triple-basis can also be arbitrarily small. Thus, ${\bm{\theta}}$ can be made to give $\epsilon$-approximate indifference for any necessary $\epsilon$. We can now define the following class: \[ \Fplussup{b} = \{ {F}} %{{\bm{f}}_{\bm{\theta}}(x;b,b') \,:\, b' \in {{\cal{F}}} \} \] which includes all score functions that implement set-triple bases that effect choice sets separated by $b$ (while predictions can vary across functions according to $b'$). \begin{corollary} \label{corr:sep_iso_all_F} If $b$ separates $s$, then $s$ is isolated by all ${F}} %{{\bm{f}} \in \Fplussup{b}$. \end{corollary} Isolation will be our main building block for showing error decomposition. For $b \in {{\cal{F}}}$, we denote: \[ {\Lambda}_b = \{s \in {V} \,:\, s \text{ is isolated by all } {F}} %{{\bm{f}} \in \Fplussup{b}\} \] Corollary \ref{corr:sep_iso_all_F} implies that ${\Delta}_b \subseteq {\Lambda}_b$. Note that although each ${F}} %{{\bm{f}}_{\bm{\theta}}(x;b,b')$ includes only two base score functions $b,b' \in {\cal{F}}$, it is in fact composed of $k$ score functions ${F}} %{{\bm{f}}_1,\dots,{F}} %{{\bm{f}}_k \in {{\cal{F}}_+}$, each determined by one of $\theta_1, \dots \theta_k \in {\bm{\theta}}$, or in other words, $\Fplussup{b} \subset ({{\cal{F}}_+})^k$. We denote by ${\cal{G}}_{\Fplussup{b}}$ the class of $k$-dimensional aggregators over $\Fplussup{b}$. The following lemma shows how isolation helps in decomposing the error of ${\cal{G}}$. By ``isolating'' a separable region of ${\mathbb{X}}} % \mathfrak{X$, a budget of $k$ (out of $\ell$) score functions can be allocated to that region, and aggregation will ensure that these score functions will only effect predictions of choice sets within the region. This is the main component in the decomposition bound of the error of ${\cal{G}}$. \begin{lemma}[Decomposition by isolation] For any $R \subseteq {\mathbb{X}}} % \mathfrak{X$ with ${\Lambda}_b \subseteq R$ and any $n \ge k$, it holds that: \begin{equation} \err{*}{R}({\cal{G}}^{(n)}_{{\cal{F}}_+}) \le p_{{\Lambda}_b} \err{*}{{\Lambda}_b}({{\cal{F}}}) + p_{R \setminus {\Lambda}_b} \err{*}{R \setminus {\Lambda}_b}({\cal{G}}^{(n-k)}_{{\cal{F}}_+}) \end{equation} \label{lemma:decomp_via_iso} \end{lemma} \begin{proof} Let ${\cal{G}}' = {\cal{G}}_{\Fplussup{b}} \times {\cal{G}}^{(n-k)}_{{\cal{F}}_+}$, i.e., aggregators whose first $k$ score functions give some ${F}} %{{\bm{f}} \in \Fplussup{b}$. Since ${\cal{G}}' \subseteq {\cal{G}}$, the minimal error cannot decrease: \begin{equation} \err{*}{R}({\cal{G}}^{(n)}_{{\cal{F}}_+}) \le \err{*}{R}({\cal{G}}') \label{eq:decomp_gprime} \end{equation} Next, fix some constant $c$, and denote by $\bar{{\cal{G}}} \subset {\cal{G}}^{(n-k)}_{{\cal{F}}_+}$ the aggregators whose absolute values are at most $c$, and by $\ubar{{\cal{G}}} \subseteq {\cal{G}}_{\Fplussup{b}}$ the aggregators whose absolute values are at least $c$.\footnote{Here we make the technical assumption that ${g}(x,s) \neq 0$ for all $x,s$.} Denoting ${\cal{G}}'' = \ubar{{\cal{G}}} \times \bar{{\cal{G}}}$, because $\bar{{\cal{G}}} \subseteq {\cal{G}}^{(n-k)}_{{\cal{F}}_+}$ and $\ubar{{\cal{G}}} \subseteq {\cal{G}}_{\Fplussup{b}}$, we have: \begin{equation} \err{*}{R}({\cal{G}}') \le \err{*}{R}({\cal{G}}'') \label{eq:decomp_gprimeprime} \end{equation} For any ${g} \in {\cal{G}}''$, since ${g}$ is an aggregator, we can write ${g} = \ubar{{g}} + \bar{{g}}$ where $\ubar{{g}} \in \ubar{{\cal{G}}}$ and $\bar{{g}} \in \bar{{\cal{G}}}$. We now consider how different $s \in R$ are treated by $\ubar{{g}}, \bar{{g}}$, and ${g}$. If $s \in {\Lambda}_b$, then because $\ubar{{g}}(x,s) > \bar{{g}}(x',s)$ for all $x,x' \in s$, $\ubar{{g}}$ `dominates' $\bar{{g}}$ in the sense that only $\ubar{{g}}$ effects predictions, i.e., $h_{g}(s) = h_{\ubar{{g}}}$. On the other hand, if $s \in R \setminus {\Lambda}_b$, then because $\ubar{{g}} \subset {\cal{G}}_{\Fplussup{b}}$, it is approximately-indifferent on $s$ (to see this, note that due to the inheritance of isolation, there is no $t \supset s$ with $t \in {\Lambda}_b$, and so $s$ falls in the second class of sets from Lemma \ref{lemma:tb_sets}). And since this approximate-indifference can be made arbitrarily small (by adjusting ${\bm{\theta}}$ as described above), $\ubar{{g}}$ does not effect predictions, i.e., $h_{g}(s) = h_{\bar{{g}}}$. Overall, for any ${g} \in {\cal{G}}''$, we have: \[ h_{g}(s) = h_{\ubar{{g}}}(s)\one{s \in {\Lambda}_b} + h_{\bar{{g}}}(s)\one{s \in R \setminus {\Lambda}_b} \] This allows us to decompose the error: \begin{equation} \label{eq:decomp_primeprime} \err{*}{R}({\cal{G}}'') \le p_{{\Lambda}_b} \err{*}{{\Lambda}_b}(\ubar{{\cal{G}}}) + p_{R \setminus {\Lambda}_b} \err{*}{R \setminus {\Lambda}_b}(\bar{{\cal{G}}}) \end{equation} and because ${M}$ is scale-invariant (Definition \ref{def:scale_inv}), scaling does not change predictions (and thus does not change the expressivity of the classes), allowing us to remove the constraints on $c$: \begin{equation} \label{eq:decomp_noc} \err{*}{{\Lambda}_b}(\ubar{{\cal{G}}}) = \err{*}{{\Lambda}_b}({\cal{G}}_{\Fplussup{b}}) , \qquad \err{*}{R \setminus {\Lambda}_b}(\bar{{\cal{G}}}) = \err{*}{R \setminus {\Lambda}_b}( {\cal{G}}^{(n-k)}_{{\cal{F}}_+}) \end{equation} Finally, because the predictions of any ${F}} %{{\bm{f}}(x;b,b') \in {\cal{F}}_{\bm{\theta}}(b)$ are determined by $b'$ (Lemma \ref{lemma:sep2iso}), we can replace ${\cal{G}}_{{\cal{F}}_{\bm{\theta}}(b)}$ in Eq. \eqref{eq:decomp_noc} with ${{\cal{F}}}$, and combining Eqs. \eqref{eq:decomp_gprime}-\eqref{eq:decomp_noc} concludes the proof. \end{proof} We now tie all lemmas together to derive Eq. \eqref{eq:err_decomp_appendix}. Recall that $\ell = k \ell' + 1$. For any $B=\{b_1,\dots,b_{\ell'}\}$ with $\cap_{b \in B}{\Lambda}_b = \varnothing$, we can iteratively applying Lemma \ref{lemma:decomp_via_iso} to isolate separable regions until our budget is depleted: \begin{align*} \err{*}{D}({\cal{G}}^{(\ell)}_{{\cal{F}}_+}) & \le p_{{\Lambda}_{b_1}} \err{*}{{\Lambda}_{b_1}}({{\cal{F}}}) + p_{{\mathbb{X}}} % \mathfrak{X \setminus {\Lambda}_{b_1}} \err{*}{{\mathbb{X}}} % \mathfrak{X \setminus {\Lambda}_{b_1}}({\cal{G}}^{(\ell-k)}_{{\cal{F}}_+}) \\ & \le p_{{\Lambda}_{b_1}} \err{*}{{\Lambda}_{b_1}}({{\cal{F}}}) + p_{{\Lambda}_{b_2}} \err{*}{{\Lambda}_{b_2}}({{\cal{F}}}) + p_{{\mathbb{X}}} % \mathfrak{X \setminus {\Lambda}_{b_1} \cup {\Lambda}_{b_2}} \err{*}{{\mathbb{X}}} % \mathfrak{X \setminus {\Lambda}_{b_1} \cup {\Lambda}_{b_2}}({\cal{G}}^{(\ell-2k)}_{{\cal{F}}_+}) \\ & \le \dots \\ &\le \sum_{b \in B} p_{{\Lambda}_b} \err{*}{{\Lambda}_b}({{\cal{F}}}) + p_{{\mathbb{X}}} % \mathfrak{X \setminus {\Lambda}_B} \err{*}{{\mathbb{X}}} % \mathfrak{X \setminus {\Lambda}_B}({\cal{G}}^{(1)}_{{\cal{F}}_+}) \\ &\le \sum_{b \in B} p_{{\Lambda}_b} \err{*}{{\Lambda}_b}({{\cal{F}}}) + p_{{\mathbb{X}}} % \mathfrak{X \setminus {\Lambda}_B} \err{*}{{\mathbb{X}}} % \mathfrak{X \setminus {\Lambda}_B}({{\cal{F}}_+}) \end{align*} where ${\Lambda}_B = \cup_{b \in B} {\Lambda}_b$, and the last inequality is due to ${{\cal{F}}_+} \subseteq {\cal{G}}^{(1)}_{{\cal{F}}_+}$ (note that also ${\cal{F}} \subseteq {{\cal{F}}_+}$, giving the version of the Theorem in the paper). Because the above holds for any $B$, we can plug in the optimal $B$. We now have: \begin{align*} \err{*}{D}({\cal{G}}^{(\ell)}_{{\cal{F}}_+}) & \le \min_{B \in {{\cal{F}}}^{\ell'}} \sum_{b \in B} p_{{\Lambda}_b} \err{*}{{\Lambda}_b}({{\cal{F}}}) + p_{{\mathbb{X}}} % \mathfrak{X \setminus {\Lambda}_B} \err{*}{{\mathbb{X}}} % \mathfrak{X \setminus {\Lambda}_B}({{\cal{F}}_+}) \\ & \le \min_{B \in {{\cal{F}}}^{\ell'}} \sum_{b \in B} p_{{\Lambda}_b} \err{*}{{\Lambda}_b}({{\cal{F}}}) + p_{{V}\setminus {\Lambda}_B} + p_{{U}} %{{\Viol_{\varnothing}}} \err{*}{{U}} %{{\Viol_{\varnothing}}}({{\cal{F}}_+})\\ & \le \min_{B \in {{\cal{F}}}^{\ell'}} \sum_{b \in B} p_{{\Delta}_b} \err{*}{{\Delta}_b}({{\cal{F}}}) + p_{{V}\setminus {\Delta}_B} + p_{{U}} %{{\Viol_{\varnothing}}} \err{*}{{U}} %{{\Viol_{\varnothing}}}({{\cal{F}}_+}) \end{align*} The first inequality holds because isolation is an inherited property, and hence the argmin $B^*$ necessarily has disjoint isolated regions $\{{\Lambda}_b\}_{b\in B^*}$. The second inequality holds because ${\Lambda}_B$ only includes sets in ${V}$, and $\err{*}{{V} \setminus {\Lambda}_B}(\cdot) \le 1$. The third inequality holds since by Lemma \ref{lemma:sep2iso}, separation entails isolations, and so ${\Delta}_b \subseteq {\Lambda}_b$, meaning that sets $s \in {\Lambda}_b \setminus {\Delta}_b$ are assumed to receive the worst-case error of one (i.e., are ``moved'' from the error term $\err{*}{{\Lambda}_b}$ to the maximal-error term $p_{{V} \setminus {\Delta}_b}$), concluding the proof. \end{proof} \section{Experiments} \label{sec:experiments} We now present our experimental evaluation on click prediction tasks on online platforms. \begin{figure}[!t] \begin{center} \includegraphics[width=0.8\columnwidth,trim=4cm 0 0 0,clip]{sda_new3_cropped} \caption{The proposed aggregation model} \label{fig:diagram} \end{center} \end{figure} \textbf{Datasets.} We evaluate our method on three large datasets: flight itineraries from Amadeus\footnote{See \cite{mottini2017deep}}, hotel reservations from Expedia\footnote{\raggedright\url{www.kaggle.com/c/expedia-personalized-sort}}, and news recommendations from Outbrain\footnote{\raggedright\url{www.kaggle.com/c/outbrain-click-prediction}}. Each dataset includes sets of alternatives and the corresponding user choices. We focus on examples where users clicked on exactly one item. Features describe items (e.g., price, quality, or category) and context (e.g., query, date and time). Unfortunately, for reasons of privacy, very little user information is available. Appendix \ref{app:datasets} includes further details. \textbf{Baselines.} We compare against three baseline categories: methods that satisfy IIA, methods that target specific violations of IIA, and methods that do not satisfy IIA but also do not directly model violations. This lets us explore whether capturing IIA violations is useful, and if so, what form of deviation is preferable. We focus on approaches that can be applied to large-scale data as the above. For IIA methods, we use Multinomial Logit (MNL) \cite{mcfadden1973conditional,train2009discrete}, SVMRank \cite{joachims2006training}, and RankNet \cite{burges2005learning}. These methods predict based on item-centric score functions, but differ in the way they are optimized. For non-IIA methods, we use a discrete Mixed MNL model \cite{train2009discrete}, AdaRank \cite{adarank}, and Deep Sets \cite{zaheer2017deep}. These differ in how they consider item dependencies: Mixed MNL models user populations, ListNet captures set dependencies via the loss function, and Deep Sets attempts to universally approximate general set functions. We also compare to simple baselines based on price or quality, and to random. \textbf{Aggregation models.} For our approach, we evaluate the performance of three models, each corresponding to one of the aggregation mechanisms from Sec. \ref{sec:model}.\\ \vspace{0.1cm} \storestyleof{itemize} \begin{listliketab} \begin{tabular}{Llll} \textbullet & \textbf{Set-dependent weights}: & ${g}(x,s) = \inner{w(s), {F}} %{{\bm{f}}(x)}$ & [{SDW}} %{{SDA$_w$}, Eq. \eqref{eq:agg_w}] \\ \textbullet & \textbf{Set-dependent embeddings}: & ${g}(x,s) = \inner{v, {\varphi}} %{{\bm{\varphi}}(x,s)}$ & [{SDE}} %{{SDA$_\feat$}, Eq. \eqref{eq:agg_emb}] \\ \textbullet & \textbf{Combined inductive bias model}:& ${g}(x,s) = \inner{w(s), {\varphi}} %{{\bm{\varphi}}(x,s)}$ & [{SDA}, Eq. \eqref{eq:agg_comb}] \end{tabular} \end{listliketab} \vspace{-0.4cm} The set function $w$ is implemented by a small permutation-invariant neural network \cite{zaheer2017deep} having 2 hidden layers of size 16 with tanh activations and use mean pooling. In the combined model, we use a slight generalization of Eq. \eqref{eq:agg_comb}, letting ${\varphi}} %{{\bm{\varphi}}(x,s)={\mu} (\inner{{F}} %{{\bm{f}}(x),\r(s)} )$ where ${F}} %{{\bm{f}}$ and $r$ are now vector-valued, and are compared by an inner product. For the a-symmetric sigmoidal ${\mu}$ we use a `kinked' tanh, and $r$ has the same architecture as $w$ but outputs a vector. Figure \ref{fig:diagram} illustrates this architecture. As noted, these design choices follow key principles from behavioral choice theory. Appendix \ref{app:ablation} includes further details and ablation studies. To highlight the contribution of aggregation, for all models we use a simple linear base class ${\cal{F}}$, allowing a clean differential comparison to IIA methods such as MNL (linear score functions, no set operations) and to non-IIA methods such as DeepSets (neural set functions, no linear components). Our main results use $\ell=24$, which strikes a good balance between performance and runtime (in general, accuracy increases with $\ell$, but most of the gain is already reached at $\ell=4$; see Fig. \ref{fig:extra} left). \textbf{Setup.} Results are based on averaging 10 random 50:25:25 train-validation-test splits. The methods we consider are varied in their expressive power and computational requirements. Hence, for a fair comparison (and to allow reasonable run times), each trial includes 10,000 randomly sampled examples. Performance is measured using top-1 accuracy, top-5 accuracy, and mean reciprocal rank (MRR). For all methods we tuned regularization, dropout, and learning rate (when applicable) using Bayesian optimization. Default parameters were used for other hyper-parameters. For optimization we used Adam with step-wise exponential decay. See Appendix \ref{app:setup} for further details. \input{results_table} \subsection{Results} Our main results are presented in Table 1, which compares the different methods for choice sets up to 10, 10, 12 items for each dataset (the full results for a range of maximal number of items can be found in Appendix \ref{app:fulltbl}). As can bee seen, SDA outperforms other baselines in all settings. When comparing predictive top-1 accuracy, non-IIA methods tend to outperform IIA methods by a margin. Discrete Mixed MNL, which deviates from IIA by targeting certain inter-item dependencies, is observed as the most competitive baseline. DeepSets, which is our most general non-IIA baseline, shows mixed results, and relatively high standard errors. Deepsets portrays the invariances required for expressing violations with significantly more parameters than SDA (Appendix \ref{app:baselines}), but lacks the inductive bias that SDA holds, thus demonstrating the importance of the latter. For measures that extend beyond the first item (such as top-5 and MRR), IIA ranking methods perform well, likely because their objective consider relations between items. Nonetheless, they are still outperformed by SDA, even though its objective considers only the top item. We conjecture that training SDA with a ranking loss will increase performance further. \subsection{Analysis} \textbf{Accuracy and violation capacity}. Figure \ref{fig:extra} (left) presents the accuracy of an aggregator for increasing $\ell$. Results show that accuracy steadily increases, although roughly $90\%$ of the gain is accuracy is achieved by $\ell=4$. Theorem \ref{thm:err_decomp} suggests that increasing $\ell$ helps by covering additional regions of violating sets. To empirically quantify this, we measure \emph{violation capacity}: \begin{equation} {\kappa}_{\S}({g}) = \frac{1}{|{\S}|}\sum_{(s,y) \in {\S}} \frac{1}{|s|-1} \sum_{y \neq x \in s} \1{g(x,s_{-x}) \neq y} \label{eq:violation_capacity} \end{equation} where $s_{-x} = s \setminus \{x\}$. Violation capacity measures how frequently the prediction changes when single items are removed from the choice set, and is a first-order approximation of the violation frequency captured by a model. Figure \ref{fig:extra} (left) reveals a tight correlation between accuracy and ${\kappa}$. \textbf{Violation budget allocation}. The decomposition in Theorem \ref{thm:err_decomp} shows how aggregation allocates one score function to cover all non-violating sets ${U}} %{{\Viol_{\varnothing}}$, and uses the remaining $\ell-1$ score functions for targeting and handling violating regions. Empirically, this suggests that ${\kappa}$ should vary across choice sets: high ${\kappa}$ for targeted violating regions, low ${\kappa}$ for ${U}} %{{\Viol_{\varnothing}}$ and all other regions. Figure \ref{fig:extra} (right) compares the violation capacity of {SDA}\, MNL, and Deep Sets. For each method, the diagram shows average ${\kappa}$ values partitioned according to intersecting correctness regions (i.e., examples that only {SDA}\ was correct on, examples that {SDA}\ and MNL were correct on but not Deep Sets, etc.). The results highlight how {SDA}\ efficiently allocates its violation budget, executing very little violation capacity on examples that MNL is correct on, and allocating the minimally necessary amount to the rest. In contrast, MNL hos no violation capacity (as it cannot express violations), and Deep Sets over-utilizes its unconstrained capacity to violate. \textbf{Comparing aggregators} Claim \ref{lemma:multiself} states that {SDA}\ generalizes many aggregation models from the literature, and by preserving their structural form (i.e., Eq. \eqref{eq:agg_ib}), introduces useful inductive bias. Figure \ref{fig:extra} (center) compares the performance of {SDA}\ to the models from Claim \ref{lemma:multiself} on Amadeus. As can be seen, {SDA}\ clearly outperforms other models. Many of these models were designed for mathematical or behavioral tractability, having simple components with light parameterization. These results demonstrate the benefit of replacing these with highly flexible parametric neural components. \begin{figure*}[t!] \centering \includegraphics[width=0.30\columnwidth]{acc_and_rmv1_v2} \hspace{0.22cm} \includegraphics[width=0.33\columnwidth]{agg_vs_ms_v2} \hspace{0.22cm} \includegraphics[width=0.31\columnwidth]{pred_compare_v3} \caption{\textbf{Left}: Accuracy (blue) and violation c apacity ${\kappa}$ (red) are highly correlated. Most of the accuracy gain is achieved by $\ell=4$. \textbf{Center}: Accuracy of SDA vs. the choice models it generalizes (Claim \ref{lemma:multiself}), showing the benefit of replacing hand-crafted elements with neural components. \blue{\textbf{Right}: MNL and Deep Sets represent two extremes: inability to express violations (${\kappa}=0$, dark blue), and over-flexibility (${\kappa}=1$, dark red). SDA finds middle ground by properly allocating its violation `budget', focusing mostly on samples that MNL gets wrong (mean ${\kappa}$ in light red).} } \label{fig:extra} \end{figure*} \section{Introduction} \label{sec:intro} One of the most prevalent activities of online users is \emph{choosing}. In almost any online platform, users constantly face choices: what to purchase, who to follow, where to dine, what to watch, and even simply where to click. As the prominence of online services becomes ever more reliant on such choices, the accurate prediction of choice is quickly becoming vital to their success. The availability of large-scale choice data has spurred hopes of feasible individual-level prediction, and many recent works have been devoted to the modeling and prediction of choice \cite{benson2016relevance, ragain2016pairwise, kleinberg2017comparison, kleinberg2017human, mottini2017deep, shah2017simple, negahban2018learning, chierichetti2018learning, overgoor2018choosing}. In a typical choice scenario, a user is presented with a set of items $s=\{x_1,\dots,x_k\}$, $x_i \in {\cal{X}}$, called the \emph{choice set}. Of these, the user chooses an item $y \in s$. In economics this is known as the problem of \emph{discrete choice} \cite{luce1959individual}. We let the collection of choice sets ${\mathbb{X}}} % \mathfrak{X$ include all sets of at most $n$ items, ${\mathbb{X}}} % \mathfrak{X = \cup_{k \le n} {\cal{X}}^k$, and assume choice sets and choices are drawn i.i.d. from an unknown joint distribution ${\cal{D}}$. Given a set of $m$ examples ${\S}=\{ (s_i,y_i) \}_{i=1}^m$ sampled from ${\cal{D}}$, our goal is to learn a choice predictor ${\hat{y}} = h(s)$ that generalizes well to unseen sets, i.e., has low expected error w.r.t. ${D}$. A natural way to predict choice is to learn a score function $f(x)$ over items. If $f$ learns to score chosen items higher than their alternatives, then the argmax rule $h_f(s) = \argmax_{x \in s} P_f(x|s)$ where $P_f(x|s) \propto e^{f(x)}$ will lead to good predictions. This approach may seem appealing, but is in fact constrained by an undesired artifact known as the \emph{Independence of Irrelevant Alternatives} (IIA) \cite{luce1959individual}: \begin{definition} \label{def:iia} For any $s \in {\mathbb{X}}} % \mathfrak{X$ and $a,b \in s$, \textbf{IIA} holds if $P(a|\{a,b\}) / P(b|\{a,b\}) = P(a|s) / P(b|s)$. \end{definition} IIA states that the likelihood of choosing $a$ over $b$ should not depend on what other alternatives are available. This means that for any choice set $s$, if $y \in s$ is predicted for $s$, then $y$ will also be predicted out of any subset of items $s' \subset s$ in which $y$ is included . IIA is a rigid constraint that imposes a fundamental limitation on what choice behavior can be expressed, and cannot be mitigated by simply increasing score function complexity (e.g., adding layers or clever non-linearities). From a practical point of view, this is discouraging, as there is ample empirical evidence of regular and consistent violations of IIA in real choice data (e.g., \cite{rieskamp2006extending}). This has led to a surge of interest in machine learning models that go beyond IIA \cite{oh2014learning, osogami2014restricted, benson2016relevance, ragain2016pairwise, otsuka2016deep, ragain2018choosing, chierichetti2018learning, seshadri2019discovering, pfannschmidt2019learning}. The {na\"{\i}ve}\ way to avoid IIA is to directly model all possible subsets, but this is likely to make learning intractable \cite{mcfadden1977application, seshadri2019discovering}. A common approach for resolving this difficulty is to impose structure, typically in the form of a probabilistic choice model encoding certain inter-item dependencies. While allowing for violations, this approach presents several practical limitations: First, explicitly modeling the dependency structure restricts \emph{how} IIA can be violated. Second, as these methods focus mostly on asymptotic properties (e.g., consistency) rather than on finite-sample expected accuracy, they may not perform well in practice. Finally, surprisingly few of these methods apply to large-scale online choice data, where the number of instances can be prohibitively large, choice sets rarely appear more than once, and items can be complex structured objects whose number is virtually unbounded. To complement most current works, and motivated by the growing need for accuracy and scalability, here we propose a framework for choice prediction that is \emph{purely discriminative}, and hence directly optimizes for accuracy. Our framework is based on the idea of \emph{set-dependent aggregation}, a principled approach in economics for modeling IIA violations \cite{ambrus2015rationalising}, that to the best of our knowledge has not been considered from a machine learning perspective. The challenge in designing a useful discriminative choice framework that supports violations is twofold. On the one hand, it must be general enough to allow for IIA violations \emph{without} explicitly modeling how they can occur. On the other hand, it must be specific enough to efficiently capture actual behavioral violations emerging form the data. In this paper, we show that set-dependent aggregation achieves both. Specifically, our framework makes the following contributions: \begin{itemize} \item \textbf{Efficient and scalable discriminative training.} Our approach is geared towards predictive performance: it directly optimizes for accuracy, can be efficiently trained end-to-end, and scales well to realistically large and complex prediction scenarios. \item \textbf{Rigorous error bounds.} We bound both approximation and estimation error of aggregation. Our results show how the complexity of the hypothesis class controls the \emph{type} and \emph{number} of accountable violations, uncovering a data-driven mechanism for targeting important violations. \item \textbf{Behavioral inductive bias.} Aggregation can provably express \emph{any} form of violation \cite{ambrus2015rationalising}, but may require an intractable number of parameters to do so. To control for overfitting, we infuse our model with inductive bias taken from behavioral decision theory, balancing flexibility and specificity without imposing any explicit structure. \item \textbf{Thorough empirical evaluation.} We conduct experiments on three large choice datasets ---flight itineraries, hotel reservations, and news recommendations--- demonstrating the utility of our approach. Our analysis reveals how accuracy is driven by the flexibility in modeling violations, which resonates well with our theoretical results. \end{itemize} Overall, our work presents a practical and theoretically-grounded approach for predicting choice.\\ \textbf{Paper organization.} We begin with a review of the related literature (Sec. \ref{sec:related}). We then present our model of set-dependent aggregation in Sec. \ref{sec:model}. This is followed in Sec. \ref{sec:theory} by our main theoretical results, bounding the approximation error (Sec. \ref{sec:apx_err}) and estimation error (Sec. \ref{sec:est_err}) of aggregators. Finally, we present our experimental results in Sec. \ref{sec:experiments}, and give concluding remarks in Sec. \ref{sec:conclusions}. \input{related} \section{Predicting Choice} \label{sec:pred_choice} \section{Proposed Model} \label{sec:model} \begin{figure}[!t] \centering \begin{subfigure}[b]{0.32\linewidth} \centering\includegraphics[width=1\linewidth]{viol_viz4_a} \caption{\textbf{Linear}: $\inner{v,{F}} %{{\bm{f}}(x)}$ \label{fig:viol_viz_lin}} \end{subfigure} \,\, \begin{subfigure}[b]{0.32\linewidth} \centering\includegraphics[width=1\linewidth]{viol_viz4_b} \caption{\textbf{{SDW}} %{{SDA$_w$}}: $\inner{w(s),{F}} %{{\bm{f}}(x)}$ \label{fig:viol_viz_sdw}} \end{subfigure} \,\, \begin{subfigure}[b]{0.32\linewidth} \centering\includegraphics[width=1\linewidth]{viol_viz4_c} \caption{\textbf{{SDE}} %{{SDA$_\feat$}}: $\inner{v,{\varphi}} %{{\bm{\varphi}}(x,s)}$ \label{fig:viol_viz_sde}} \end{subfigure}% \caption{An illustration of how set-dependent aggregation can violate IIA. Points represent an embedding of items in ${\mathbb{R}}^\ell$ with $\ell=2$. Two sets are shown: $s$ and $s' = s \setminus \{x\}$ for some $x \in s$. IIA dictates that removing $x$ from $s$ does not change the prediction ${\hat{y}}$. This is the case for linear aggregation (\subref{fig:viol_viz_lin}), where neither weights $v \in {\mathbb{R}}^\ell$ or embedding mapping ${\varphi}} %{{\bm{\varphi}}$ depend on the set. When weights ${w}} %{\bm{{w}}$ are a function of $s$, removing an item can change the scoring direction (\subref{fig:viol_viz_sdw}). When ${\varphi}} %{{\bm{\varphi}}$ is a function of $s$, removing an item can change the spatial position of items (\subref{fig:viol_viz_sde}). Both of these allow $s$ and $s'$ to have different maximizing items, and hence different predictions. } \label{fig:viol_viz} \end{figure} At the core of our approach is the idea of \emph{aggregation}: combining a collection of item score functions ${F}} %{{\bm{f}} = (f_1,\dots,f_\ell)$ into a single score function ${g}$. We refer to $\ell$ as the aggregation dimension. Aggregation is a popular approach to enriching the hypothesis class, but it is easy to show that standard forms of aggregation (e.g., linear aggregation $\inner{v,{F}} %{{\bm{f}}(x)}$, $v \in {\mathbb{R}}^\ell$ as in bagging or boosting) are still bound to IIA. Hence, to express violations, aggregation must be \emph{set-dependent}. Our model is a combination of two powerful set-dependent aggregation mechanisms (illustrated in Fig. \ref{fig:viol_viz}): \vspace{0.1cm} \textbf{Set-dependent weights}: Let $s \in {\mathbb{X}}} % \mathfrak{X$. Starting with $g(x;v) = \inner{v,{F}} %{{\bm{f}}(x)}$, consider replacing each scalar weight $v_i$ with a set function $w_i( \cdotp) : {\mathbb{X}}} % \mathfrak{X \rightarrow {\mathbb{R}}$. This gives the following aggregation model: \begin{equation} \text{\textbf{{SDW}} %{{SDA$_w$}:}} \quad {g}(x,s;w) = \inner{w(s), {F}} %{{\bm{f}}(x)}, \qquad w(s) = (w_1(s), \dots, w_\ell(s)) \label{eq:agg_w} \end{equation} Denote ${\hat{y}} = \argmax_{x \in s} \inner{w(s),{F}} %{{\bm{f}}(x)}$, and let $s' = s \setminus \{x\}$ for some $x \neq {\hat{y}}$. Recall that IIA is violated when removing $x$ from $s$ changes the prediction. Here, because removing $x$ changes the input to each $w_i$, the contribution of each $f_i \in {F}} %{{\bm{f}}$ to ${g}$ changes from $w_i(s)$ to $w_i(s')$. Geometrically, the scoring direction changes, and therefore the choice prediction can change as well (Fig. \ref{fig:viol_viz_sdw}). \vspace{0.15cm} \textbf{Set-dependent embeddings}: Now, consider instead replacing each item score function $f_i \in {F}} %{{\bm{f}}$ with an item-centric set function ${\varphi}} %{{\bm{\varphi}}_i(\cdotp,\cdotp) : {\cal{X}} \times {\mathbb{X}}} % \mathfrak{X \rightarrow {\mathbb{R}}$. The aggregation model is now: \begin{equation} \text{\textbf{{SDE}} %{{SDA$_\feat$}:}} \quad {g}(x,s;v,{\varphi}} %{{\bm{\varphi}}) = \inner{v, {\varphi}} %{{\bm{\varphi}}(x,s)}, \qquad {\varphi}} %{{\bm{\varphi}}(x,s) = ({\varphi}} %{{\bm{\varphi}}_1(x,s), \dots, {\varphi}} %{{\bm{\varphi}}_\ell(x,s)) \label{eq:agg_emb} \end{equation} The vector ${\varphi}} %{{\bm{\varphi}}(x,s)$ is a set-dependent embedding of $x$ (the dependence on ${F}} %{{\bm{f}}$ is implicit). The predicted item is that whose embedding is closest to $v$'s. Here, when the set changes (i.e., by removing an item), items shift in the embedded space, and the prediction can change (Fig. \ref{fig:viol_viz_sde}). \vspace{0.15cm} Our final and most general \textbf{set-dependent aggregation} model combines both mechanisms: \begin{equation} \text{\textbf{SDA}:} \quad {g}(x,s;w,{\varphi}} %{{\bm{\varphi}}) = \inner{w(s), {\varphi}} %{{\bm{\varphi}}(x,s)} \label{eq:agg_comb} \end{equation} We now describe the learning framework and propose a concrete architecture for SDA. \subsection{Learning} Our goal is to learn an aggregator ${g}$ that minimizes the expected risk $\err{}{}({g}) = \expect{{D}}{{\Delta}(y,{g}(s))}$ where ${\Delta}$ is the 0/1 loss. We approximate this by minimizing the empirical risk: \begin{equation} \min_{{g} \in {\cal{G}}} \sum_{i=1}^m {\Delta}(y_i,{g}(s_i)) + \lambda {\mathcal{R}}({g}), \qquad\quad {\Delta}(y,{g}(s)) = \one{h_{g}(s) \neq y} \label{eq:learning_objective} \end{equation} where ${\cal{G}}$ is an aggregator class, and ${\mathcal{R}}$ is a regularization term with coefficient $\lambda$, Note that the decision rule $h_{g}(s) = \argmax_{x \in s} {g}(x,s)$ is now set-dependent. Because aggregation is simply a template for combining score functions, if ${\cal{F}}$, $w$, and ${\varphi}} %{{\bm{\varphi}}$ are differentiable, $g$ is differentiable as well, and can therefore be efficiently optimized end-to-end using standard gradient methods. In Sec. \ref{sec:theory} we bound the expected risk of aggregator classes ${\cal{G}}$. \subsection{Inductive bias} To allow for efficient learning, we implement $w(s)$ and ${\varphi}} %{{\bm{\varphi}}(x,s)$ using key principles from behavioral choice theory, suggesting that the choices are based on a relative, a-symmetric, and context-dependent perception of utility. In accordance, we instantiate: \begin{equation} w(s) = w({F}} %{{\bm{f}}(s)), \qquad {\varphi}} %{{\bm{\varphi}}(x,s) = {\mu} \big({F}} %{{\bm{f}}(x) - \r({F}} %{{\bm{f}}(s)) \big) \label{eq:agg_ib} \end{equation} where ${F}} %{{\bm{f}}(s)=\{{F}} %{{\bm{f}}(x)\}_{x \in s}$. Here, ${F}} %{{\bm{f}}$ models item utilities, $r$ is a set-specific reference point for comparing utilities \cite{tversky1991loss}, ${\mu}$ is a loss-averse evaluation mechanism \cite{kahneman1979prospect,tversky1992advances}, and $w$ integrates multiple evaluations in a context-dependent manner \cite{tversky1969intransitivity,tversky1993context}. This construction generalizes many models from the fields of economics, psychology, and marketing: \begin{claim} The aggregation model in Eq. \eqref{eq:agg_ib} generalizes choice models in \cite{tversky1969intransitivity,mcfadden1973conditional,mcfadden1978modeling, kaneko1979nash,kalai2002rationalizing,kivetz2004alternative,orhun2009optimal}. \label{lemma:multiself} \end{claim} See Appendix \ref{app:ib} for details. In practice, we implement ${F}} %{{\bm{f}}$, $w$ and $r$ using appropriate neural networks, and ${\mu}$ using an a-symmetric s-shaped nonlinearity \cite{maggi2004characterization}. \section{Model Specification} \label{sec:model_specs} Thus far we have considered only general forms of aggregation. We now proceed to presenting a specific aggregation model which is well-suited for choice prediction. Our model strikes a balance between flexibility (by satisfying certain invariances) and specificity (using appropriate inductive bias). We propose the following form of aggregation: \begin{equation} g(x,s) = \big\langle w(s), {\mu}_d \big( {F}} %{{\bm{f}}(x), \r(s) \big) \big\rangle. \label{eq:agg} \end{equation} We now elaborate on the different components of ${g}$. For a single dimension $i \in [\ell]$ in the embedded space, items are first evaluated using some $f_i(x) \in {\cal{F}}$. Then, a ``reference'' valuation is constructed via a set function $r_i(s)$. Next, $f_i(x)$ and $r_i(s)$ are compared by a scalar operator $d(\cdotp,\cdotp)$, such as $d(a,b)=a-b$. We have found it useful to generalize this by letting $f_i$ and $r_i$ be vector valued, and setting $d$ to be an inner product. The item-reference relation is then fed into an a-symmetric non-linearity ${\mu}(\cdotp)$. We denote by $\mu_d$ the composition of $\mu$ over $d$. Finally, all $\ell$ valuations are aggregated using set-dependent weights $w(s)$. Figure \ref{fig:diagram} presents a diagram of this setup. Eq. \eqref{eq:agg} injects inductive bias inspired by the following key principles in behavioral choice theory: \begin{enumerate}[label=\textbf{P\arabic*}:,ref=P\arabic*] \setlength\itemsep{0.2em} \item \label{p:nonlin} \textbf{Asymmetry.} Losses and gains are perceived in an a-symmetric, non-linear manner. This is the hallmark of Kahneman and Tversky's Prospect Theory \cite{kahneman1979prospect,tversky1992advances}. \item \label{p:r} \textbf{Relativity.} Valuations are relative, and are considered with respect to a mutual (and possibly hypothetical) referral item \cite[e.g., ][]{tversky1991loss}. \item \label{p:w} \textbf{Integrability.} Subjective value is multi-dimensional, and context determines how valuations are integrated into a single choice \cite[e.g., ][]{tversky1969intransitivity, tversky1993context}. \end{enumerate} \begin{proposition} $g(x,s)$ in Eq. \eqref{eq:agg} satisfies \ref{p:nonlin}, \ref{p:r}, and \ref{p:w}. \end{proposition} To see this, note that for each dimension $i$, item scores $f_i(x)$ are compared to a mutual set-dependent reference point $r_i(s)$ via $d$, satisfying \ref{p:r}. Using a pointwise a-symmetric non-linearity for ${\mu}$ gives \ref{p:nonlin}. Finally, in accordance with \ref{p:w}, valuations are aggregated in ${g}$ via ${w}} %{\bm{{w}}(s)$. We now describe our specific choice of components. We model $w(s)$ and $r(s)$ as set neural networks \cite{zaheer2017deep}. These are general neural networks whose architecture guarantees permutation invariance, meaning that permuting $s$ will not change the output. For the scalar function ${\mu}$, we have found it useful to use a kinked tanh function: \[ {\mu}(z) = c \tanh(z) \cdotp \one{z<0} + \tanh(z) \cdotp \one{z\ge0}, \quad c>1 \] which is inspired by the s-shaped utility functions used in prospect theory \cite{maggi2004characterization}. Since all four elements of ${g}$ are differentiable, ${g}$ can be optimized over any appropriate loss function (i.e., cross entropy) using standard gradient methods. The learned parameters include the weights in $w$ and in $r$, and $c$ for ${\mu}$. We note that Eq. \eqref{eq:agg} encompasses several models from the multi-self literature. Since these are usually designed for mathematical tractability, they do not always include explicit functional forms, and use simple non-parametric set operations for $w$ and $r$. The predictive advantage of our parametrized model is demonstrated empirically in Sec. \ref{sec:agg_vs_ms}. \begin{figure}[!t] \begin{center} \includegraphics[width=0.3\columnwidth]{diagram3} \caption{The proposed aggregation model} \label{fig:diagram} \end{center} \end{figure} \input{results_table} \subsection{Related material} \label{sec:related} IIA begins with Luce's Axiom of Choice \cite{luce1959individual}, which for a certain noise distribution, induces the popular Multinomial Logit model (MNL) \cite{mcfadden1973conditional,train2009discrete}. Two common extensions--- Nested MNL and Mixed MNL ---relax IIA by grouping items via a tree structure \cite{mcfadden1978modeling} or modeling a mixture population \cite{mcfadden2000mixed}, respectively. These, however, pose restrictive assumptions on the nature of violations, require elaborate hand-coded auxiliary inputs, and are in many cases intractable. Although recent progress has alleviated some difficulties \cite{oh2014learning, benson2016relevance, chierichetti2018learning}, applying these models in practice remains difficult. Recent works have proposed other probabilistic models that deviate from IIA, by modeling pairwise utilities \cite{ragain2018choosing}, $k^{\text{th}}$-order interactions \cite{ragain2016pairwise,seshadri2019discovering}, and general subset relations \cite{benson2018discrete}. These, however, do not optimize for predictive accuracy, and rarely apply to complex choice settings with many items and sparse choice sets. Others suggest discriminative solutions, but these include models that tend to be either over-specific or over-general \cite{mottini2017deep,pfannschmidt2019learning} and provide no guarantees as to what violations can be captured. Our work draws on the literature of utility aggregation (or ``multi-self'' models), studied extensively in economics \cite{kalai2002rationalizing, fudenberg2006dual, manzini2007sequentially, green2009choice, ambrus2015rationalising}, psychology \cite{tversky1972elimination, shafir1993reason, tversky1993context}, and marketing \cite{kivetz2004alternative}. While these typically focus on mathematical tractability or behavioral plausibility, our focus is on statistical and computational aspects relevant to machine learning. Our work is largely inspired by recent results in economics on the expressivity of aggregation \cite{ambrus2015rationalising}. While they give worst-case guarantees for unparameterized items under the realizability assumption, our results study the statistical behavior of parametric aggregation. To the best of our knowledge, our paper is the first to provide rigorous finite-sample error bounds for set-dependent aggregation in the context of choice prediction. \section{Theoretical Analysis} \label{sec:theory} In this section we bound the expected risk of aggregators. Our results demonstrate the power of set-dependent aggregation: expressive enough to allow for arbitrary violations, and concise enough to be efficiently learned. The risk of any ${g} \in {\cal{G}}$ breaks down into two fundamental error types \cite{shalev2014understanding}: \begin{equation} \err{}{}({g}) = \underbrace{\err{*}{}({\cal{G}})}_{\text{approximation}} + \quad \underbrace{ \err{}{}({g}) - \err{*}{}({\cal{G}}) }_{\text{estimation}}, \qquad\qquad \err{*}{{\cal{G}}} = \min_{{g}' \in {\cal{G}}} \err{}{{D}}({g}') \end{equation} Approximation error is a property of the class ${\cal{G}}$, measuring its suitability for examples drawn from ${D}$. Estimation error is specific to $g$, measuring its performance relative to ${g}^*$. Our results show that the tradeoff in both errors is controlled by two factors: the complexity of the utility function class ${\cal{F}}$ and the aggregation dimension $\ell$. \subsection{Approximation Error} \label{sec:apx_err} Our first result shows how aggregation combines predictors that \emph{cannot} express violations into a model that can account for \emph{any} form of violation. Our main theorem reveals how this is achieved: aggregation uses score functions to `isolate' regions of violating sets, and within each region, operate independently. Technically, this is shown by decomposing the approximation error of ${\cal{G}}$ over these regions, where the error in each region depends on the error of ${\cal{F}}$. We begin with some definitions. Recall that IIA mandates that if $y$ is chosen from $s$, then it should also be chosen from any $s' \subseteq s$ with $y \in s'$. This motivates a definition of IIA violation due to \cite{ambrus2015rationalising}:\footnote{ The definition in \cite{ambrus2015rationalising} additionally requires $s$ to be of maximal size, which they need for a counting argument. } \begin{definition}[IIA Violation, \cite{ambrus2015rationalising}] \label{def:viol} A set $s$ \textbf{violates IIA} if there exists $s' \supset s$ with $c(s) \neq c(s') \in s$. \end{definition} Denote the set of all violating sets by ${V}$ and non-violating sets by ${U}} %{{\Viol_{\varnothing}} = {\mathbb{X}}} % \mathfrak{X \setminus {V}$. Let the predicate $s \succarg{f} s'$ be true if $f$ scores items in $s$ higher than items in $s'$, i.e., $f(x) > f(x')\,\,\forall x \in s, x' \in s'$. \begin{definition}[Separation] A score function $f$ \textbf{separates} $s$ if $s \succarg{f} \blue{{\mathbb{X}}} % \mathfrak{X \setminus s}$, defining the \textbf{separable region}: $${\Delta}_f = \{ s \in {V} \,:\, s \text{ is separated by } f \}$$ \label{def:separation} \end{definition} We are now ready to state our main result (see Appendix \ref{app:approx} for proof and further details). \begin{theorem} The approximation error $\err{*}{}({\cal{G}})$ decomposes over: \begin{enumerate} \item \textbf{non-violating sets} with risk at most $\err{*}{}({\cal{F}}|{U}} %{{\Viol_{\varnothing}})$ \item \textbf{separable violating regions} with risk at most $\err{*}{}({\cal{F}}|{\Delta}_f)$ per region \end{enumerate} and the set of separable regions is optimal under budget constraint $\ell$. Specifically, we have: \begin{equation} \err{*}{}({\cal{G}}) \le \sum_{R \in {U}} %{{\Viol_{\varnothing}} \cup {\Delta}_{F}} %{{\bm{f}}} p_R \, \err{*}{}({\cal{F}}|R) + p_{{V} \setminus {\Delta}_{F}} %{{\bm{f}}} \label{eq:err_decomp} \end{equation} for the optimal ${F}} %{{\bm{f}} \in {\cal{F}}^{\ell'}$, where ${\Delta}_{F}} %{{\bm{f}} = \cup_{f \in {F}} %{{\bm{f}}} {\Delta}_f$, $\ell' \le (\ell-1)/5$, and $p_A=P(s \in A)$. \label{thm:err_decomp} \end{theorem} Theorem \ref{thm:err_decomp} hints at how aggregation can account for violations: it partitions ${\mathbb{X}}} % \mathfrak{X$ into regions, and applies ${\cal{F}}$ to each region independently. In this process, ${\cal{F}}$ plays a corresponding dual role of both determining separable regions ${\Delta}_f$ and predicting within these regions. This demonstrates how the \emph{type} of accountable violations is controlled by the expressivity of ${\cal{F}}$, and how the \emph{number} of violations (via the number of regions) is controlled by $\ell$. In principal, aggregation can account for any violation: \begin{corollary} If $y=c(s)$ for some choice function $c$ and for all $s \in {\mathbb{X}}} % \mathfrak{X$, then with sufficiently large $\ell$ and sufficiently expressive ${\cal{F}}$, the approximation error vanishes, i.e., $\err{*}{}({\cal{G}})=0$.\footnote{ Here we assume that the approximation error does not include the irreducible error. \qquad\qquad\qquad\qquad} \end{corollary} Our proof takes the main building blocks of \cite{ambrus2015rationalising}--- objects called ``triple bases'' ---and carefully weaves them within a statistical framework. As in \cite{ambrus2015rationalising}, results apply to classes satisfying a natural property of \emph{scale-invariance}; these include all but one model from Claim \ref{lemma:multiself}. The main lemma in the proof requires that ${\cal{G}}$ is defined over an auxiliary neural-network class of score functions that is slightly richer than ${\cal{F}}$, and shows how ``implementing'' triple bases using simple neural circuits enables a decomposition of the error over violating regions. The general statement of Theorem \ref{thm:err_decomp} is that the more complex ${\cal{F}}$ and the larger $\ell$, the better the approximation error. Our next results quantifies how this trades off with estimation error. \subsection{Estimation Error} \label{sec:est_err} Our next results establish the learnability of aggregation. We give sample complexity bounds on the empirical risk $\err{}{{\S}}({g}) = \expect{{\S}}{{\Delta}(y,{g}(s))}$ showing how learning both weight and embedding mechanisms (Sec. \ref{sec:model}) depends on ${\cal{F}}$, $\ell$, and the aggregation components in ${g}$. Proofs are based on Rademacher bounds and are given in Appendix \ref{app:est}. To simplify the analysis, we focus on set operations and on a linear base class: \[ {\cal{F}}_\text{lin}^\rho = \{ {F}} %{{\bm{f}}(x) = x^\top \Theta \,:\, \Theta \in {\mathbb{R}}^{d \times \ell}, \, \|\Theta\|_\rho \le 1 \} \] where $\|\cdotp\|_\rho$ is the induced $\rho$-norm. This suffices to cover the models from Claim \ref{lemma:multiself}.\footnote{ All except for one of the three models proposed in \cite{kivetz2004alternative}.} For any function $q$, we denote its Lipschitz constant by $\lambda_q$ when it is scalar-valued and by $\lambda_q^\rho$ when it is vector valued and with respect to the $\rho$-norm. We also use $X_\rho = \max_{x \in s \in {\S}} \|x\|_\rho$. The first bound applies to the set-dependent weight mechanism (Eq. \eqref{eq:agg_w}). \begin{theorem} Let ${\cal{G}}$ be a class of aggregators over ${\cal{F}}_\text{lin}^\infty$ of the form $g(x,s) = \inner{{w}} %{\bm{{w}}(s), {F}} %{{\bm{f}}(x)}$. Then for all ${D}$ and any $\delta \in [0,1]$, it holds that \[ \err{}{}({\cal{G}}) \le \err{}{{\S}}({\cal{G}}) + 4 X_\infty^2 \lambda_w^\rho \sqrt{\frac{2 \log 2d}{m}} + O \left( \sqrt{\frac{ \log(1 / \delta)}{m}} \right) \] with probability of at least $1-\delta$. \end{theorem} The second bound applies to the set-dependent embedding mechanism (Eq. \eqref{eq:agg_emb}), where for concreteness we set ${\varphi}} %{{\bm{\varphi}}$ according to the inductive bias model in Eq. \eqref{eq:agg_ib}. \begin{theorem} Let ${\cal{G}}$ be a class of aggregators over ${\cal{F}}_\text{lin}^1$ of the form $g(x,s) = \inner{v,{\varphi}} %{{\bm{\varphi}}(x,s)}$ where ${\varphi}} %{{\bm{\varphi}}(x,s)=\inner{w, {\mu}({F}} %{{\bm{f}}(x)-r(s))}$ as in Eq. \eqref{eq:agg_ib}. Then for all ${D}$ and any $\delta \in [0,1]$, it holds that \begin{equation*} \err{}{}({\cal{G}}) \le \err{}{{\S}}({\cal{G}}) + 4 W_1 X_\infty \lambda_\mu (1+\lambda_r^\rho) \sqrt{\frac{2 \log 2d}{m}} + O \left( \sqrt{\frac{\log(1 / \delta)}{m}}\right) \end{equation*} with probability of at least $1-\delta$, where $W_1 = \|w\|_1$. \end{theorem} Both results show what governs learnability: the dimension $\ell$ plays an implicit role via the Lipschitz constants of the set operations, and ${\cal{F}}$ effects the bound via the norm of $w$ (also depending on $\ell$).
{'timestamp': '2019-06-18T02:01:39', 'yymm': '1906', 'arxiv_id': '1906.06365', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06365'}
arxiv
\section{Fitting the activations} \label{sec:parametricfit} \subsection{Parametric Fr\'echet model after average-pooling} In this section we derive a parametric model that fits the distribution of activations on output of the spatial pooling layer. The output the the last convolutional layer can be well approximated with a Gaussian distribution. Then the batch-norm centers the Gaussian and reduces its variance to unit, and the ReLU replaces the negative part with 0. Thus the ReLU outputs an equal mixture of a cropped unit Gaussian and a Dirac of value 0. The average pooling sums $n=2\times2$ to $n=14\times14$ of those distributions together. Assuming independence of the inputs, it can be seen as a sum of $n'$ cropped Gaussians, where $n'$ follows a discrete binomial distribution. Unfortunately, we found this composition of distributions is not tractable in close form. Instead, we observed experimentally that the output distribution is close to an extreme value distribution. This is due to the fact that only the positive part of the Gaussians contributes to the output values. In an extreme value distribution that is the sum of several (arbitrary independent) distributions, the same happens: only the highest parts of those distributions contribute. Thus, we model the statistics of activations as a Fr\'echet (a.k.a. inverse Weibull) distribution. This is a 2-parameter distribution whose CDF has the form: \[ P(x,\mu,\sigma) = e^{-\left(1+\frac{\xi}{\sigma}(x-\mu)\right)^{-1/\xi}} \] With~$\xi$~a~positive~constant, $\mu \in \mathbb{R} , \sigma \in \mathbb{R}^{*}_{+}.$ We observed that the parameter $\xi$ can be kept constant at $0.3$ to fit the distributions. \begin{figure*}[b] \begin{minipage}{0.24\linewidth} \includegraphics[width=\linewidth]{figs/Frechet_distribution/CDF_subplots/whitout_title/CDF_of_non_zero_value_after_average_pooling_Frechet_fig1_res64.pdf} \\ Resolution: 64 \end{minipage} \hfill \begin{minipage}{0.24\linewidth} \includegraphics[width=\linewidth]{figs/Frechet_distribution/CDF_subplots/whitout_title/CDF_of_non_zero_value_after_average_pooling_Frechet_fig2_res128.pdf} \\ Resolution: 128 \end{minipage} \hfill \begin{minipage}{0.24\linewidth} \includegraphics[width=\linewidth]{figs/Frechet_distribution/CDF_subplots/whitout_title/CDF_of_non_zero_value_after_average_pooling_Frechet_fig3_res224.pdf} \\ Resolution: 224 \end{minipage} \hfill \begin{minipage}{0.24\linewidth} \includegraphics[width=\linewidth]{figs/Frechet_distribution/CDF_subplots/whitout_title/CDF_of_non_zero_value_after_average_pooling_Frechet_fig4_res448.pdf} \\ Resolution: 448 \end{minipage} \caption{\label{fig:pdfresolutionfrechet} Fitting of the CDF of activations with a Fr\'echet distribution. } \end{figure*} Figure~\ref{fig:pdfresolutionfrechet} shows how the Fr\'echet model fits the empirical CDF of the distribution. The parameters were estimated using least-squares minimization, excluding the zeros, that can be considered outliers. The fit is so exact that the difference between the curves is barely visible. To correct the discrepancy in distributions at training and test times, we compute the parameters $\mu_\mathrm{ref}, \sigma_\mathrm{ref}$ of the distribution observed on training images time for $K_\text{test} = K_\text{train}$. Then we increase $K_\text{test}$ to the target resolution and measure the parameters $\mu_0, \sigma_0$ again. Thus, the transformation is just an affine scaling, still ignoring zeros. When running the transformed neural net on the Imagenet evaluation, we obtain accuracies: \begin{center} \begin{tabular}{|l|rrrrrr|} \hline $K_\text{test}^\text{image}$ & 64 & 128 & 224 & 256 & 288 & 448 \\ accuracy & 29.4 & 65.4 & 77 &78 & 78.4 & 76.5 \\ \hline \end{tabular} \end{center} Hence, the accuracy does not improve with respect to the baseline. This can be explained by several factors: the scalar distribution model, however good it fits to the observations, is insufficient to account for the individual distributions of the activation values; just fitting the distribution may not be enough to account for the changes in behavior of the convolutional trunk. \subsection{Gaussian model before the last ReLU activation} Following the same idea as what we did previously we looked at the distribution of activations by channel before the last ReLU according to the resolution. We have seen that the distributions are different from one resolution to another. With higher resolutions, the mean tends to be closer to 0 and the variance tends to become smaller. By acting on the distributions before the ReLU, it is also possible to affect the sparsity of values after spatial-pooling, which was not possible with the previous analysis based on Frechet's law. We aim at matching the distribution before the last ReLU with the distribution of training data at lower resolution. We compare the effect of this transformation before/after fine tuning with the learnt batch-norm approach. The results are summarized in Table~\ref{tab:adaptlaw}. We can see that adapting the resolution by changing the distributions is effective especially in the case of small resolutions. Nevertheless, the adaptation obtained by fine-tuning the the batch norm improves performs better in general. \begin{table*} \caption{\label{tab:adaptlaw} Matching distribution before the last Relu application to ResNet-50: Resulting top-1 accuracy \% on ImageNet validation set } \centering {\small \begin{tabular}{cccccc@{\hspace{11pt}}c@{\hspace{11pt}}c@{\hspace{11pt}}c@{\hspace{11pt}}c} \toprule \multicolumn{1}{c}{Model} &\multicolumn{1}{c}{Train} & \multicolumn{1}{c}{Adapted }& \multicolumn{2}{c}{Fine-tuning}& \multicolumn{5}{c}{Test resolution} \\ \cmidrule(lr){4-5} \cmidrule(lr){6-10} used &resolution & Distribution & Classifier & Batch-norm & 64 & 224 & 288 & 352 & 384\\ \cmidrule(lr){1-1} \cmidrule(lr){2-2} \cmidrule(lr){3-5} \cmidrule(lr){6-10} ResNet-50 & 224 & \_ & \_ & \_ & 29.4 & 77.0 & 78.4 & 78.1 & 77.7 \\ ResNet-50 & 224 & \checkmark & \_ & \_ & 29.8 & 77.0 & 77.7 & 77.3 & 76.8 \\ ResNet-50 & 224 & \_ & \checkmark & \_ & 40.6 & 77.1 & 78.6 &78.9 & 78.9 \\ ResNet-50 & 224 & \_ & \checkmark & \checkmark & 41.7 & 77.1 & 78.5 & 78.9 & 79.0 \\ ResNet-50 & 224 & \checkmark & \checkmark & \_ & 41.8 & 77.1 & 78.5 & 78.8 & 78.9 \\ \bottomrule \end{tabular}} \end{table*} \section{Border and round-off effects} \label{sec:roundoff} Due to the complex discrete nature of convolutional layers, the accuracy is not a monotonous function of the input resolution. There is a strong dependency on the kernel sizes and strides used in the first convolutional layers. Some resolutions will not match with these parameters so we will have a part of the images margin that will not be taken into account by the convolutional layers. In Figure~\ref{fig:onepixels}, we show the variation in accuracy when the resolution of the crop is increased by steps of 1~pixel. Of course, it is possible to do padding but it will never be equivalent to having a resolution image adapted to the kernel and stride size. Although the global trend is increasing, there is a lot of jitter that comes from those border effects. There is a large drop just after resolution 256. We observe the drops at each multiple of 32, they correspond to a changes in the top-level activation map's resolution. Therefore we decided to use only sizes that are multiples of 32 in the experiments. \begin{figure}[t] \begin{center} \includegraphics[width=0.5\columnwidth]{figs/pixels_increment_by_one/Best_accuracy_resolution_zoom_224.pdf}~% \end{center} \caption{\label{fig:onepixels} Evolution of the top-1 accuracy of the ResNet-50 trained with resolution 224 according to the testing resolution (no finetuning). This can be considered a zoom of figure~\ref{fig:accuracyresolution} with 1-pixel increments. } \end{figure} \section{Result tables} \label{sec:resulttables} Due to the lack of space, we report only the most important results in the main paper. In this section, we report the full result tables for several experiments. Table~\ref{tab:baselines} report the numerical results corresponding to Figure~\ref{fig:accuracyresolution} in the main text. Table~\ref{tab:ablationstudytable} reports the full ablation study results (see Section~\ref{sec:ablation}). \label{sec:supptimings} Table~\ref{tab:time} reports the runtime measurements that Section~\ref{sec:timings} refers to. Table~\ref{tab:dataaugmentationcomparison} reports a comparaison between test DA and test DA2 that Section~\ref{sec:experiments} refers to. \begin{table*} {\small ~\hfill \begin{tabular}{lrcccc} \toprule test $\backslash$ train & 64 \ \ & 128 & 160 & 224 & 384 \\ \midrule 64 & 63.2 & 48.3 & 40.1 & 29.4 & 12.6 \\ 128 & \textbf{68.2} & 73.3 &71.2 & 65.4 & 48.0 \\ 224 & 55.3 & \textbf{75.7} &\textbf{ 77.3} & 77.0 & 70.5 \\ 288 & 42.4 & 73.8 & 76.6 & \textbf{78.4} & 75.2 \\ 384 & 23.8 & 69.6 & 73.8 & 77.7 & 78.2 \\ 448 & 13.0 & 65.8 &71.5 & 76.6 & \textbf{78.8} \\ 480 & 9.7 & 63.9 & 70.2 & 75.9 & 78.7 \\ \bottomrule \end{tabular}% % % \hfill \begin{tabular}{l|llll} \toprule test $\backslash$ train & 64 & 128 & 224 & 384 \\ \midrule 64 & 63.5 & 53.7 & 41.7 & 27.5 \\ 128 & \textbf{71.3} & 73.4 & 67.7 & 55.7 \\ 224 & 66.9 & \textbf{77.1} & 77.1 & 71.9 \\ 288 & 62.4 & 76.6 & 78.6 & 75.7 \\ 384 & 55.0 & 74.8 & \textbf{79.0} & 78.2 \\ 448 & 49.7 & 73.0 & 78.4 & 78.8 \\ 480 & 46.6 & 72.2 & 78.1 & \textbf{79.0} \\ \bottomrule \end{tabular} \hfill ~} \smallskip \caption{ \label{tab:baselines} Top-1 validation accuracy for different combinations of training and testing resolution. Left: with the standard training procedure, (no finetuning, no adaptation of the ResNet-50). Right: with our data-driven adaptation strategy and test-time augmentations. } \end{table*} \iffalse \begin{table} \centering \begin{tabular}{l|llll} \toprule test $\backslash$ train & 64 & 128 & 224 & 384 \\ \midrule 64 & 63.5 & 53.7 & 41.7 & 27.5 \\ 128 & \textbf{71.3} & 73.4 & 67.7 & 55.7 \\ 224 & 66.9 & \textbf{77.1} & 77.1 & 71.9 \\ 288 & 62.4 & 76.6 & 78.6 & 75.7 \\ 384 & 55.0 & 74.8 & \textbf{79.0} & 78.2 \\ 448 & 49.7 & 73.0 & 78.4 & 78.8 \\ 480 & 46.6 & 72.2 & 78.1 & \textbf{79.0} \\ \bottomrule \end{tabular} \caption{\label{tab:finetunebatchnormbaselines} Top-1 validation accuracy for different combinations of training and testing resolution. This is with the fine-tuning of the last batch norm and the classification layer of the ResNet-50 network with test-time augmentations. } \end{table} \fi \begin{table*} \centering {\small \begin{tabular}{c|ccc|cccccc} \toprule \multicolumn{1}{c}{Train} & \multicolumn{3}{|c}{Fine-tuning}& \multicolumn{6}{|c}{Test resolution (top-1 accuracy)} \\ \cmidrule(lr){2-4} \cmidrule(lr){5-10} resolution & Classifier & Batch-norm & Data aug. & 64 & 128 &224 & 288 & 384 & 448\\ \midrule & -- & -- & n/a & 48.3 & 73.3 & \textbf{75.7} & 73.8 & 69.6 & 65.8 \\ % & \checkmark & -- & train DA & 52.8 & 73.3 & \textbf{77.1} & 76.3& 73.2 & 71.7 \\ 128 & \checkmark & -- & test DA& 53.3 & 73.4 & \textbf{77.1} & 76.4& 74.4 & 72.3 \\ % & \checkmark & \checkmark & train DA & 53.0 & 73.3 & \textbf{77.1} & 76.5 & 74.4 & 71.9 \\ & \checkmark & \checkmark & test DA & 53.7 & 73.4 & \textbf{77.1} & 76.6 & 74.8 & 73.0 \\ \midrule & -- & -- & n/a & 29.4 & 65.4 & 77.0 & \textbf{78.4} & 77.7 & 76.6 \\ % & \checkmark & -- & train DA & 39.9 &67.5 & 77.0 & 78.6 & \textbf{78.9} & 78.0 \\ 224 & \checkmark & -- & test DA & 40.6 & 67.3 & 77.1 & 78.6 & \textbf{78.9} & 77.9 \\ % & \checkmark & \checkmark & train DA & 40.4 & 67.5 & 77.0 & 78.6 & \textbf{78.9} & 78.0 \\ & \checkmark & \checkmark & test DA & 41.7 & 67.7 & 77.1 & 78.6 & \textbf{79.0} & 78.4 \\ \bottomrule \end{tabular}} \smallskip \caption{\label{tab:ablationstudytable} Ablation study: Accuracy when enabling or disabling some components of the training method. Train DA: training-time data augmentation during fine-tuning, test DA: test-time one. } \end{table*} \newcommand{\std}[1]{\footnotesize{$\pm #1$}} \begin{table*} \centering \small \begin{tabular}{ll|rrrr|rc} \toprule \multicolumn{2}{c}{Resolution} & \multicolumn{2}{c}{Train time per batch (ms)} & \multicolumn{2}{c}{Resolution fine-tuning (ms)} & \multicolumn{2}{c}{Performance} \\ \cmidrule(lr){1-2} \cmidrule(lr){3-4} \cmidrule(lr){5-6} \cmidrule(lr){7-8} train & test & backward & forward & backward & forward & Total time (h) & accuracy \\ \midrule 128 & 128 & 29.0 \std{4.0} & 12.8 \std{2.8} & \_ & \_ & 111.8 \hspace{1.5em} & 73.3 \\ 160 & 160 & 30.2 \std{3.2} & 14.5 \std{3.4} & \_ & \_ & 119.7 \hspace{1.5em} & 75.1 \\ 224 & 224 & 35.0 \std{2.0} & 15.2 \std{3.2} & \_ & \_ & 133.9 \hspace{1.5em} & 77.0 \\ 384 & 384 & 112.4 \std{6.2} & 18.2 \std{3.9} & \_ & \_ & 348.5 \hspace{1.5em} & 78.2 \\ \midrule 160 & 224 & 30.2 \std{3.2} & 14.5 \std{3.4} & \_ & \_ & 119.7 \hspace{1.5em} & 77.3 \\ 224 & 288 & 35.0 \std{2.0} & 15.2 \std{3.2} & \_ & \_ & 133.9 \hspace{1.5em} & 78.4 \\ \midrule 128 & 224 & 29.0 \std{4.0} & 12.8 \std{2.8} & 4.4 \std{0.9} & 14.4 \std{2.5} & 124.1 \hspace{1.5em} & 77.1 \\ 160 & 224 & 30.2 \std{3.2} & 14.5 \std{3.4} & 4.4 \std{0.9} & 14.4 \std{2.5} & 131.9 \hspace{1.5em} & 77.6 \\ 224 & 384 & 35.0 \std{2.0} & 15.2 \std{3.2} & 8.2 \std{1.3} & 18.0 \std{2.7} & 151.5 \hspace{1.5em} & 79.0\\ \bottomrule \end{tabular} \smallskip \caption{\label{tab:time} Execution time for the training. Training and fine-tuning times are reported for a batch of size 32 for training and 64 for fine-tuning, on one GPU. Fine-tuning uses less memory than training therefore we can use larger batch size. The total time is the total time spent on both, with 120 epochs for training and 60 epochs of fine-tuning on ImageNet. Our approach corresponds to fine-tuning of the batch-norm and the classification layer. } \end{table*} \begin{table*} \centering \small \begin{tabular}{lcccc} \toprule Models & Train & Test & Top-1 test DA (\%) & Top-1 test DA2 (\%) \\ \midrule ResNext-101 32x48d & 224 & 288 & 86.0 & 86.1 \\ ResNext-101 32x48d & 224 & 320 & 86.3 & 86.4 \\ \midrule ResNet-50 & 224 & 320 & 79.0 & 79.1 \\ \midrule ResNet-50 CutMix & 224 & 384 & 79.7 & 79.8 \\ \bottomrule \end{tabular} \smallskip \caption{\label{tab:dataaugmentationcomparison} Comparisons of performance between data-augmentation test DA and test DA2 in the case of fine-tuning batch-norm and classifier. } \end{table*} \section{Impact of Random Resized Crop} \label{sec:RandomResizedCropEffect} In this section we measure the impact of the RandomResizedCrop illustrated in the section~\ref{sec:experiments}. To do this we did the same experiment as in section~\ref{sec:experiments} but we replaced the RandomResizedCrop with a Resize followed by a random crop with a fixed size. The figure~\ref{fig:norandomresizedcrop} and table~\ref{tab:norandomresizedcrop} shows our results. We can see that the effect observed in the section~\ref{sec:experiments} is mainly due to the Random Resized Crop as we suggested with our analysis of the section~\ref{sec:analysis}. \begin{table} \centering \begin{tabular}{l|llll} \toprule test $\backslash$ train & 64 & 128 & 224 & 384 \\ \midrule 64 & 60.0 & 48.7 & 28.1 & 11.5 \\ 96 & \textbf{61.6} & 65.0 & 50.9 & 29.8 \\ 128 & 54.2 & 70.8 & 63.5 & 46.0 \\ 160 & 42.4 & \textbf{72.4} & 69.7 & 57.0 \\ 224 & 21.7 & 69.8 & 74.6 & 68.8 \\ 256 & 15.3 & 66.4 & \textbf{75.2} & 72.1 \\ 384 & 4.3 & 44.8 & 71.7 & 76.7 \\ 440 & 2.3 & 33.6 & 67.1 & \textbf{77.0} \\ \bottomrule \end{tabular} \caption{\label{tab:norandomresizedcrop} Top-1 validation accuracy for different combinations of training and testing resolution. ResNet-50 train with resize and random crop with a fixed size instead of random resized crop. } \end{table} \begin{figure}[t] \begin{center} \includegraphics[width=0.5\columnwidth]{figs/No_Random_Resized_Crop/without_random_resized_crop_test_higher.pdf}~% \end{center} \caption{\label{fig:norandomresizedcrop} Top-1 accuracy of the ResNet-50 according to the test time resolution. ResNet-50 train with resize and random crop with a fixed size instead of random resized crop. } \end{figure} \section{Fine-Grained Visual Categorization contests: iNaturalist \& Herbarium} \label{sec:challenges} In this section we summarize the results we obtained with our method during the CVPR 2019 iNaturalist~\cite{Horn2017INaturalist} and Herbarium~\cite{Kiat2019Herbarium} competitions\footnote{ \url{https://www.kaggle.com/c/herbarium-2019-fgvc6} \newline \url{https://www.kaggle.com/c/inaturalist-2019-fgvc6}}. We used the approach lined out in Subsection~\ref{sec:transferlearning}, except that we adapted the preprocessing to each dataset and added a few ``tricks'' useful in competitions (ensembling, multiple crops). \subsection{Challenges} The iNaturalist Challenge 2019 dataset contains images of 1010 animal and plant species, with a training set of 268,243 images and a test set of 35,351 images. The main difficulty is that the species are very similar within the six main families (Birds, Reptiles, Plants, Insects, Fungi and Amphibians) contained in the dataset. There is also a very high variability within the classes as the appearance of males, females and juveniles is often very different. What also complicates the classification is the size of the area of interest which is very variable from one image to another, sometimes the images are close-ups on the subject, sometimes we can hardly distinguish it. As a preprocessing, all images have been resized to have a maximum dimension of 800 pixels. The Herbarium contest requires to identify melastome species from 683 herbarium specimenina. The training set contain 34,225 images and the test set contain 9,565 images. The main difficulty is that the specimina are very similar and not always intact. In this challenge the particularity is that there is no variability in the background: each specimen is photographed on a white sheet of paper. All images have been also resized to have a maximum dimension of 800 pixels. \subsection{Ensemble of classifiers} In both cases we used 4 different CNNs to do the classification and we averaged their results, which are themselves from 10 crops of the image. We chose 4 quite different in their architectures in order to obtain orthogonal classification results. We tried to include the ResNet-50, but it was significantly worse than the other models, even when using an ensemble of models, probably due to its limited capacity. We used two fine-tuning stages: (1) to adapt to the new dataset in 120 epochs and (2) to adapt to a higher resolution in a few epochs. We chose the initial training resolution with grid-search, within the computational constraints. We did not skew the sampling to balance the classes. The rationale for this is that the performance measure is top-1 accuracy, so the penalty to misclassify infrequent classes is low. \subsection{Results} Table~\ref{tab:challenge} summarizes the parameters of our submission and the results. We report our top-performing approach, 3 and 1 points behind the winners of the competition. Note that we just used our method off-the-shelf and therefore used much fewer evaluations on the public part of the test set (5 for iNaturalist and 8 for Herbarium). The number of CNNs that at are combined in our ensemble is also smaller that two best performing ones. In addition, for iNaturalist we did not train on data from the 2018 version of the contest. In summary, our participation was a run with minimal if no tweaking, where we obtain excellent results (5th out of more than 200 on iNaturalist), thanks to the test-time resolution adaptation exposed in this article. \begin{table*} \centering \small \begin{tabular}{c|c|ccc|c} \toprule \multicolumn{1}{c}{INaturalist}& \multicolumn{1}{|c}{Train} & \multicolumn{3}{|c}{Fine-tuning} & \multicolumn{1}{|c}{Test}\\ \cmidrule(lr){3-5} Model used & resolution & Layer 4 & Classifier & Batch-norm & resolution \\ \midrule SE-ResNext-101-32x4d & 448 & -- & \checkmark & \checkmark & 704 \\ SENet-154 & 448 & \checkmark & \checkmark & \checkmark & 672 \\ Inception-ResNet-V2 & 491 & -- & \checkmark & \checkmark & 681 \\ ResNet-152-MPN-COV \cite{Li2017MPN} & 448 & -- & -- & -- & 448 \\ \midrule \multicolumn{1}{c}{}& \multicolumn{1}{c}{final score : } &\multicolumn{1}{c}{86.577 \%}& \multicolumn{1}{c}{Rank : 5 / 214} &\multicolumn{1}{c}{}& \multicolumn{1}{c}{}\\ \toprule \multicolumn{1}{c}{Herbarium}& \multicolumn{1}{|c}{Train} & \multicolumn{3}{|c}{Fine-tuning} & \multicolumn{1}{|c}{Test}\\ \cmidrule(lr){3-5} Model used & resolution & Layer 4 & Classifier & Batch-norm & resolution \\ \midrule SENet-154 & 448 & -- & \checkmark & \checkmark & 707 \\ ResNet-50 & 384 & -- & \checkmark & \checkmark & 640 \\ \midrule \multicolumn{1}{c}{}& \multicolumn{1}{c}{final score : } &\multicolumn{1}{c}{88.845 \%}& \multicolumn{1}{c}{Rank : 4 / 22} &\multicolumn{1}{c}{}& \multicolumn{1}{c}{}\\ \bottomrule \end{tabular} \smallskip \caption{\label{tab:challenge} Our best ensemble results for the Herbarium and INaturalist competitions. } \end{table*} \section{Method}\label{sec:approach} Based on the analysis of~\cref{sec:analysis}, we propose two improvements to the standard setting. First, we show that the difference in apparent object sizes at training and testing time can be removed by increasing the crop size at test time, which explains the empirical observation of~\cref{sec:paradox}. Second, we slightly adjust the network before the global average pooling layer in order to compensate for the change in activation statistics due to the increased size of the input crop. \subsection{Calibrating the object sizes by adjusting the crop size} \Cref{eq:avgscaleratio} estimates the change in the apparent object sizes during training and testing. If the size of the intermediate image $K_\text{test}^\text{image}$ is \emph{increased} by a factor $\alpha$ (where $\alpha \approx 1/0.80 = 1.25$ in the example) then at test time, the apparent size of the objects is increased by the same factor. This equalizes the effect of the training pre-processing that tends to zoom on the objects. However, increasing $K_\text{test}^\text{image}$ with $K_\text{test}$ fixed means looking at a smaller part of the object. This is not ideal: the object to identify is often well framed by the photographer, so the crop may show only a detail of the object or miss it altogether. Hence, in addition to increasing $K_\text{test}^\text{image}$, we \emph{also} increase the crop size $K_\text{test}$ to keep the ratio $K_\text{test}^\text{image} / K_\text{test}$ constant. % However, this means that $K_\text{test} > K_\text{train}$, which skews % the activation statistics (\cref{sec:prelimactmap}). The next section shows how to compensate for this skew. \ifnips \subsection{Adjusting the statistics before spatial pooling} \else \subsection{Adjusting statistics before spatial pooling} \fi At this point, we have selected the ``correct'' test resolution for the crop but we have skewed activation statistics. Hereafter we explore two approaches to compensate for this skew. % \paragraph{Parametric adaptation.} We fit the output of the average pooling layer (\cref{sec:prelimactmap}) with a parametric Fr\'echet distribution at the original $K_\text{train}$ and final $K_\text{test}$ resolutions. Then, we define an equalization mapping from the new distribution back to the old one via a scalar transformation, and apply it as an activation function after the pooling layer (see Appendix~\ref{sec:parametricfit}). This compensation provides a measurable but limited improvement on accuracy, probably because the model is too simple and does not differentiate the distributions of different components going through the pooling operator. \paragraph{Adaptation via fine-tuning.} Increasing the crop resolution at test time is effectively a domain shift. A natural way to compensate for this shift is to fine-tune the model. In our case, we fine-tune on the same training set, after switching from $K_\text{train}$ to $K_\text{test}$. Here we choose to restrict the fine-tuning to the very last layers of the network. A take-away from the distribution analysis is that the sparsity should be adapted. This requires at least to include the batch normalization that precedes the global pooling into the fine-tuning. In this way the batch statistics are adapted to the increased resolution. We also use the test-time augmentation scheme during fine-tuning to avoid incurring further domain shifts. \Cref{fig:cdfbatchnormeffect} shows the pooling operator's activation statistics before and after fine-tuning. After fine-tuning the activation statistics closely resemble the train-time statistics. % This hints that adaptation is successful. However, as discussed above, this does not imply an improvement in accuracy. \begin{figure*} \begin{center} \begin{minipage}{0.24\linewidth} \includegraphics[width=\columnwidth]{figs/Batch_norm_effect/CDF_Batch_norm_effect_subplot/without_title/CDF_Batch_norm_effect_fig1_res64.pdf} \\ \centering $K_\text{test}=64$ \end{minipage} \hfill \begin{minipage}{0.24\linewidth} \includegraphics[width=\columnwidth]{figs/Batch_norm_effect/CDF_Batch_norm_effect_subplot/without_title/CDF_Batch_norm_effect_fig2_res128.pdf} \\ \centering $K_\text{test}=128$ \end{minipage} \hfill \begin{minipage}{0.24\linewidth} \includegraphics[width=\columnwidth]{figs/Batch_norm_effect/CDF_Batch_norm_effect_subplot/without_title/CDF_Batch_norm_effect_fig3_res224.pdf} \\ \centering $K_\text{test}=224$ \end{minipage} \hfill \begin{minipage}{0.24\linewidth} \includegraphics[width=\columnwidth]{figs/Batch_norm_effect/CDF_Batch_norm_effect_subplot/without_title/CDF_Batch_norm_effect_fig4_res448.pdf}\\ \centering $K_\text{test}=448$ \end{minipage} \end{center} \caption{\label{fig:cdfbatchnormeffect} CDF of the activations on output of the average pooling layer, for a ResNet-50, when tested at different resolutions $K_\text{test}$. Compare the state before and after fine-tuning the batch-norm. % } \end{figure*} \section{Experiments}\label{sec:experiments} \newcommand{B}{B} \label{sec:setup} \paragraph{Benchmark data.} We experiment on the ImageNet-2012 benchmark~\cite{Russakovsky2015ImageNet12}, reporting validation performance as top-1 accuracy. It has been argued that this measure is sensitive to errors in the ImageNet labels~\cite{stock2018convnets}. However, the top-5 metrics, which is more robust, tends to saturate with modern architectures, while the top-1 accuracy is more sensitive to improvements in the model. To assess the significance of our results, we compute the standard deviation of the top-1 accuracy: we classify the validation images, split the set into 10 folds and measure the accuracy on 9 of them, leaving one out in turn. The standard deviation of accuracy over these folds is $\sim 0.03\%$ for all settings. \ifnips Therefore, we report 1 significant digit in the accuracy percentages. \else Thus we report 1 significant digit in the accuracy percentages. \fi In the supplemental material, we also report results on the Fine-Grained Visual Categorization challenges iNaturalist and Herbarium. \paragraph{Architectures.} We use standard state-of-the-art neural network architectures with no modifications, We consider in particular ResNet-50~\cite{He2016ResNet}. For larger experiments, we use PNASNet-5-Large \cite{Liu2018PNAS}, learned using ``neural architecture search'' as a succession of interconnected cells. It is accurate (82.9\% Top-1) with relatively few parameters (86.1 M). We use also ResNeXt-101 32x48d \cite{mahajan2018exploring}, pre-trained in weakly-supervised fashion on 940 million public images with 1.5K hashtags matching with 1000 ImageNet1K synsets. It is accurate (85.4\% Top-1) with lot of parameters (829 M). \paragraph{Training protocol.} We train ResNet-50 with SGD with a learning rate of $0.1 \times B / 256$, where $B$ is the batch size, as in~\cite{Tong2018BagofTricks}. The learning rate is divided by 10 every 30 epochs. With a Repeated Augmentation of 3, an epoch processes $5005 \times 512 / B$ batches, or $\sim$90\% of the training images, see~\cite{berman2019multigrain}. In the initial training, we use $B=512$, 120 epochs and the default PyTorch data augmentation: horizontal flip, random resized crop (as in~\cref{sec:analysis}) and color jittering. To finetune, the initial learning rate is $0.008$ same decay, $B=512$, 60 epochs. The data-augmentation used for fine-tuning is described in the next paragraph. For ResNeXt-101 32x48d we use the pretrained version from PyTorch hub repository~\cite{pretrainedpytorchWSL}. We use almost the same fine-tuning as for the ResNet-50. We also use a ten times smaller learning rate and a batch size two times smaller. For PNASNet-5-Large we use the pretrained version from Cadene's GitHub repository~\cite{pretrainedpytorch}. The difference with the ResNet-50 fine-tuning is that we modify the last three cells, in one epoch and with a learning rate of 0.0008. We run our experiments on machines with 8 Tesla V100 GPUs and 80\,CPU cores to train and fine-tune our ResNet-50. \paragraph{Fine-tuning data-augmentation.} \label{par:finetunedata} We experimented three data-augmentation for fine-tuning: The first one (test DA) is resizing the image and then take the center crop, The second one (test DA2) is resizing the image, random horizontal shift of the center crop, horizontal flip and color jittering. The last one (train DA) is the train-time data-augmentation as described in the previous paragraph. A comparison of the performance of these data augmentation is made in the section~\ref{sec:resulttables}. The test DA data-augmentation described in this paragraph being the simplest. Therefore test DA is used for all the results reported with ResNet-50 and PNASNet-5-Large in this paper except in Table~\ref{tab:sota} where we use test DA2 to have slightly better performances in order to compare ours results with the state of the art. For ResNeXt-101 32x48d all reported results are obtained with test DA2. We make a comparison of the results obtained between testDA, testDA2 and train DA in section~\ref{sec:resulttables}. \paragraph{The baseline} experiment is to increase the resolution without adaptation. Repeated augmentations already improve the default PyTorch ResNet-50 from 76.2\% top-1 accuracy to 77.0\%. Figure~\ref{fig:accuracyresolution}(left) shows that increasing the resolution at test time increases the accuracy of all our networks. E.g., the accuracy of a ResNet-50 trained at resolution 224 increases from 77.0 to 78.4 top-1 accuracy, an improvement of 1.4 percentage points. This concurs with prior findings in the literature \cite{He2016IdentityMappings}. \begin{figure*}[t] \includegraphics[width=0.45\linewidth]{figs/Accuracy_according_to_the_resolution/Best_accuracy_resolution.pdf}~% \hfill \includegraphics[width=0.45\linewidth]{figs/Accuracy_according_to_the_resolution/Best_accuracy_resolution_fine_tune_BN.pdf} \caption{\label{fig:accuracyresolution} Top-1 accuracy of the ResNet-50 according to the test time resolution. Left: without adaptation, right: after resolution adaptation. The numerical results are reported in Appendix~\ref{sec:resulttables}. A comparison of results without random resized crop is reported in Appendix~\ref{sec:RandomResizedCropEffect}. % } \end{figure*} \subsection{Results} \paragraph{Improvement of our approach on a ResNet-50.} Figure~\ref{fig:accuracyresolution}(right) shows the results obtained after fine-tuning the last batch norm in addition to the classifier. With fine-tuning we get the best results ($79\%$) with the classic ResNet-50 trained at $K_\text{train}=224$. Compared to when there is no fine-tuning, the $K_\text{test}$ at which the maximal accuracy is obtained increases from $K_\text{test}=288$ to $384$. If we prefer to reduce the training resolution, $K_\text{train}=128$ and testing at $K_\text{train}=224$ yields 77.1\% accuracy, which is above the baseline trained at full test resolution without fine-tuning. \paragraph{Multiple resolutions.} To improve the accuracy, we classify the image at several resolutions and average the classification scores. Thus, the training time remains the same but there is a modest increase in inference time compared to processing only the highest-resolution crop. With $K_\text{train}=128$ and $K_\text{test}=[256,192]$, the accuracy is 78.0\%. With $K_\text{train}=224$ and $K_\text{test}=[384,352]$, we improve the single-crop result of 79.0\% to 79.5\%. \paragraph{Application to larger networks.} The same adaptation method can be applied to any convolutional network. In Table~\ref{tab:largenetwork} we report the result on the PNASNet-5-Large and the IG-940M-1.5k ResNeXt-101 32x48d \cite{mahajan2018exploring}. For the PNASNet-5-Large, we found it beneficial to fine-tune more than just the batch-normalization and the classifier. Therefore, we also experiment with fine-tuning the three last cells. By increasing the resolution to $K_\text{test}=480$, the accuracy increases by 1 percentage point. By combining this with an ensemble of 10 crops at test time, we obtain \textbf{83.9\%} accuracy. With the ResNeXt-101 32x48d increasing the resolution to $K_\text{test}=320$, the accuracy increases by 1.0 percentage point. We thus reached \textbf{86.4\%} top-1 accuracy. \def \hspace{11pt} {\hspace{11pt}} \begin{table*} \caption{\label{tab:largenetwork} Application to larger networks: Resulting top-1 accuracy % } \centering {\small \begin{tabular}{cccccc@{\hspace{11pt}}c@{\hspace{11pt}}c@{\hspace{11pt}}c@{\hspace{11pt}}c@{\hspace{11pt}}c} \toprule \multicolumn{1}{c}{Model} &\multicolumn{1}{c}{Train} & \multicolumn{3}{c}{Fine-tuning}& \multicolumn{6}{c}{Test resolution} \\ \cmidrule(lr){3-5} \cmidrule(lr){6-11} used &resolution & Classifier & Batch-norm & Three last Cells & 331 & 384 & 395 & 416 & 448 & 480\\ \cmidrule(lr){1-1} \cmidrule(lr){2-2} \cmidrule(lr){3-5} \cmidrule(lr){6-11} PNASNet-5-Large & 331 & \_ & \_ & \_ & 82.7 & 83.0 & \textbf{83.2} &83.0 & 83.0 & 82.8 \\ PNASNet-5-Large & 331 & \checkmark & \checkmark & \_ & 82.7 & 83.4 & 83.5 & 83.4 &\textbf{ 83.5} & 83.4 \\ PNASNet-5-Large & 331 & \checkmark & \checkmark & \checkmark & 82.7 & 83.3 & 83.4 & 83.5 & 83.6& \textbf{83.7} \\ \midrule & & Classifier & Batch-norm & Three last conv layer & \multicolumn{2}{c}{224} & \multicolumn{2}{c}{288} & \multicolumn{2}{c}{320}\\ % \cmidrule(lr){3-5} \cmidrule(lr){6-11} ResNeXt-101 32x48d & 224 & \checkmark & \checkmark & \_ & \multicolumn{2}{c}{85.4} & \multicolumn{2}{c}{86.1} & \multicolumn{2}{c}{\textbf{86.4}}\\ \bottomrule \end{tabular}} \end{table*} \paragraph{Speed-accuracy trade-off.} \label{sec:timings} We consider the trade-off between training time and accuracy (normalized as if it was run on 1~GPU). The full table with timings are in supplementary Section~\ref{sec:supptimings}. In the initial training stage, the forward pass is 3 to 6 times faster than the backward pass. However, during fine-tuning the ratio is inverted because the backward pass is applied only to the last layers. In the low-resolution training regime ($K_\text{train}=128$), the additional fine-tuning required by our method increases the training time from 111.8~h to 124.1~h (+11\%). This is to obtain an accuracy of 77.1\%, which outperforms the network trained at the native resolution of 224 in 133.9~h. We produce a fine-tuned network with $K_\text{test}=384$ that obtains a higher accuracy than the network trained natively at that resolution, and the training is $2.3\times$ faster: 151.5~h instead of 348.5~h. \begin{table*} \caption{\label{tab:sota} State of the art on ImageNet with ResNet-50 architectures and with all types of architecture (Single Crop evaluation) % % } \centering \small \begin{tabular}{lcccccc} \toprule Models & Extra Training Data &Train & Test & \# Parameters & Top-1 (\%) & Top-5 (\%) \\ \midrule ResNet-50 Pytorch & \_ & 224 & 224 & 25.6M & 76.1 & 92.9\\ ResNet-50 mix up \cite{Zhang2017Mixup} & \_ & 224 & 224 & 25.6M & 77.7 & 94.4\\ ResNet-50 CutMix \cite{Yun2019CutMix} & \_ & 224 & 224 & 25.6M & 78.4 & 94.1\\ ResNet-50-D \cite{Tong2018BagofTricks} & \_ & 224 & 224 & 25.6M & 79.3 & 94.6\\ MultiGrain R50-AA-500 \cite{berman2019multigrain}& \_ & 224 & 500 & 25.6M & 79.4 & 94.8\\ ResNet-50 Billion-scale \cite{Yalniz2019BillionscaleSL} & \checkmark & 224 & 224 & 25.6M & 81.2 & 96.0\\ \midrule Our ResNet-50 & \_ & 224 & 384 & 25.6M & 79.1 & 94.6\\ Our ResNet-50 CutMix & \_ & 224 & 320 & 25.6M & 79.8 & 94.9\\ Our ResNet-50 Billion-scale@160 & \checkmark & 160 & 224 & 25.6M & 81.9 & 96.1\\ Our ResNet-50 Billion-scale@224 & \checkmark & 224 & 320 & 25.6M & 82.5 & 96.6\\ \midrule PNASNet-5 (N = 4, F = 216) \cite{Liu2018PNAS} & \_ & 331 & 331 & 86.1M & 82.9 & 96.2\\ MultiGrain PNASNet @ 500px \cite{berman2019multigrain} & & 331 & 500 & 86.1M & 83.6 & 96.7\\ % AmoebaNet-B (6,512) \cite{Yanping2018GPipe} & \_ & 480 & 480 & 577M & 84.3 & 97.0\\ EfficientNet-B7 \cite{tan2019efficientnet} & \_ & 600 & 600 & 66M & 84.4 & 97.1\\ \midrule Our PNASNet-5 & \_ & 331 & 480 & 86.1M & 83.7 & 96.8 \\ % \midrule ResNeXt-101 32x8d \cite{mahajan2018exploring} & \checkmark & 224 & 224 & 88M & 82.2 & 96.4 \\ ResNeXt-101 32x16d \cite{mahajan2018exploring} & \checkmark & 224 & 224 & 193M & 84.2 & 97.2 \\ ResNeXt-101 32x32d \cite{mahajan2018exploring} & \checkmark & 224 & 224 & 466M & 85.1 & 97.5 \\ ResNeXt-101 32x48d \cite{mahajan2018exploring} & \checkmark & 224 & 224 & 829M & 85.4 & 97.6 \\ \midrule Our ResNeXt-101 32x48d & \checkmark & 224 & 320 & 829M & \textbf{86.4} & \textbf{98.0} \\ \bottomrule \end{tabular} \vspace{-1em} \end{table*} \paragraph{Ablation study.}\label{sec:ablation} We study the contribution of the different choices to the performance, limited to $K_\text{train}=128$ and $K_\text{train}=224$. By simply fine-tuning the classifier (the fully connected layers of ResNet-50) with test-time augmentation, we reach 78.9\% in Top-1 accuracy with the classic ResNet-50 initially trained at resolution 224. The batch-norm fine-tuning and improvement in data augmentation advances it to 79.0\%. The higher the difference in resolution between training and testing, the more important is batch-norm fine-tuning to adapt to the data augmentation. The full results are in the supplementary Section~\ref{sec:resulttables}. \subsection{Beyond the current state of the art} Table~\ref{tab:sota} compares our results with competitive methods from the literature. Our ResNet-50 is slightly worse than ResNet50-D and MultiGrain, but these do not have exactly the same architecture. On the other hand our ResNet-50 CutMix, which has a classic ResNet-50 architecture, outperforms others ResNet-50 including the slightly modified versions. Our fine-tuned PNASNet-5 outperforms the MultiGrain version. To the best of our knowledge our ResNeXt-101 32x48d surpasses all other models available in the literature. With \textbf{86.4\%} Top-1 accuracy and \textbf{98.0\%} Top-5 accuracy it is the first model to exceed 86.0\% in Top-1 accuracy and 98.0\% in Top-5 accuracy on the ImageNet-2012 benchmark~\cite{Russakovsky2015ImageNet12}. It exceeds the previous state of the art~\cite{mahajan2018exploring} by 1.0\% absolute in Top-1 accuracy and 0.4\% Top-5 accuracy. \subsection{Transfer learning tasks} \label{sec:transferlearning} We have used our method in transfer learning tasks to validate its effectiveness on other dataset than ImageNet. We evaluated it on the following datasets: iNaturalist 2017~\cite{Horn2017INaturalist}, Stanford Cars~\cite{Cars2013}, CUB-200-2011~\cite{WahCUB_200_2011}, Oxford 102 Flowers~\cite{Nilsback08}, Oxford-IIIT Pets~\cite{parkhi12a}, NABirds~\cite{Horn2015NaBirds} and Birdsnap~\cite{Berg2014Birdsnap}. We used our method with two types of networks for transfer learning tasks: SENet-154~\cite{Hu2017SENet} and InceptionResNet-V2~\cite{Szegedy2016InceptionResNetV2}. For all these experiments, we proceed as follows. (1) we initialize our network with the weights learned on ImageNet (using models from \cite{pretrainedpytorch}). (2) we train it entirely for several epochs at a certain resolution. (3) we fine-tune with a higher resolution the last batch norm and the fully connected layer. Table~\ref{tab:transfertask} summarizes the models we used and the performance we achieve. We can see that in all cases our method improves the performance of our baseline. Moreover, we notice that the higher the image resolution, the more efficient the method is. This is all the more relevant today, as the quality of the images increases from year to year. \begin{table*} \caption{\label{tab:transfertask} Transfer learning task with our method and comparison with the state of the art. We only compare ImageNet-based transfer learning results with a single center crop for the evaluation (if available, otherwise we report the best published result) without any change in architecture compared to the one used on ImageNet. We report Top-1 Accuracy(\%). } \centering \small \begin{tabular}{llcc|lc} \toprule Dataset & Models & Baseline & With Our Method & \multicolumn{2}{c}{State-Of-The-Art Models} \\ \midrule iNaturalist 2017~\cite{Horn2017INaturalist} & SENet-154 & 74.1 & \textbf{75.4} & IncResNet-V2-SE \cite{Horn2017INaturalist} & 67.3 \\ Stanford Cars~\cite{Cars2013} & SENet-154 & 94.0 & 94.4 & EfficientNet-B7 \cite{tan2019efficientnet} & \textbf{94.7} \\ CUB-200-2011~\cite{WahCUB_200_2011} & SENet-154 & 88.4 & \textbf{88.7} & MPN-COV \cite{Li2017MPN} & \textbf{88.7}\\ Oxford 102 Flowers~\cite{Nilsback08} & InceptionResNet-V2& 95.0 & 95.7 & EfficientNet-B7 \cite{tan2019efficientnet} & \textbf{98.8}\\ Oxford-IIIT Pets~\cite{parkhi12a} & SENet-154 & 94.6 & 94.8 & AmoebaNet-B (6,512) \cite{Yanping2018GPipe} &\textbf{95.9}\\ NABirds~\cite{Horn2015NaBirds} & SENet-154 & 88.3 & \textbf{89.2} & PC-DenseNet-161 \cite{Dubey2017PCDenseNet} & 82.8 \\ Birdsnap~\cite{Berg2014Birdsnap} & SENet-154 & 83.4 & \textbf{84.3}& EfficientNet-B7 \cite{tan2019efficientnet} & \textbf{84.3}\\ \bottomrule \end{tabular} \end{table*} \section{Introduction}\label{sec:introduction} Convolutional Neural Networks~\cite{lecun1989backpropagation} (CNNs) are used extensively in computer vision tasks such as image classification~\cite{Krizhevsky2012AlexNet}, object detection~\cite{ren2015faster}, inpainting~\cite{xie2012image}, style transfer~\cite{gatys2016image} and even image compression~\cite{rippel2017real}. In order to obtain the best possible performance from these models, the training and testing data distributions should match. However, often data pre-processing procedures are different for training and testing. For instance, in image recognition the current best training practice is to extract a rectangle with random coordinates from the image, which artificially increases the amount of training data. This region, which we call the \emph{Region of Classification} (RoC), is then resized to obtain a crop of a fixed size (in pixels) that is fed to the CNN. At test time, the RoC is instead set to a square covering the central part of the image, which results in the extraction of a so called ``center crop''. This reflects the bias of photographers who tend center important visual content. Thus, while the crops extracted at training and test time have the same size, they arise from different RoCs, which skews the distribution of data seen by the CNN. \input{fig-traintestaug} Over the years, training and testing pre-processing procedures have evolved to improve the performance of CNNs, but so far they have been optimized separately~\cite{Ekin2018AutoAugment}. In this paper, we first show that this separate optimization has led to a significant distribution shift between training and testing regimes with a detrimental effect on the test-time performance of models. We then show that this problem can be solved by jointly optimizing the choice of resolutions and scales at training and test time, while keeping the same RoC sampling. Our strategy only requires to fine-tune two layers in order to compensate for the shift in statistics caused by the changing the crop size. This allows us to retain the advantages of existing pre-processing protocols for training and testing, including augmenting the training data, while compensating for the distribution shift. Our approach is based on a rigorous analysis of the effect of pre-processing on the statistics of natural images, which shows that increasing the size of the crops used at test time compensates for randomly sampling the RoCs at training time. This analysis also shows that we need to use lower resolution crops at training than at test time. This significantly impacts the processing time: halving the crop resolution leads to a threefold reduction in the network evaluation speed and reduces significantly the memory consumption for a typical CNN, which is especially important for training on GPUs. For instance, for a target test resolution of 224$\times$224, training at resolution 160$\times$160 provides better results than the standard practice of training at resolution 224$\times$224, while being more efficient. In addition we can adapt a ResNet-50 train at resolution 224$\times$224 for the test resolution 320$\times$320 and thus obtain top-1 accuracy of 79.8\% (single-crop) on ImageNet. Alternatively, we leverage the improved efficiency to train high-accuracy models that operate at much higher resolution at test time while still training quickly. For instance, we achieve an top-1 accuracy of 86.4\% (single-crop) on ImageNet with a ResNeXt-101 32x48d pre-trained in weakly-supervised fashion on 940 million public images. Finally, our method makes it possible to save GPU memory, which could in turn be exploited by optimization: employing larger batch sizes usually leads to a better final performance~\cite{Tong2018BagofTricks}. \section{Conclusion} We have studied extensively the effect of using different train and test scale augmentations on the statistics of natural images and of the network's pooling activations. We have shown that, by adjusting the crop resolution and via a simple and light-weight parameter adaptation, it is possible to increase the accuracy of standard classifiers significantly, everything being equal otherwise. We have also shown that researchers waste resources when both training and testing strong networks at resolution $224\times 224$; We introduce a method that can ``fix'' these networks post-facto and thus improve their performance. An implementation of our method is open-sourced at \url{https://github.com/facebookresearch/FixRes}. \bibliographystyle{plain} \section{Region selection and scale statistics}\label{sec:analysis} \input{fig-pdfresolution} \input{fig-resolution} Applying a Convolutional Neural Network (CNN) classifier to an image generally requires to pre-process the image. One of the key steps involves selecting a rectangular region in the input image, which we call \emph{Region of Classification} (RoC). The RoC is then extracted and resized to a square crop of a size compatible with the CNN{} (e.g.~AlexNet requires a $224\times 224$ crop as input). While this process is simple, in practice it has two subtle but significant effects on how the image data is presented to the CNN{}. First, the resizing operation changes the \emph{apparent size} of the objects in the image (\cref{sec:apparent}). This is important because, differently from translation, CNNs \emph{do not} have a predictable response to a scale change. Second, the choice of different crop sizes (for architectures such as ResNet that admit non-fixed inputs) has an effect on the \emph{statistics} of the network activations, especially after global pooling layers (\cref{sec:prelimactmap}). This section analyses in detail these two effects. In the discussion, we use the following conventions: The ``input image'' is the original training or testing image; the RoC is a rectangle in the input image; and the ``crop'' is the pixels of the RoC, rescaled with bilinear interpolation to a fixed resolution, then fed to the CNN{}. \subsection{Scale and apparent object size}\label{sec:apparent} If a CNN is to acquire a scale-invariant behavior for object recognition, it must \emph{learn} it from data. However, resizing the input images in pre-processing changes the distribution of objects sizes. Since different pre-processing protocols are used at training and testing time% \footnote{ The reason for this difference the following. At training time, the extraction and resizing of the RoC is used as an opportunity to \emph{augment} the data by randomly altering the scale of the objects, in this manner the CNN is stimulated to be invariant to a wider range of object scales. }, the size distribution \emph{differs} in the two cases. This is quantified next. \subsubsection{Relation between apparent and actual object sizes} We consider the following imaging model: the camera projects the 3D world onto a 2D image, so the apparent size of the objects is inversely proportional to their distance from the camera. For simplicity, we model a 3D object as an upright square of height and width $R\times R$ (its depth is irrelevant). The 3D object sits at a distance $Z$ from the camera and is fronto-parallel to it. Hence, its image is a $r \times r$ rectangle, where the \emph{apparent size} $r$ is given by $r=fR/Z$ where $f$ is the \emph{focal length} of the camera. Thus we can express the apparent size as the product $r = f \cdot r_1$ of the focal length $f$, which depends on the camera, and of the variable $r_1=R/Z$, whose distribution $p(r_1)$ is camera-independent. While the focal length is variable, the \emph{field of view} angle $\theta_{\text{FOV}}$ of most cameras is usually in the $[40^\circ, 60^\circ]$ range. Hence, for an image of size $H\times W$ one can write $ f = k\sqrt{HW} $ where $ k^{-1} = 2 \tan (\theta_{\text{FOV}}/2) \approx 1 $ is approximately constant. With this definition for $f$, the apparent size $r$ is expressed in pixels. \subsubsection{Effect of image pre-processing on the apparent object size}\label{s:aug} Now, we consider the effect of rescaling images on the apparent size of objects. If an object has an extent of $r\times r$ pixels in the input image, and if $s$ is the scaling factor between input image and the crop, then by the time the object is analysed by the CNN, it will have the new size of $rs \times rs$ pixels. The scaling factor $s$ is determined by the pre-processing protocol, discussed next. \paragraph{Train-time scale augmentation.} \newcommand{K_\text{train}}{K_\text{train}} \newcommand{K_\text{test}^\text{image}}{K_\text{test}^\text{image}} \newcommand{K_\text{test}}{K_\text{test}} As a prototypical augmentation protocol, we consider \texttt{RandomResizedCrop} in {PyTorch}, which is very similar to augmentations used by other toolkits such as {Caffe} and the original AlexNet. \texttt{RandomResizedCrop} takes as input an $H \times W$ image, selects a RoC at random, and resizes the latter to output a $K_\text{train}\timesK_\text{train}$ crop. The RoC extent is obtained by first sampling a scale parameter $\sigma$ such that $\sigma^2 \sim U([\sigma^2_-,\sigma^2_+])$ and an aspect ratio $\alpha$ such that $\ln \alpha \sim U([\ln\alpha_-,\ln\alpha_+])$. Then, the size of the RoC in the input image is set to $H_\text{RoC}\times W_\text{RoC} = \sqrt{\sigma\alpha HW} \times \sqrt{\sigma HW/\alpha}$. The RoC is resized anisotropically with factors $(K_\text{train}/H_\text{RoC}, K_\text{train}/W_\text{RoC})$ to generate the output image. Assuming for simplicity that the input image is square (i.e.~$H=W$) and that $\alpha=1$, the scaling factor from input image to output crop is given by: \begin{equation}\label{e:randmresized} s = \frac {\sqrt{K_\text{train} K_\text{train}}}{\sqrt{H_\text{RoC} W_\text{RoC}}} % % % % % = \frac{1}{\sigma} \cdot \frac{K_\text{train}}{\sqrt{HW}}. \end{equation} By scaling the image in this manner, the apparent size of the object becomes \begin{equation}\label{e:raug} r_\text{train} = s \cdot r = s f \cdot r_1 = \frac{kK_\text{train}}{\sigma} \cdot r_1. \end{equation} Since $kK_\text{train}$ is constant, differently from $r$, $r_\text{train}$ does \emph{not} depend on the size $H\times W$ of the input image. Hence, pre-processing \emph{standardizes} the apparent size, which otherwise would depend on the input image resolution. This is important as networks do not have built-in scale invariance. \paragraph{Test-time scale augmentation.} As noted above, test-time augmentation usually differs from train-time augmentation. The former usually amounts to: isotropically resizing the image so that the shorter dimension is $K_\text{test}^\text{image}$ and then extracting a $K_\text{test} \times K_\text{test}$ crop (\texttt{CenterCrop}) from that. Under the assumption that the input image is square ($H=W$), the scaling factor from input image to crop rewrites as $s = K_\text{test}^\text{image}/\sqrt{HW}$, so that \begin{equation}\label{e:teaug} r_{\text{test}} = s\cdot r = k K_\text{test}^\text{image} \cdot r_1. \end{equation} This has a a similar size standardization effect as the train-time augmentation. \paragraph{Lack of calibration.} Comparing~\cref{e:raug,e:teaug}, we conclude that the same input image containing an object of size $r_1$ results in two different apparent sizes if training or testing pre-processing is used. These two sizes are related by: \begin{align} \frac{r_{\text{test}}}{r_{\text{train}}} = \sigma \cdot \frac{K_\text{test}^\text{image}}{K_\text{train}}. \label{eq:apparentsizeratio} \end{align} In practice, for standard networks such as AlexNet $K_\text{test}^\text{image}/K_\text{train} \approx 1.15$; however, the scaling factor $\sigma$ is sampled (with the square law seen above) in a range $[\sigma_-, \sigma_+] = [0.28, 1]$. Hence, at testing time the same object may appear as small as a third of what it appears at training time. For standard values of the pre-processing parameters, the expected value of this ratio w.r.t.~$\sigma$ is \begin{equation} \operatorname{E}\left[\frac{r_{\text{test}}}{r_{\text{train}}}\right] = F\cdot \frac{K_\text{test}^\text{image}}{K_\text{train}} \approx 0.80, \qquad F = \frac{2}{3} \cdot \frac{\sigma_+^3 - \sigma_-^3} {\sigma_+^2 - \sigma_-^2}, \label{eq:avgscaleratio} \end{equation} where $F$ captures all the sampling parameters. \subsection{Scale and activation statistics}\label{sec:prelimactmap} In addition to affecting the apparent size of objects, pre-processing also affects the activation statistics of the CNN, especially if its architecture allows changing the size of the input crop. % We first look at the \emph{receptive field size} of a CNN activation in the previous layer. This is the number of input spatial locations that affect that response. For the convolutional part of the CNN, comprising linear convolution, subsampling, ReLU, and similar layers, changing the input crop size is approximately transparent because the receptive field is unaffected by the input size. However, for classification the network must be terminated by a pooling operator (usually average pooling) in order to produce a fixed-size vector. % Changing the size of the input crop strongly affects the activation statistics of this layer. \paragraph{Activation statistics.} We measure the distribution of activation values after the average pooling in a ResNet-50 in~\cref{fig:pdfbatchnormeffect}. As it is applied on a ReLU output, all values are non-negative. At the default crop resolution of $K_\text{test}$\,=\,$K_\text{train}$\,=\,224 pixels, the activation map is 7$\times$7 with a depth of 2048. At $K_\text{test}$\,=\,64, the activation map is only 2$\times$2: pooling only 0 values becomes more likely and activations are more sparse (the rate of 0's increases form 0.5\% to 29.8\%). The values are also more spread out: the fraction of values above 2 increases from 1.2\% to 11.9\%. Increasing the resolution reverts the effect: with $K_\text{test}$\,=\,448, the activation map is 14$\times$14, the output is less sparse and less spread out. This simple statistical observations shows that if the distribution of activations changes at test time, the values are not in the range that the final classifier layers (linear \& softmax) were trained for. \subsection{Larger test crops result in better accuracy}\label{sec:paradox} Despite the fact that increasing the crop size affects the activation statistics, it is generally beneficial for accuracy, since as discussed before it reduces the train-test object size mismatch. For instance, the accuracy of ResNet-50 on the ImageNet validation set as $K_\text{test}$ is changed (see~\cref{sec:experiments}) are: {\footnotesize \ifnips ~ \hfill \begin{tabular}{lrrrrrrrr} \toprule $K_\text{test}$ & 64 & 128 & 224 & 256 & 288 & 320 & 384 & 448 \\ accuracy & 29.4 & 65.4 & 77.0 & 78.0 & 78.4 & 78.3 & 77.7 & 76.6 \\ \bottomrule \end{tabular} \hfill ~ \else \begin{center} \begin{tabular}{lr@{\hspace{10pt}}r@{\hspace{10pt}}r@{\hspace{10pt}}r@{\hspace{10pt}}r@{\hspace{10pt}}r@{\hspace{10pt}}r@{\hspace{10pt}}r@{\hspace{10pt}}} \toprule $K_\text{test}$ & 64 & 128 & 224 & 256 & 288 & 320 & 384 & 448 \\ accuracy & 29.4 & 65.4 & 77.0 & 78.0 & 78.4 & 78.3 & 77.7 & 76.6 \\ \bottomrule \end{tabular} \end{center} \fi } Thus for $K_\text{test}=288$ the accuracy is 78.4\%, which is \emph{greater} than 77.0\% obtained for the native crop size $K_\text{test}=K_\text{train}=224$ used in training. In \cref{fig:accuracyresolution}, we see this result is general: better accuracy is obtained with higher resolution crops at test time than at train time. In the next section, we explain and leverage this discrepancy by adjusting the network's weights. \ifnips \begin{figure*} \begin{minipage}{0.45\linewidth} \includegraphics[width=0.98\linewidth]{figs/Batch_norm_effect/CDF_resolution_effect.pdf} \end{minipage} \hfill \raisebox{1.8em}{ \begin{minipage}{0.48\linewidth} \caption{\label{fig:pdfbatchnormeffect} Cumulative density function of the vectors components on output of the spatial average pooling operator, for a standard ResNet-50 trained at resolution 224, and tested at different resolutions. The distribution is measured on the validation images of Imagenet. } \end{minipage}} \vspace{-0.1em} \end{figure*} \else \begin{figure} \includegraphics[width=0.98\linewidth]{figs/Batch_norm_effect/CDF_resolution_effect.pdf} \caption{\label{fig:pdfbatchnormeffect} Cumulative density function of the vectors components on output of the spatial average pooling operator, for a standard ResNet-50 trained at resolution 224, and tested at different resolutions. The distribution is measured on the validation images of Imagenet. } \end{figure} \fi \section{Related work}\label{sec:related} \paragraph{Image classification} is a core problem in computer vision. It is used as a benchmark task by the community to measure progress. Models pre-trained for image classification, usually on the ImageNet database~\cite{deng2009imagenet}, transfer to a variety of other applications~\cite{oquab2014learning}. Furthermore, advances in image classification translate to improved results on many other tasks~\cite{gordo2017end,Kornblith2018DoBetter}. Recent research in image classification has demonstrated improved performance by considering larger networks and higher resolution images~\cite{Yanping2018GPipe,mahajan2018exploring}. For instance, the state of the art in the ImageNet ILSVRC 2012 benchmark is currently held by the ResNeXt-101 32x48d~\cite{mahajan2018exploring} architecture with 829M parameters using 224$\times$224 images for training. The state of the art for a model learned from scratch is currently held by the EfficientNet-b7~\cite{tan2019efficientnet} with 66M parameters using 600$\times$600 images for training. In this paper, we focus on the ResNet-50 architecture~\cite{He2016ResNet} due to its good accuracy/cost tradeoff (25.6M parameters) and its popularity. We also conduct some experiments using the PNASNet-5-Large~\cite{Liu2018PNAS} architecture that exhibits good performance on ImageNet with a reasonable training time and number of parameters (86.1M) and with the ResNeXt-101 32x48d~\cite{mahajan2018exploring} weakly supervised because it was the network publicly available with the best performance on ImageNet. \paragraph{Data augmentation} is routinely employed at training time to improve model generalization and reduce overfitting. Typical transformations~\cite{Hu2017SENet,berman2019multigrain,Szegedy2015Goingdeeperwithconvolutions} include: random-size crop, horizontal flip and color jitter. In our paper, we adopt the standard set of augmentations commonly used in image classification. As a reference, we consider the default models in the PyTorch library. The accuracy is also improved by combining multiple data augmentations at test time, although this means that several forward passes are required to classify one image. For example, \cite{He2016ResNet,Krizhevsky2012AlexNet,Szegedy2015Goingdeeperwithconvolutions} used ten crops (one central, and one for each corner of the image and their mirrored versions). Another performance-boosting strategy is to classify an image by feeding it at multiple resolutions~\cite{He2016ResNet,Simonyan2015VGG,Szegedy2015Goingdeeperwithconvolutions}, again averaging the predictions. More recently, multi-scale strategies such as the feature pyramid network~\cite{lin2017feature} have been proposed to directly integrate multiple resolutions in the network, both at train and test time, with significant gains in category-level detection. \paragraph{Feature pooling.} A recent approach~\cite{berman2019multigrain} employs $p$-pooling instead of average pooling to adapt the network to test resolutions significantly higher than the training resolution. The authors show that this improves the network's performance, in accordance with the conclusions drawn by Boureau~\emph{et al.}~\cite{Boureau2010Pooling}. Similar pooling techniques have been employed in image retrieval for a few years~\cite{radenovic2018fine,tolias2015particular}, where high-resolution images are required to achieve a competitive performance. These pooling strategies are combined~\cite{tolias2015particular} or replace~\cite{radenovic2018fine} the RMAC pooling method~\cite{tolias2015particular}, which aggregates a set of regions extracted at lower resolutions.
{'timestamp': '2019-07-22T02:07:13', 'yymm': '1906', 'arxiv_id': '1906.06423', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06423'}
arxiv
\section{Introduction}\label{sec:introduction} \IEEEPARstart{T}{he} main objective in large scale and high speed communication networks is the design of a reliable and secure data transmission system. In conventional secure communication systems, channel encoding is used at the physical layer for error correction while encryption is done at a higher layer to make the communication confidential. Nowadays, since many communication devices are constrained in resources or are becoming portable, it is needed to enhance security without increasing computational or hardware complexity. Rao was the first that joined encryption and error correction (based on a linear block code) in a single step \cite{Rao} to resolve the issue in an insecure and unreliable channel efficiently. The main purpose of this scheme is to provide both security and reliable data transmission at the same time using a symmetric-key cryptosystem. Rao defines the proposed cryptosystem based on binary Goppa codes. It is proved that this cryptosystem is not secure against chosen-plaintext attacks. To overcome this weakness, Rao and Nam have introduced a revised symmetric-key cryptosystem \cite{Rao-Nam}, \cite{Rao-Nam2}. In this paper we use RN to abbreviate Rao and Nam cryptosystem. Struik and Tilburg have generalized the RN scheme to any finite field $\mathbb{F}_q$ \cite{STRUIK}. Barbero and Ytrehus have reduced the secret key size of the RN scheme, while maintaining the security level of the system \cite{Barbero-Ytrehus}. The previous proposed RN-like schemes have very large key size or low information rate that makes them impractical. Several schemes have been presented in the literature to modify RN, reduce the key size, increase information rate and improve security against known attacks. Some of them use quasi-cyclic (QC) codes to reduce the key size and use low-density parity-check (LDPC) codes to increase the information rate \cite{Eghlidos}, \cite{Hooshmand-ISC}. Unlike the previous RN-like schemes that scramble, permute or change the codeword bits, the proposed joint schemes based on QC-LDPC codes in \cite{Dakhilalian}, \cite{Esmaeili1} and \cite{Esmaeili2}, randomly puncture the codeword corresponding to a plaintext. The security and the key sizes of these schemes have been significantly improved. Another joint scheme has been proposed based on low-density lattice codes (LDLCs) \cite{LDLC} that has practical decoder \cite{Hooshmand}. All of these RN-like schemes are vulnerable to the message-resent attack \cite{Berson}. It is an interesting idea to consider nonlinear layers for RN-like schemes to provide their resistance against well known chosen plaintext attacks. The RN-like schemes, named SECC (secret error-correcting codes), use nonlinear codes, or block chaining technique to withstand against the chosen plaintext attacks, while retaining the error correction performance \cite{SECC}. ECBC (Error Correction Based Cipher) is another RN-like scheme that uses a nonlinear function $f$ in its structure \cite{ECBC}. In parallel, a differential-style attack (chosen-plaintext attack) against ECBC and SECC has been proposed in \cite{Differential-Cryptanalysis}. It is shown that the non-linear function $f$ used in ECBC is particularly vulnerable to this attack and its secret key is recovered in constant time. The security of \cite{SECC} and \cite{ECBC} is enhanced to resist the differential attack proposed in \cite{Differential-Cryptanalysis} by considering a special design for the nonlinear function $f$ \cite{Deepthi-Nonlinear}. The authors claim that the proposed scheme is the most efficient secure channel coding scheme among the previous code based schemes \cite{Deepthi-Nonlinear}. There is another approach for joining encryption and encoding in a single step. The proposed schemes in this approach use error correcting codes as a replacement of the AES (Advanced Encryption Standard) diffusion layer \cite{HD}, \cite{GLOBECOM}. The message-resend attack \cite{Berson} is not effective on these joint AES-coding schemes. In spite of providing error correction, small key size (equal to AES) and data security against linear and differential attacks, these schemes suffer from higher computational complexities compared to RN-like schemes. In the RN-like schemes, the security is embedded in the channel code to enhance the security of the entire system. They are fast and easy from an implementation standpoint. The earlier RN-like schemes have smaller error correction capability than error correction codes. Indeed, to achieve significant error correction capacity, the schemes' parameters have to be large which lead to large key size and high computational complexity. However, this issue has been resolved in recent RN-like schemes \cite{Deepthi-Nonlinear}. Low power consumption for RN-like schemes is an important advantage that leads us to concentrate on RN-like schemes. This allows us to use the same hardware components for error correction and security. In the conventional joint schemes, modulation is applied on the resulting point that is sent to the channel. In this paper, we propose an alternative secure wireless communication model that uses a coded-modulation scheme based on lattices to design an RN-like scheme to merge encryption, channel encoding and modulation in a single step. Using lattices in designing RN-like schemes is rare due to the high complexity of lattice encoding and decoding even for legitimate users. We use a special type of lattices that provide proper efficiency for the proposed scheme. In general, a digital modulator is used at the output of the channel encoder, which serves as an interface to the communication channels. The modulator produces signal waveforms that transmit information. When treating a channel coding as a separate operation independent of modulation, the coded sequences generally have a smaller channel symbol duration than the uncoded sequences for the same information rate. Accordingly, the power spectral density (PSD) of the channel signals changes essentially. On the other hand, if the modulation is designed in conjunction with the channel coding, error correction can be achieved without leading to any essential changes in the PSD. The advantages of the coded-modulation schemes, that are the schemes in which coding and modulation are combined, are highlighted here. This importance is featured more when designing coding techniques for high-SNR (signal to noise ratio) regimes or bandlimited channels \cite{Ungerboeck}. Therefore, our goal is to use a proper coded-modulation scheme in our cryptosystem to provide a secure communication for high-SNR or bandlimited channels. Based on Shannon's capacity theorem, an optimal block code for a bandlimited additive white Gaussian noise (AWGN) channel consists of a dense packing of the code points within a sphere in a high-dimensional Euclidean space. Lattices and trellis codes are two main categories of packings, for moderate coding gains at moderate complexity \cite{Forney}. Lattices are most of the densest known packings. Construction-A of lattices \cite{conway} are not among the densest packings but define a natural mapping from codewords of the underlying code to lattice points in the Euclidean space. Thus, they are coded-modulation schemes. A lattice code is defined by a lattice $\Lambda$ and a shaping region $B\subset \mathbb{R}^n$, where its codewords are all the lattice points that belong to the shaping region $B$. Lattice codes are a suitable coded-modulation scheme on bandlimited (high-SNR) AWGN channels \cite{Forney}. In this paper, we use a lattice code of some kind of construction-A lattices. LDPC lattices are the first family of modern lattices \cite{sadeghi1, sadeghi2} with practical decoding algorithms in high dimensions \cite{Safarnejad}. It has been shown that these lattices can achieve desirable performance when compared to other modern lattices \cite{Hassan}. A special sub-class of LDPC lattices, QC-LDPC lattices, is a construction-A lattices that have practical encoder as well \cite{QC-LDPC-Lattices}. Due to the easy construction, linear encoding and decoding complexity and good error performance of the QC-LDPC lattices, their lattice codes have the potential to become a practical and efficient coding scheme for the AWGN channel. Furthermore, QC-LDPC lattices have many applications in the wireless communications \cite{Full-Duplex}, \cite{Hassan-ISIT}, as well as in designing symmetric and asymmetric key encryption schemes \cite{Mina}, \cite{Mina-Public}. In this paper, we exploit the characteristics of QC-LDPC lattice codes and the efficiency of this coded-modulations to merge encryption, channel encoding and modulation in a single step. Due to the hardware reuse, such scheme improves the transmission efficiency, reduces the system processing delay and saves in hardware usage. More flexibility in terms of design and technology used for the construction is given, as well. The sparse nature of the parity-check matrix of the QC-LDPC lattices can be exploited to reduce the key size. Moreover, good error performance and linear encoding and decoding (time and space) complexities (in terms of the lattice dimension) of these lattice codes provide an efficient joint scheme that is suitable for secure communication in bandlimited (high-SNR) AWGN channels. This paper is organized as follows. In Section \ref{sec:preliminaries}, we present some lattice notation used in this paper. In Section \ref{sec:Encryption}, a symmetric key encryption scheme based on QC-LDPC lattices is presented. We describe a joint encryption, encoding and modulation scheme based on these lattices in Section \ref{sec:joint encryption}. In Section \ref{sec:Key Size and Complexity}, we give details about the key sizes, computational complexity of encryption and decryption. Section \ref{sec:attacks} is devoted to the security analysis and numerical results related to the security of our scheme against different attacks. The comparison with other RN-like schemes and a summary of the paper are given in Section \ref{sec:Comparison} and Section \ref{sec:Conclusion}, respectively. \section{Preliminaries}~\label{sec:preliminaries} \subsection{Construction of Lattices from Codes} Let $\mathbb{R}^{m}$ be the $m$-dimensional real vector space with Euclidean norm. An $n$-dimensional \emph{lattice} is a discrete additive subgroup of $\mathbb{R}^m$ that is presented by the set of all integer linear combinations of a given basis of $n$ linearly independent vectors in $\mathbb{R}^{m}$ \cite{conway}. Let $\mathbf{b_1},\mathbf{b_2},\dots,\mathbf{b_n}\in \mathbb{R}^m$, be the basis vectors of the lattice $\Lambda$. The \emph{generator matrix} for the lattice is the matrix $\mathbf{B}$, where $\mathbf{b}_i$ is its $i$-th row. Therefore, the lattice $\Lambda$ is defined as $\Lambda=\{\boldsymbol{\xi}\cdot \mathbf{B} | ~\boldsymbol{\xi} \in \mathbb{Z}^{n}\}.$ If $m=n$, the lattice is \emph{full rank}. For more details about lattices and their properties, see \cite{conway}. There are many ways to construct lattices from linear codes; many properties of such lattices can be related to the properties of their underlying codes \cite{conway}. In our work Construction-A of lattices is used that are explained in the sequel. Let $\mathcal{C}=C \left[n, k \right]\subseteq\mathbb{Z}_{p}^n$ be a linear code with dimension $k$ and length $n$, where $p$ is a prime number. A lattice $\Lambda$ constructed from the code $\mathcal{C}$ based on Construction-A is defined by $$\Lambda=p\mathbb{Z}^n+\phi\left(\mathcal{C}\right)=\{p\mathbf{z}+\phi(\mathbf{c}): \mathbf{c}\in \mathcal{C}, \mathbf{z}\in \mathbb{Z}^n\},$$ where $\phi\colon\mathbb{Z}_p^n\rightarrow\mathbb{R}^n$ is the embedding function which maps a vector in $\mathbb{Z}_p^n$ to its real version \cite{conway}. Indeed, Construction-A is a method for generating a lattice by ``lifting'' a linear code $\mathcal{C}$ to the Euclidean space. In this paper, we use binary linear codes and lattices with $p=2$. We consider a subclass of LDPC lattices \cite{sadeghi2} that can be obtained from Construction-A \cite{sadeghi3}. It is interesting to focus on the quasi-cyclic (QC) version of these lattices for cryptographic purposes. \begin{definition} Let $\mathcal{C}=C \left[n, k \right]$ be a binary linear QC-LDPC code. A \emph{QC-LDPC lattice} $\Lambda$ is a lattice based on Construction-A along with a binary linear QC-LDPC code $\mathcal{C}$ which is defined as $\Lambda=\{\mathbf{x}\in \mathbb{Z}^n ~|~ \mathbf{H}_{qc}\cdot{\mathbf x}^T\equiv 0 \;\;(\bmod\,2)\}$, where $\mathbf{H}_{qc}$ is the parity-check matrix of $\mathcal{C}$ \cite{QC-LDPC-Lattices}. \end{definition} The generator matrix of a QC-LDPC lattice $\Lambda$ is the following ${n\times n}$ matrix \begin{equation}~\label{generator matrix} \small \mathbf{G_{\Lambda}}=\left[\begin{array}{cc} \mathbf{I_{k}}& \mathbf{A_{k\times (n-k)}} \\ \mathbf{0_{(n-k)\times k}} & 2\mathbf{I_{n-k}} \end{array}\right]=\left[\begin{array}{ll} \quad \quad \quad\mathbf{G_{\mathcal{C}}} \\ \mathbf{0_{(n-k)\times k}} & 2\mathbf{I_{n-k}} \end{array}\right], \end{equation} where $\mathbf{0}$ stands for the zero block, $\mathbf{I}$ for an identity block and $\mathbf{G_{\mathcal{C}}}=\left[\begin{array}{cc} \mathbf{I_{k}}& \mathbf{A_{k\times (n-k)}} \end{array}\right]_{k\times n}$ is the systematic form of the generator matrix of $\mathcal{C}$ \cite{Hassan}. \subsubsection{Encoding of QC-LDPC lattices}\label{LDPC lattice encoding} Based on a method for encoding Construction-A lattices in \cite{conway}, the encoding of LDPC lattices is introduced in \cite{Hassan} as follows. In order to find a decoding method for these family of lattices, a translated sublattice of lattice $\Lambda$, generated by (\ref{generator matrix}), is considered. First, the codewords' components of the binary code $\mathcal{C}$ are converted into $\pm 1$, that is, $0$ is converted to $-1$ and $1$ is converted to $1$. Then, the set $ \Lambda(\mathcal{C})=\{ \mathbf{c}+4\mathbf{z} \, |\, \mathbf{c}\in \mathcal{C},\,\, \mathbf{z}\in \mathbb{Z}^n\}$, where $\mathcal{C}$ is a QC-LDPC code with $\pm1$ components, is a lattice which is closed under the addition $\bm{\lambda}_1\oplus\bm{\lambda}_2\triangleq\bm{\lambda}_1+\bm{\lambda}_2+(1,\ldots ,1)$, for all $\bm{\lambda}_1,\bm{\lambda}_2\in\Lambda(\mathcal{C})$. Therefore, the encoding algorithm of sublattice $\Lambda(\mathcal{C})$ for any integer row vector $\boldsymbol{\xi}\in \mathbb{Z}^n$ can be done with the generator matrix (\ref{generator matrix}) as $E(\boldsymbol{\xi})= 2 \boldsymbol{\xi}\cdot \mathbf{G_{\Lambda}}-\mathbf{1}$, where $\mathbf{1}=(1,\ldots ,1)$, $E$ is the encoding function and $E(\boldsymbol{\xi})$ is a point of the lattice $\Lambda(\mathcal{C})$ \cite{Hassan}. Let the points of the lattice $\Lambda(\mathcal{C})$ be transmitted over an unconstrained AWGN channel with noise variance $\sigma^2$. Then, its volume-to-noise ratio is defined as $\mbox {VNR}=\frac{4^{(2n-k)/n}}{2\pi e \sigma^2}$. \subsubsection{Decoding of QC-LDPC lattices} Let $\mathbf{x}=\mathbf{c}+4\mathbf{z}$ be the transmitted lattice vector of $ \Lambda(\mathcal{C})$ and $\mathbf{y}=\mathbf{c}+4\mathbf{z}+\mathbf{n}$ be the received vector from the AWGN channel, where $\mathbf{n}\sim \mathcal{N}(0,\sigma^2)$. A soft decision message passing algorithm, that is sum-product algorithm (SPA), is presented in \cite{QC-LDPC-Lattices} for decoding QC-LDPC lattices that has low implementation complexity and memory requirements. These lattices can be decoded in linear time complexity in terms of dimension. \subsection{RDF-QC-LDPC codes} To have efficient decoding and good performance for QC-LDPC codes, their parity-check matrix should be free of length-$4$ cycles. In this paper, we consider QC-LDPC codes with rate $R=(n_0- 1)/n_0$ with parity-check matrix described by \begin{equation}\label{parity check} \mathbf{H}_{qc}=\left[ \begin{array}{c|c|c|c} \mathbf{H}_0 & \mathbf{H}_1 & \cdots & \mathbf{H}_{n_0-1} \end{array} \right], \end{equation} where $\textbf{H}_0, \ldots, \textbf{H}_{n_0-1}$ are $b\times b$ circulant matrices and have low row/column Hamming weight. Some algebraic approaches for code design are possible with this particular form of the parity-check matrix. However, some of them impose constraints on the code length. The proposed techniques based on \emph{Difference Families} (DFs) such as \emph{Extended Difference Families} (EDFs) and \emph{Random Difference Families} (RDFs), loosen the constraints using computer aided procedures \cite{Baldi-book}. Using these techniques and given the number of circulant blocks $n_0$ with column weight $d_v$, the size of the circulant matrices, $b$, is chosen to ensure the absence of length-$4$ cycles in the associated code \cite{Baldi-book}. For $d_v=5$ and $n_0=8$, the size of circulant matrices is $b=187$ by the RDF construction technique \cite{Baldi-book}. Therefore, the RDF-QC-LDPC code with these parameters ($d_v$ and $n_0$) has code length $1496$, dimension $1309$, rate $R = 7/8$ and row weight $d_c = 40$ \cite{Baldi-book}. However, using the same parameters, the size of the circulant matrix for the EDF-based solution is $b > 200$. The minimum length of QC-LDPC code based on EDF technique for $d_v=5$ and $n_0=8$ is $ 1600$ \cite{Baldi-book}. Hence, the RDF-based approach allows to design shorter codes compared to those designed through the EDF approach. Simulation results of symbol error rate (SER) versus VNR of QC-LDPC lattices based on EDF and RDF over the AWGN channel are presented in \figurename~\ref{RDF.EDF-simulation}. According to the results of this figure, RDF based QC-LDPC lattices outperform EDF based QC-LDPC lattices in smaller dimensions. For example, in SER$=10^{-5}$, an RDF based QC-LDPC lattice with parameters $(k,n)=(1309,1496)$, $d_v=5$ and $n_0=8$ has $0.05$dB better performance compared to an EDF based QC-LDPC lattice with $(k,n)=(1407,1608)$, $d_v=5$ and $n_0=8$. \begin{figure}[h] \centerline{\includegraphics[width=3.5in]{Performance_new.pdf}} \caption{Error performance of EDF and RDF based QC-LDPC lattices.}\label{RDF.EDF-simulation} \end{figure} The results of \figurename~\ref{RDF.EDF-simulation} also show that by using underlying codes with higher rates and increasing the $n_0$ value, which results in a decrease of $d_v$ value, we gain a considerable performance improvement. For example, in the SER of $10^{-5}$, using an RDF based QC-LDPC lattice with $(k,n)=(215,258)$, $d_v=3$, $n_0=6$ gives us $0.5$dB performance improvement compared to the same dimension RDF based QC-LDPC lattice with $(k,n)=(128,256)$, $d_v=7$, $n_0=2$. Interesting aspects of the design technique based on RDFs, which is important for cryptographic applications, are generating a large number of equivalent codes with the same code length, dimension and column weight, as well as designing shorter codes compared to those designed based on DFs and EDFs approaches. All these good features and the easy construction of RDF-QC-LDPC codes lead us to use them as the underlying codes used in our lattices. In the rest of this paper, whenever we use a QC-LDPC lattice, we mean that the lattice is constructed using an RDF QC-LDPC code as its underlying code. \section{Symmetric key cryptosystem based on QC-LDPC lattices}~\label{sec:Encryption} In this work, we design a new symmetric key encryption scheme using a special type of lattices, namely QC-LDPC lattices. Defining an appropriate nonlinear function, we enhance the security of the cryptosystem against chosen plaintext attack, differential or linear type attacks. We adapt the method presented in \cite{Function-f} to design an invertible nonlinear mapping $F$ for our encryption scheme where all the operations are performed over the field of real numbers $\mathbb{R}$. In the structure of this mapping, we use some $n\times n$ linear transformations represented by an $n\times n$ binary matrix. We construct the transformation matrices using a companion matrix of a primitive polynomial in $\mathbb{F}_2[x]$ described as follows. The linear transformations corresponding to these invertible matrices are represented by the linear operators $F_0, \ldots, ,F_{2^{d}-1}$, for an integer number $d> 0$. The input vector of the mapping $F$ is $\mathbf{z}=(\mathbf{a}, \mathbf{b})$, where $\mathbf{a}$ is an $n$-tuple vector and $\mathbf{b}$ is a $d$-tuple binary vector. The input to each linear transformation is an $n$-tuple vector $\mathbf{a}$ in which $a_i \in \mathbb{Z}$, for $i=0, \ldots, n-1$. Each linear operator $F_j$, for $j=0, \ldots, 2^{d}-1$, transforms an $n$-tuple input to an $n$-tuple output. Then, the output of the linear transformations are passed through a multiplexer, controlled by the $d$-tuple vector $\mathbf{b}$ which serves as the control line. Indeed, the control line of the multiplexer is used to select one of the outputs of the linear transformations. The overall structure of the mapping is shown in \figurename~\ref{function}. \begin{figure}[h] \begin{center} \definecolor{qqqqff}{rgb}{0.,0.,1.} \begin{tikzpicture}[line cap=round,line join=round,>=triangle 45,x=0.9cm,y=0.9cm] \clip(-5.91331923190833,-1.499142517555464) rectangle (5.161336712460304,5.198171753387659); \draw (-2.36,3.4)-- (-1.08,3.4); \draw (-2.36,3.4)-- (-2.36,2.26); \draw (-1.08,3.4)-- (-1.08,2.26); \draw (-2.36,2.26)-- (-1.08,2.26); \draw (-1.08,2.26)-- (-2.36,2.26); \draw (-1.74,4.02)-- (3.38,4.02); \draw [->] (-1.74,4.02) -- (-1.74,3.4); \draw (-1.72,2.26)-- (-1.72,1.8); \draw (-1.72,1.8)-- (-0.9,1.8); \draw [->] (0.9,4.66) -- (0.9,4.02); \draw (-0.22,3.4)-- (1.06,3.4); \draw (-0.22,3.4)-- (-0.22,2.26); \draw (1.06,3.4)-- (1.06,2.26); \draw (-0.22,2.26)-- (1.06,2.26); \draw (1.06,2.26)-- (-0.22,2.26); \draw [->] (0.42,4.02) -- (0.42,3.4); \draw [->] (0.44,2.26) -- (0.43273,1.24); \draw [->] (-0.9,1.8) -- (-0.8763636363636375,1.238181818181818); \draw (-1.69455,1.24)-- (3.4,1.24); \draw (-1.69455,1.24)-- (-1.694545454545456,0.47454545454545544); \draw (-1.694545454545456,0.47454545454545544)-- (3.4,0.47); \draw [->] (0.9018681224191829,0.4722288828315322) -- (0.9,-0.3364); \draw [->] (-5.1127272727272745,0.8381818181818186) -- (-1.6945476139056432,0.8381817102009543); \draw (-1.5706906030789811,5.1721423537455275) node[anchor=north west] {Input vector $\mathbf{a}$ ($n$-tuple)}; \draw (-5.41260123786735745,1.393416069659905) node[anchor=north west] {Control vector $\mathbf{b}$}; \draw (-1.2451582767810327,-0.46615985416359645) node[anchor=north west] {Output vector $F(\mathbf{a},\mathbf{b})$}; \draw (1.4527153927969545,2.828523576088912) node[anchor=north west] {$...$}; \draw (1.4527153927969545,1.8785228323964707) node[anchor=north west] {$...$}; \draw (-2.003670291701091,3.131715302799265) node[anchor=north west] {$F_0$}; \draw (0.058033449929322176,3.091289739237885) node[anchor=north west] {$F_1$}; \draw (0.28037404951691575,1.2285220887040296) node[anchor=north west] {MUX}; \draw (-4.6026078701825297,0.867883743361959) node[anchor=north west] { ($d$-tuple)}; \draw (2.744254148228917,3.44)-- (4.024254148228916,3.44); \draw (2.744254148228917,3.44)-- (2.744254148228917,2.3); \draw (4.024254148228916,3.44)-- (4.024254148228916,2.3); \draw (2.744254148228917,2.3)-- (4.024254148228916,2.3); \draw (4.024254148228916,2.3)-- (2.744254148228917,2.3); \draw [->] (3.3842541482289166,4.02) -- (3.3842541482289157,3.44); \draw (3.404254148228917,2.3)-- (3.404254148228917,1.8); \draw (3.404254148228917,1.8)-- (2.5042541482289167,1.8); \draw [->] (2.5042541482289167,1.8) -- (2.5188041482289165,1.24); \draw (2.5188041482289165,1.24)-- (3.404254148228917,1.23818); \draw (3.404254148228917,1.23818)-- (3.4097041482289168,0.47); \draw (2.8473973356645867,3.192353648141336) node[anchor=north west] {$F_{2^d -1}$}; \draw (0.061225176639677,-0.9512666169001621) node[anchor=north west] { ($n$-tuple)}; \end{tikzpicture} \caption{The structure of nonlinear mapping $F$.} \label{function} \end{center} \end{figure} In this paper, we construct the corresponding matrices for the linear transformations used in the architecture of $F$ based on the following mathematical method. In this architecture, the applied linear transformations need to have maximal period. Indeed, the corresponding matrix $\mathbf{U}$ should have maximal order, that is, $\mathbf{U}^{2^n -1}=\mathbf{I}$, where $\mathbf{I}$ is the $n\times n$ identity matrix, and $\mathbf{U}^{m}\neq\mathbf{I}$, for $m< 2^n -1$. Let $g\in \mathbb{F}_q[x]$ be a nonzero polynomial of degree $n\geq 1$. If $g(0) \neq 0$, the order of $g$ is the least positive integer $e$, $1\leq e \leq q^n -1$, such that $g(x)| x^e -1$ and it is denoted by $ord(g)$ \cite{Daniel-Book}. It is known that the order of a primitive polynomial $g$ of degree $n$ is equal to $q^n -1$. Let $g(x)=x^n+a_{n-1}x^{n-1}+\cdots +a_{1}x+a_0$, where $a_0\neq 0$, Then, $C(g)$ is the companion matrix of $g$ as \begin{equation*}\label{c(f)} \small C(g)=\left[ {\begin{array}{ccccc} 0 & 1 & 0 & \cdots & 0 \\ 0 & 0 & 1 & \cdots & 0 \\ \vdots & \vdots & \vdots & \ddots & 0 \\ 0 & 0 & 0 & \cdots & 1 \\ - {a_0} & - {a_1} & - {a_2} & \cdots & - {a_{n-1}} \\ \end{array}} \right]_{n\times n}. \end{equation*} Since $\det(C(g)) = (-1)^n a_0$ and $g(0)=a_0\neq 0$, the companion matrix of $g$ is an invertible matrix, that is, $C(g)\in GL_n(q)$ \cite{Darafsheh}. Furthermore, the order of the polynomial $g$ is related to the order of companion matrix \cite{Darafsheh}. It can be verified that the order of $C(g)$ as an element of $GL_n(q)$ is equal to the order of $g$. It can be shown that the inverse of a companion matrix of the polynomial $g(x)=x^n+a_{n-1}x^{n-1}+a_{n-2}x^{n-2}+\cdots +a_{1}x+a_0$ is a companion matrix of the polynomial $r(x)=x^n+\frac{a_{1}}{a_0}x^{n-1}+\frac{a_{2}}{a_0}x^{n-2}+\cdots +\frac{a_{n-1}}{a_0}x+\frac{1}{a_0}$. Let us consider a primitive polynomial $g\in \mathbb{F}_2[x]$ of degree $n$ with $g(0) \neq 0$. Therefore, the order of its corresponding companion matrix satisfies $ord(C(g))=ord(g)=2^n -1$ and $\det(C(g)) = (-1)^n$. We use this companion matrix $C(g)$ that is a binary low dense matrix of maximum order $2^n -1$ to construct a nonlinear function $F$ for our proposed scheme. For simplicity we write $C(g)=\mathbf{U}$ in the sequel. Then, the set $\mathrm{S}=\{\mathbf{I}, \mathbf{U}, \mathbf{U}^2, \ldots, \mathbf{U}^{2^{n}-2}\}$ contains $2^n -1$ invertible binary matrices of dimension $n\times n$. The mapping $F$ is obtained using $2^d$ linear transformations from the set $\mathrm{S}$ indicated by the linear transformations $F_0, \ldots, ,F_{2^{d}-1}$. As a consequence, $F:\mathbb{Z}^{n+d}\longrightarrow \mathbb{Z}^{n}$ is a mapping defined by $F\big(\mathbf{a}, \mathbf{b}\big)=F_{\alpha}(\mathbf{a})=\mathbf{a}\mathbf{U}^{\alpha}$, where $\alpha=\sum_{i=0}^{d-1}{b_i 2^i}\in \{0, 1, \ldots, 2^{d}-1\}$ is determined by the vector $\mathbf{b}$ as the control line of the multiplexer. The public set $\mathrm{S}$ and a secret control line $\mathbf{b}$ of the multiplexer define this function. On the other hand, the output $F(\mathbf{a}, \mathbf{b})=\{f_1(\mathbf{a}, \mathbf{b}), \ldots, f_n(\mathbf{a}, \mathbf{b})\}$ is the concatenation of the output of $2^d$ linear operators selected according to the logic of multiplexer \cite{Function-f}. Each component function can be written mathematically as \begin{align}\label{function-F} f_i(\mathbf{a}, \mathbf{b})\equiv \mathop \bigoplus \nolimits_{j = 0}^{{2^d} - 1} {D_j }(\mathbf{b}){\mathbf{u}_{ji}}(\mathbf{a}) ~ (\textrm{mod} ~2), \end{align} where $\mathbf{u}_{ji}$ is the $i$th row of the matrix $\mathbf{U}^{j}$, and $D_j(\cdot)$ is a function defined as $D_j(\mathbf{b})=D_\sigma(\mathbf{b})= ({{\bar i}_1} \oplus {b_1}) \cdots ({{\bar i}_d} \oplus {b_d}) $ over $ \sigma = ({i_1}\,, \ldots ,\,{i_d})$ which is the binary representation of $j$ and $\bar v$ is the complement of $v$. In a similar way \cite{Function-f}, it can be proved that the algebraic degree of each component function of the proposed mapping $F$ and their nonzero linear combinations is $d+1$. \subsection{Key generation}\label{key generation} Encryption is done using the following secret keys that are chosen by the authorized transmitter and receiver. \begin{enumerate} \item A random regular $(n=n_0b, k=(n_0-1)b, d_c)$-QC-LDPC code constructed from RDFs with a parity-check matrix of size $(n-k)\times n$ in the form of (\ref{parity check}) and constant row weight $d_c$. This RDF-QC-LDPC code with the parity-check matrix $\mathbf{H}_{qc}$ is used to construct a QC-LDPC lattice (according to the previous section). \item A vector $\mathbf{s}$ as $l_1$-bit initial value (seed) of a linear feedback shift register (LFSR) which is described using a polynomial $q$. We use this LFSR to produce an $n$-tuple intentional error vector $\mathbf{e}$ in the scheme. For reducing the key size and increasing the period of the resultant keystream, we use a reseeding mechanism for this LFSR at the end of each period. This mechanism uses the modular division circuit with a different polynomial $p$ for another LFSR of the same length proposed in \cite{Modulation-circuit}. With a proper selection of the polynomials $q$ and $p$, the period of the LFSR is equal to $(2^{l_1} - 1)^2$. Since, the output of each period of the LFSR is a vector with approximately $(2^{l_1} - 1)$ bits, then the length of the LFSR should be selected in such a way that the message length $n$ is close to the period of LFSR, that is, $(2^{l_1} - 1)\approx n$. Therefore, we consider $l_1=\lceil \log_2 n \rceil$ which implies $(2^{l_1} - 1)^2\approx n^2$. Using this procedure, we can produce $n$ different pseudorandom binary vectors $\mathbf{e}_i$, $i=1, \ldots, n$, of length $n$ for the encryption algorithm. \item An $n\times n$ block diagonal permutation matrix $\mathbf{P}=\textrm{diag}(\boldsymbol{\pi}_1 ,\ldots ,\boldsymbol{\pi}_v)$ formed by ${q\times q}$ sub-matrices $\boldsymbol{\pi}_i$, for $i=1, \ldots, v$, where $v=n/q$. The diagonal elements $\boldsymbol{\pi}_i$'s are permutation sub-matrices, so the Hamming weight of each row and column is one. We control $q\times q$ sub-matrices $\boldsymbol{\pi}_i$, for $i=1, \ldots, v$, by $v$ different initial values for an LFSR of length $ \lceil\log_2 q\rceil$. We describe it in Section \ref{sec-key-size}. Since, the sub-matrices $\boldsymbol{\pi}_i$s are saved instead of the permutation matrix $\mathbf{P}$, it is needed to save only the corresponding initial value of the LFSR. We concatenate these initial values and store them in a vector $\mathbf{t}$ of length $l_4=v \lceil\log_2 q\rceil$ bits as a key. \item An $l_2$-bit initial vector $\mathbf{h}$ of an LFSR that controls the multiplexer in the construction of the nonlinear mapping $F$. The vector $\mathbf{h}$ serves as the control line and the multiplexer outputs one of the outputs of the linear transformations according to this control line. \end{enumerate} Let $d_v$ denote the number of nonzero elements in each row/column of $\mathbf{H}_i$ in $\mathbf{H}_{qc}$, thus the row weight of $\mathbf{H}_{qc}$ is $d_c=n_0d_v$. Let $\mathbf{H}_{n_0-1}$ be non-singular, particularly, this implies that $d_v$ is odd. Then, the systematic generator matrix of this QC-LDPC code is \begin{eqnarray}\label{G-qc} \mathbf{G_{\mathcal{C}}}=\left[\begin{array}{c|c} \mathbf{I_{k}}\qquad & \begin{array}{c} (\mathbf{H}_{n_0-1}^{-1}\mathbf{H}_0)^T \\ (\mathbf{H}_{n_0-1}^{-1}\mathbf{H}_1)^T \\ \vdots\\ (\mathbf{H}_{n_0-1}^{-1}\mathbf{H}_{n_0-2})^T \end{array} \end{array}\right]_{k\times n}, \end{eqnarray} where $[\, \cdot \,]^T$ denotes the transposition operation. Then, the generator matrix $\mathbf{G_{\Lambda}}$ of the corresponding QC-LDPC lattice is obtained by replacing it in Eq. (\ref{generator matrix}). Since each circulant matrix $\mathbf{H_i}$, for $i=0, \ldots, n_0-1$, is completely described by its first row, the QC-LDPC code with parity-check matrix (\ref{parity check}) is given by the first row of these circulant blocks. Therefore, we save the first row of $\mathbf{H}_{qc}$ instead of the entire matrix. \subsection{Encryption Algorithm} To encrypt a message $\mathbf{m} \in \mathbb{Z}^{n}$, an intentional pseudorandom error vector $\mathbf{e}\in \mathbb{F}_2^{n}$ is generated using the LFSR with the secret initial value $\mathbf{s}$ and the reseeding mechanism. This error vector of length $n$ has an arbitrary Hamming weight. Then, the ciphertext is computed as follows \begin{align*} \mathbf{y}&=\Big(2F\big((\mathbf{m}+\mathbf{\overline{e}}), \mathbf{h}\big) \mathbf{G_{\Lambda}}-\mathbf{1}+2\mathbf{e}\Big)\mathbf{P}\\ &=\Big(2\mathbf{x} \mathbf{G_{\Lambda}}-\mathbf{1}+2\mathbf{e}\Big)\mathbf{P}, \end{align*} where $\mathbf{\overline{e}}$ is the complement of the vector $\mathbf{e}$ in $\mathbb{F}_2$. The nonlinear function $F$ maps the intentionally corrupted message $(\mathbf{m}+\mathbf{\overline{e}})$ to the vector $\mathbf{x}=F\big((\mathbf{m}+\mathbf{\overline{e}}), \mathbf{h}\big)=(\mathbf{m}+\mathbf{\overline{e}})\mathbf{U}^{\alpha}$, in which $\alpha=\sum_{i=0}^{d-1}{h_i 2^i}$ and $\mathbf{h}$ is the secret control line of the employed multiplexer in $F$. Indeed, the ciphertext $\mathbf{y}$ is the permutation of the lattice point $\boldsymbol{\tilde{\lambda}}=2\mathbf{x} \mathbf{G_{\Lambda}}-\mathbf{1}$ which has been perturbed by the vector $2\mathbf{e}$. In general, the $j$th instance of the ciphertext $ \mathbf{y}_j$ ($j\geq 1$) corresponds to the $j$th instance of the plaintext $ \mathbf{m}_j$ as follows \begin{align*} \mathbf{y}_j&=\Big(2F\big((\mathbf{m}_j+\mathbf{\overline{e}}_{(j)_{N_e}}), \mathbf{h}_{(j)_{N_h}}\big) \mathbf{G_{\Lambda}}-\mathbf{1}+2\mathbf{e}_{(j)_{N_e}}\Big)\mathbf{P}_{(j)_{N_p}}, \end{align*} where $(j)_{N}$ is considered as $j \mod N$. The numbers $N_e, N_h$ and $N_p$ express the total possibilities of the intentional error vector $\mathbf{e}$, the multiplexer select logic $\mathbf{h}$ and the permutation matrix $\mathbf{P}$, respectively. Indeed, the vectors $\mathbf{e}$ and $\mathbf{h}$ and the permutation matrix $\mathbf{P}$ are changed corresponding to the output of the used LFSRs in their producing process. For simplicity, in the following, we ignore their subscripts. As each lattice point $\boldsymbol{\tilde{\lambda}}=2\mathbf{x} \mathbf{G_{\Lambda}}-\mathbf{1}$ is a vector with odd components, we must add $2\mathbf{e}$ instead of $\mathbf{e}$ as intentional error vector in the encryption process. Otherwise, $2\mathbf{x} \mathbf{G_{\Lambda}}-\mathbf{1}+\mathbf{e}$ is a vector with some even components that reveals the perturbed positions. Moreover, based on Section \ref{LDPC lattice encoding}, each lattice point in $\Lambda(\mathcal{C})$ can be expressed as a vector of the form $\mathbf{c}+4\mathbf{z}$, where $\mathbf{c}\in \mathcal{C}$ (converted into $\pm 1$) and $\mathbf{z}\in \mathbb{Z}^n$. When we add the vector $2\mathbf{e}$ to a lattice point in the encryption process, we get \begin{equation*} \mathbf{c}+4\mathbf{z}+2\mathbf{e}= \mathbf{c'}+4\mathbf{z'}, \end{equation*} where $\mathbf{c'}$ is a vector with components $\pm 1$ and $\mathbf{z'}\in \mathbb{Z}^n$. Hence, $\boldsymbol{\tilde{\lambda}}+2\mathbf{e}$ is another lattice point that gives no information about the intentional error vector $\mathbf{e}$. \subsection{Decryption Algorithm} For decryption, the authorized receiver must be aware of the intentional error vector $\mathbf{e}$ that the transmitter uses by encrypting each plaintext. In addition, both the authorized receiver and transmitter need to use the same LFSR with the same seed $\mathbf{s}$ as a part of the secret key. Therefore, if they use the modular division circuit for generating the pseudorandom error vector $\mathbf{e}$ simultaneously, they can use the same error vector $\mathbf{e}$ for encryption and decryption. Hence, the decryption is done by employing the following steps: \begin{enumerate} \item Multiply the ciphertext $\mathbf{y}$ by $\mathbf{P}^{-1}=\mathbf{P}^{T}$ and get \begin{equation*} \mathbf{y'}= \mathbf{y}\mathbf{P}^{T}=2\mathbf{x} \mathbf{G_{\Lambda}}-\mathbf{1}+2\mathbf{e}. \end{equation*} \item Subtract $2\mathbf{e}$ from $\mathbf{y'}$ to get $2\mathbf{x} \mathbf{G_{\Lambda}}-\mathbf{1}$. \item Recover the vector $\mathbf{x}=F\big((\mathbf{m}+\mathbf{\overline{e}}), \mathbf{h}\big)$ by adding the vector $\mathbf{1}$ to $\mathbf{y'}-2\mathbf{e}$ and multiplying the result by $\frac{1}{2}\mathbf{G^{-1}_{\Lambda}}$, where \begin{equation*} \mathbf{G^{-1}_{\Lambda}}=\left[\begin{array}{cc} \mathbf{I_{k}}& -\frac{1}{2}\mathbf{A_{k\times (n-k)}} \\ \mathbf{0_{(n-k)\times k}} & \frac{1}{2}\mathbf{I_{(n-k)}} \end{array}\right]. \end{equation*} \item Apply the inverse of the function $F$ on $\mathbf{x}$ using the secret vector $\mathbf{h}$ and recover the intentionally corrupted message vector $\mathbf{m}'=\mathbf{m}+\mathbf{\overline{e}}$. \item Retrieve the original message $\mathbf{m}$ by computing $\mathbf{m}'-\mathbf{\overline{e}}$. \end{enumerate} We can use this system for communication in which the ciphertext is transmitted over a noisy channel. This entails some modifications to our cryptosystem to present a joint scheme that can process encryption, channel coding and modulation in a single step which is discussed in the next section. \section{The proposed Joint Encryption, channel coding and modulation scheme}~\label{sec:joint encryption} In this section, we use QC-LDPC lattices to introduce a joint scheme to provide secure communication over bandwidth-limited (high-SNR) AWGN channels. For communications over a noisy power constrained AWGN channel, the encoding operation must be accompanied by a shaping method. This prevents the transmission power of a codeword from being unnecessarily increased. Indeed, we make sure that only lattice points that belong to a shaping region are actually used. Then, instead of mapping the message vector $\mathbf{m}$ to the lattice point $\mathbf{m}\mathbf{G_{\Lambda}}$ in $\Lambda$, it should be mapped to another lattice point $\mathbf{m'}\mathbf{G_{\Lambda}}$, belonging to the shaping region. Some known shaping methods in the literature are hypercube shaping, Voronoi shaping and spherical shaping. In theoretical approaches, the infinite lattice is intersected with a spherical shaping to produce a power-constrained lattice code. Due to the high computational complexity of this shaping, we consider an efficient hypercube shaping algorithm that has minimum complexity among other shaping methods for QC-LDPC lattices to obtain finite lattice constellations \cite{Full-Duplex}. Thus, we choose a signal constellation formed by a QC-LDPC lattice together with a hypercube shaping region for process of the mapping. Indeed, each message is modulated to one of the constellation points using QC-LDPC lattice encoding and a suitable shaping method. \subsection{The Proposed Encryption Algorithm}~\label{encrption-joint} The ciphertext of the proposed symmetric key encryption scheme is in the following form: \begin{equation}\label{joint-encryption-eq} \mathbf{y}=\Big(2F\big((\mathbf{m}+\mathbf{\overline{e}}), \mathbf{h}\big) \mathbf{G_{\Lambda}}-\mathbf{1}+2\mathbf{e}\Big)\mathbf{P}. \end{equation} All operations, such as applying the function $F$ on $\mathbf{m}'=\mathbf{m}+\mathbf{\overline{e}}$ and computing the lattice point $\boldsymbol{\tilde{\lambda}}=2\mathbf{x} \mathbf{G_{\Lambda}}-\mathbf{1}$, and so on, are computed over the real numbers $\mathbb{R}$. Therefore, the resulting ciphertext $\mathbf{y}$ may have large components, even if we restrict the message components. While transmitting the ciphertext over a noisy power constrained AWGN channel, the encrypting operation must be accompanied by a shaping method. In this way, the vector $\boldsymbol{\tilde{\lambda}}$ is limited to a region around the origin that leads to the reduction of ciphertext transmission power. On the other hand, the matrices $\mathbf{U}^{i}$s ($i=0, \ldots, 2^n-2$) in the set $S$ have no structure and may be dense enough. We have observed that some columns in $\mathbf{U}^{i}$s are all one vectors. Therefore, even by applying a shaping method on $\mathbf{x}=F(\mathbf{m}', \mathbf{h})=\mathbf{m}'\mathbf{U}^{\alpha}$, where $\alpha=\sum_{i=0}^{d-1}{h_i 2^i}$, the vector $\mathbf{x}$ may be mapped into a big hypercube with high complexity. Thus, we restrict the components of the input integer vector $\mathbf{m}$ to the following finite constellation before shaping: \begin{eqnarray}\label{constelation} m_{2i} \in \left\{x\in\mathbb{Z}\,\left|\, -L_{i}\leq x\leq -1 \right.\right\}, \,\,\, i=1,\ldots, n/2,\\ m_{2i-1} \in \left\{x\in\mathbb{Z}\,\left|\, 0\leq x\leq L_{i}-1 \right.\right\}, \,\,\, i=1,\ldots, n/2,\nonumber \end{eqnarray} where $L_i$'s are positive integers. In this way, $-L_{i}\leq m'_{2i}\leq 0$ and $0\leq m'_{2i-1}\leq L_{i}$, for $i=1,\ldots, \frac{n}{2}$. Therefore, the vector $\mathbf{x}$ in the worst case lies in an $n$-dimensional hypercube around the origin such that $x_{i}\in \{x\in\mathbb{Z}\, | \, -\frac{n}{2}L_{i} \leq x\leq \frac{n}{2}L_{i} \}$. In our proposed scheme, it is desirable to design an optimal finite constellation for the entries of $\mathbf{m}$ such that the sizes of the entries of $\mathbf{x}=\mathbf{m}'\mathbf{U}^{\alpha}$ become as small as possible. Designing such constellation could be an interesting problem for future work. In the next step, we compute the lattice point $\boldsymbol{\lambda}=\mathbf{x}\mathbf{G_{\Lambda}}$ in the encryption process. Since all operations are performed over real numbers, the entries of $\mathbf{x}\mathbf{G_{\Lambda}}$ can also be large. Therefore, to make the scheme practical, we use a hypercube shaping method to keep the corresponding entries of the ciphertext vector as small as possible. Indeed, instead of mapping the vector $\mathbf{x}$ to the lattice point $\boldsymbol{\lambda}=\mathbf{x}\mathbf{G_{\Lambda}}$ in the infinite lattice $\Lambda$, it is mapped to a lattice point $\boldsymbol{\lambda}'=\mathbf{x'}\mathbf{G_{\Lambda}}$ inside an $n$-dimensional hypercube such that $|\lambda_i'|\leq nL_i-1$, for $i=1,\ldots, n$. In the first step we enforce that $-\frac{n}{2}L_{i}\leq x_i\leq \frac{n}{2}L_{i}$, for $i=1,\ldots ,n$. Therefore, the needed restriction condition of the input vector to a finite constellation for the shaping algorithm is satisfied. Thus, we consider a new lattice point \begin{equation}\label{shaped-vector} \boldsymbol{\lambda}'=\mathbf{x'}\mathbf{G_{\Lambda}}=(\mathbf{x}-\mathbf{z}\mathbf{L})\mathbf{G_{\Lambda}}, \end{equation} instead of $\boldsymbol{\lambda}=\mathbf{x}\mathbf{G_{\Lambda}}$, where $\mathbf{L}=\textrm{diag}(nL_1-1,\ldots ,nL_n-1)$ is an $n\times n$ diagonal matrix. The vector $\mathbf{z}$ is an integer vector of length $n$ that is chosen such that the new lattice point components lie in an $n$-dimensional hypercube around the origin \cite{Full-Duplex}. To find the vector $\mathbf{z}$, we first solve the system of linear equations obtained from (\ref{shaped-vector}) and then choose an integer $\mathbf{z}$ such that $|\lambda_i'|\leq nL_i-1$, for $i=1,\ldots ,n$. Therefore, we have \begin{equation*} \lambda_i'= \left\{ \begin{array}{cc} x_i-z_i(nL_i -1) & i=1,\ldots ,k, \\ 2(x_i-z_i(nL_i -1)) +\sum_{j=1}^{k}x'_j a_{j,i-k}, & i=k+1,\ldots ,n, \end{array} \right. \end{equation*} where $a_{ji}$ is the $(j,i)$-th entry of the matrix $\mathbf{A}$ in $\mathbf{G_{\Lambda}}$. We consider $z_i=0$, for $1\leq i \leq k$ that leads to $x'_i=x_i$ and $|\lambda_i'|=|x_i|\leq nL_i-1$. Moreover, for $k+1\leq i \leq n$, we have $-nL_i+1\leq 2(x_i-z_i(nL_i -1)) +\sum\nolimits_{j=1}^{k}x_j a_{j,i-k} \leq nL_i-1$, or $-\frac{1}{2}+\frac{x_i}{nL_i -1}+\frac{\sum_{j=1}^{k}x_j a_{j,i-k}}{2(nL_i -1)} \leq z_i \leq \frac{1}{2} +\frac{x_i}{nL_i -1} +\frac{\sum_{j=1}^{k}x_j a_{j,i-k}}{2(nL_i -1)}$. The above interval contains only one integer number, thus it has the unique solution $z_i=\left\lfloor \frac{1}{nL_i-1} \left(x_i+ \frac{1}{2}\sum_{j=1}^{k}a_{j,i-k}x_j\right)\right\rceil$. Indeed, we convert the vector $\mathbf{x}$ to $\mathbf{x'}=\mathbf{x}-\mathbf{z}\mathbf{L}$, in order to embed the vector $\boldsymbol{\lambda}'=\mathbf{x'}\mathbf{G_{\Lambda}}$ to the following hypercube \begin{eqnarray}\label{shaping-region} \small \mathcal{L}= \left\{x\in\mathbb{Z}^n\left|\begin{array}{cc} -\frac{n}{2}L_{i}\leq x_i\leq \frac{n}{2}L_{i} & i=1,\ldots, k, \\ -nL_{i}+1 \leq x_i\leq nL_{i}-1 & i=k+1,\ldots, n \end{array} \right.\right\}. \end{eqnarray} Replacing $\mathbf{x}$ by the converted vector $\mathbf{x}'$, in the relation (\ref{joint-encryption-eq}), the transmitted vector over the noisy AWGN channel is expressed as $\mathbf{y}=(2 \mathbf{x'}\mathbf{G_{\Lambda}}-\mathbf{1}+2\mathbf{e})\mathbf{P}$. The encryption algorithm is shown in \figurename~\ref{block-diagram}. The information rate of a lattice code $\Gamma$ of length $n$ (in bits/symbol) is defined to be $R=\log_2(|\Gamma|)/n$ \cite{LDLC}. Since the points of the lattice code $\Gamma=\left(2\Lambda\cap\mathcal{L}\right) \mathbf{-1}$ are in bijective correspondence with the information integer vectors $\mathbf{m}$, according to Eq.(\ref{constelation}), the information rate of this lattice code is $R=\sum_{i=1}^{n}\log_2 (2L_i)/n$. \begin{figure}[h] \centerline{\includegraphics[width=9in]{Block-diagram.pdf}} \caption{The proposed joint encryption, encoding and modulation scheme based on QC-LDPC lattice codes}\label{block-diagram} \end{figure} \subsection{The Proposed Decryption Algorithm} The authorized receiver (Bob) attempts to decrypt the possibly erroneous received vector $\mathbf{r}=(2 \mathbf{x'}\mathbf{G_{\Lambda}}-\mathbf{1}+2\mathbf{e})\mathbf{P}+\mathbf{e}_{ch}$, where $\mathbf{e}_{ch}$ is the AWGN channel noise that is drawn from an i.i.d. Gaussian distribution with variance $\sigma^2$. Using the secret keys $ \{\mathbf{s}, \mathbf{h}, \mathbf{H}_{qc}, \mathbf{t}\}$, the ciphertext is decrypted as follows: \begin{enumerate} \item The received vector $\mathbf{r}$ is multiplied by $\mathbf{P}^{-1}=\mathbf{P}^{T}$ to get \begin{equation*} \mathbf{r'}= \mathbf{r}\mathbf{P}^{T}= (2 \mathbf{x'}\mathbf{G_{\Lambda}}-\mathbf{1}+2\mathbf{e})+\mathbf{e}_{ch}\mathbf{P}^{T}. \end{equation*} \item Having the secret vector $\mathbf{s}$, the corresponding error vector $\mathbf{e}$ and $\mathbf{r''}=\mathbf{r'}-2\mathbf{e}$ are computed. \item The vector $\mathbf{r''}=2\mathbf{x'} \mathbf{G_{\Lambda}}-\mathbf{1}+\mathbf{e}_{ch}\mathbf{P}^{T}$ is decoded using $\mathbf{H}_{qc}$ by applying the SPA iterative decoding algorithm of QC-LDPC lattices \cite{QC-LDPC-Lattices}. Then $\boldsymbol{\tilde{\lambda}}'=2\mathbf{x'}\mathbf{G_{\Lambda}}-\mathbf{1}$ is obtained. \item The vector $\mathbf{x}$ is recovered from the shaped lattice point $\boldsymbol{\tilde{\lambda}}'$ using Algorithm \ref{unshape}. \begin{algorithm} \begin{algorithmic}[1] \small \Procedure{MOD}{$\boldsymbol{\tilde{\lambda}}', (L_1,\ldots ,L_n), \mathbf{G^{-1}_{\Lambda}}$} \State $\mathbf{x'} \gets \left\lfloor\left(\frac{\boldsymbol{\tilde{\lambda}}'+\mathbf{1}}{2}\right)\mathbf{G^{-1}_{\Lambda}}\right\rceil$ \For{$i=1:n$} \If{$\bmod(x'_i, (nL_i-1))< \frac{n}{2}L_{i}$} \State $r_i\gets \bmod(x'_i, (nL_i-1))$ \Else{} \State $r_i\gets \bmod(x'_i, (nL_i-1))-(nL_i-1)$ \EndIf \EndFor \State \textbf{return} $\mathbf{x}=(r_1,\ldots ,r_n)$. \EndProcedure \end{algorithmic} \caption{Recover original vector} \label{unshape} \end{algorithm} \normalsize \item Retrieving the vector $\mathbf{m'}=\mathbf{m}+\mathbf{\overline{e}}$ from the vector $\mathbf{x}=\mathbf{m'}\mathbf{U}^{\alpha}$ is equivalent to computing $\mathbf{m'}=\mathbf{x}(\mathbf{U}^{\alpha})^{-1}$ by the secret vector $\mathbf{h}$, in which $\alpha=\sum_{i=0}^{d-1}{h_i 2^i}$. Then, subtracting the vector $\mathbf{\overline{e}}$ from $\mathbf{m'}$ recovers the original message $\mathbf{m}$. \end{enumerate} \section{Efficiency}~\label{sec:Key Size and Complexity} The efficiency of the cryptosystem is measured in terms of the key size and the computational complexity of encryption and decryption processes. \subsection{Complexity}\label{complexity} Encryption is performed by computing $\mathbf{m}'=\mathbf{m}+\mathbf{\overline{e}}$, then mapping it to the vector $\mathbf{x}=\mathbf{m}'\mathbf{U}^{\alpha}$ by the function $F$ through a multiplexer controlled by the binary vector $ \mathbf{h}$. The vector $\mathbf{x}$ is converted to the vector $\mathbf{x}'$ using a hypercube shaping method and then encoded by a QC-LDPC lattice to a lattice point $\boldsymbol{\tilde{\lambda}}'=2\mathbf{x'}\mathbf{G_{\Lambda}}-\mathbf{1}$. By adding the intentional error vector $2\mathbf{e}$ and multiplying the whole combination by the permutation matrix $\mathbf{P}$, the overall system becomes non-systematic. Therefore, an estimation of the computational complexity, caused by the encryption algorithm is given as \begin{align*}\label{encryption complexity} C_{encrypt}=& C_{add}(\mathbf{\overline{e}})+ C_{compute}(F(\mathbf{m}', \mathbf{h}))+C_{shaping}(\mathbf{x}\mathbf{G_{\Lambda}}) + C_{encode}(\mathbf{x}')+C_{add}(2\mathbf{e})+ C_{product}\big(\mathbf{P}\big). \end{align*} In the encryption process, the terms $ C_{add}(\mathbf{\overline{e}})$, $C_{add}(2\mathbf{e})$ and $C_{product}\big(\mathbf{P}\big)$ have lower order complexity, which are linear, than other terms. Indeed, the complexity of the encryption process is upper-bounded by the complexity of $ C_{compute}(F((\mathbf{m}+\mathbf{\overline{e}}) , \mathbf{h}))+C_{shaping}(\mathbf{x}\mathbf{G_{\Lambda}})+C_{encode}(\mathbf{x}')$. The time and space complexities of QC-LDPC lattice encoding are linear in terms of the dimension of lattice \cite{QC-LDPC-Lattices}. The overall computational complexity of the hypercube shaping for a $\boldsymbol{\lambda}=\mathbf{x}\mathbf{G_{\Lambda}} \in \Lambda$ is $O(n w_c)$, where $w_c$ is the average number of nonzero elements in a row of $\mathbf{G_{\Lambda}}$ \cite{Hassan}. Since $F(\mathbf{m}', \mathbf{h})=\mathbf{m}'\mathbf{U}^{\alpha}$, where $\alpha=\sum_{i=0}^{d-1}{h_i 2^i}$, then $C_{compute}(F(\mathbf{m}', \mathbf{h}))$ is equal to the computational complexity of vector $\mathbf{m}'=(\mathbf{m}+\mathbf{\overline{e}})$ times matrix $\mathbf{U}^{\alpha}$. The function can be implemented using a similar pipelined architecture proposed in \cite{Function-f}. Let $\alpha=h_0+2h_1+2^2 h_2+\cdots+2^{d-1}h_{d-1}$, then $\mathbf{U}^{\alpha}=\mathbf{U}^{h_0}\cdot(\mathbf{U}^2)^{h_1}\cdot(\mathbf{U}^{2^2})^{h_2} \cdots (\mathbf{U}^{2^{d-1}})^{h_{d-1}}$, where $h_i$s are $0$ or $1$. Indeed, the proposed function can be implemented using the matrices $\mathbf{U}, \mathbf{U}^2, \ldots, \mathbf{U}^{2^{d-1}}$ and $d$ number of 2-to-1 multiplexers instead of all matrices ($2^d$ numbers) in $S$ and one $2^d$-to-$1$ multiplexer. Therefore, its computational complexity is of order $O(n^2)$. As a consequence, the complexity of the encryption process is of order $O(n^2)$, in terms of lattice dimension $n$. Since, we have $d$ stages in the pipeline, the latency of the architecture is $O(d)$. Using similar arguments, the decryption complexity is expressed as \begin{align*} C_{decrypt}=&C_{product}\big(\mathbf{P}^T\big)+C_{add}(-2\mathbf{e})+C_{decode}(\mathbf{r''}) + C_{MOD}(\boldsymbol{\tilde{\lambda}}')+C_{compute}(F^{-1}(\mathbf{x}))+C_{add}(-\overline{\mathbf{e}}). \end{align*} Since the dominant terms that have much larger effect on the implementation complexity are $C_{decode}(\mathbf{r''})$, $ C_{MOD}(\boldsymbol{\tilde{\lambda}}')$ and $C_{compute}(F^{-1}(\mathbf{x}))$, the decryption complexity is upper-bounded by the complexity of $C_{decode}(\mathbf{r''})+ C_{MOD}(\boldsymbol{\tilde{\lambda}}')+C_{compute}(F^{-1}(\mathbf{x}))$. The QC-LDPC lattice decoding has computational complexity of $O(n d_v I)$, where $I$ is the maximum number of iterations required by the decoding algorithm to correct the error and $d_v $ is the column weight of the parity-check matrix $\mathbf{H}_{qc}$. Hence, QC-LDPC lattices have linear computational complexity in the lattice dimension \cite{QC-LDPC-Lattices}. The information integer components $x_i$ are recovered from $x'_i$ after multiplication by the matrix $\mathbf{G^{-1}_{\Lambda}}$ followed by a simple modulo operation that is explained in Algorithm \ref{unshape}. Therefore, $C_{MOD}(\boldsymbol{\tilde{\lambda}}')=C_{mult}(\mathbf{G^{-1}_{\Lambda}})$, where according to the structure of $\mathbf{G^{-1}_{\Lambda}}$, it can be demonstrated that it is equal to complexity of the encoding algorithm of QC-LDPC lattices which is linear in terms of lattice dimension. The computational complexity of applying $F^{-1}(\mathbf{x})$ is equivalent to multiplication of the matrix $(\mathbf{U}^{\alpha})^{-1}$ to the vector $\mathbf{x}$. In the same way, its computational complexity is of order $O(n^2)$. Hence, the total computational complexity for decryption is bounded by $O(n^2)$. The complexity of computing the nonlinear function $F$ and $F^{-1}$ is a bottleneck for our scheme. Indeed, we had to sacrifice the linear complexity of our design to prevent some chosen plaintext attacks like differential attack against the proposed scheme. However, designing another nonlinear function which can be implemented with linear complexity is desirable and open for further research. \subsection{Message expansion} According to Section \ref{encrption-joint}, the shaped vectors $2\mathbf{x'} \mathbf{G_{\Lambda}}-\mathbf{1} \in 2\Lambda-\mathbf{1}$ are uniformly distributed over the hypercube $2\mathcal{L}-\mathbf{1}$, where $\mathcal{L}$ is presented in Eq. (\ref{shaping-region}). Therefore, the ciphertext $\mathbf{y}=(2 \mathbf{x'}\mathbf{G_{\Lambda}}-\mathbf{1}+2\mathbf{e})\mathbf{P}$ belongs to the following set \small \begin{eqnarray}\label{Hypercube-region} \left\{x\in\mathbb{Z}^n\left|\begin{array}{cc} -nL_{i}-1\leq x_i\leq nL_{i}+1 & i=1,\ldots, k, \\ -2nL_{i}+1 \leq x_i\leq 2nL_{i}-1 & i=k+1,\ldots, n \end{array} \right.\right\}. \end{eqnarray} \normalsize For simplicity, we consider $L_i = L$, for $i=1,\ldots, n$. Then, the information rate of our cryptosystem is $R=\log_2(2L)$. Furthermore, according to Eq. (\ref{constelation}), the integer vector $\mathbf{m}$ is restricted to the finite constellation $m_i \in \left\{-L,\ldots, L-1 \right\}$, for $i=1,\ldots, n$. Therefore, the plaintext size is at most $n\lceil\log_2(2L)\rceil$ bits and the number of bits required to derive a ciphertext is $(n-k)\lceil\log_2(4nL-1)\rceil +k\lceil\log_2(2nL+3)\rceil$. Therefore, the message expansion of our cryptosystem is \begin{IEEEeqnarray*}{rCl}\label{message expansion} \small \frac{(n-k)\lceil\log_2(4nL-1)\rceil +k\lceil\log_2(2nL+3)\rceil}{n\lceil\log_2(2L)\rceil}. \end{IEEEeqnarray*} If we consider the parameters $n_0=6$, $d_v=3$ and $b=43$ that introduce a QC-LDPC lattice with $(k, n)=(215, 258)$, this ratio approaches $1$ as $L$ approaches infinity. Moreover, the message expansion of our cryptosystem, belongs to the interval $[1, 5.6]$, for $L\geq 2$ and the proposed parameters. \subsection{Key size}\label{sec-key-size} The secret key that needs to be exchanged between the sender and authorized receiver consists of an initial value $\mathbf{s}$ of the $l_1$-bit LFSR for generating the error vector $\mathbf{e}$, the parity-check matrix $\mathbf{H}_{qc}$ for decoding of QC-LDPC lattices, the $d$-bit vector $\mathbf{h}$ that determines the selection logic of the multiplexer for nonlinear mapping $F$, and the vector $\mathbf{t}$ correspond to the permutation matrix $\mathbf{P}$. In the proposed encryption scheme, the random error vector $\mathbf{e}$ is generated using an $l_1$-bit LFSR along with a modular division circuit proposed in \cite{Modulation-circuit}. Therefore, we store the initial vector $\mathbf{s}$ of the LFSR that requires a memory of approximately $l_1=\lceil\log_2 n\rceil$ bits. The required memory for saving the vector $\mathbf{h}$ is $l_2$ bits. We consider it in order for the cryptosystem to be secure against different cryptanalysis. Here we consider it of size approximately $7\lceil\log_2 n\rceil$. To save the secret key $\mathbf{H}_{qc}$, we can just save the nonzero positions of the first rows of $(\mathbf{H}_i)_{b\times b}$, for $i=0, \ldots, n_0-1$, and keep it as the secret parity-check matrix. Thus, its storage involves at most $l_3=d_v\lceil\log_2 b\rceil n_0$ memory bits, where $d_v$ is the row/column Hamming weight of $\mathbf{H}_i$, for $i=0, \ldots, n_0-1$. We use an efficient hardware structure for the permutation of a vector that is based on a shift register and some multiplexers \cite{Deepthi-Nonlinear}. By this method, for different message blocks, we generate different permutation matrices. Under this low hardware complexity, we can reduce the key size of the scheme compared to other joint schemes as well as be secure against known attacks. \begin{figure}[h] \centerline{\includegraphics[width=4in]{Permutation-implement.jpg}} \caption{Hardware design for vector permutation by the matrix $\mathbf{P}$.}\label{Permutation-implement} \end{figure} The designed hardware structure for permuting a vector by $\mathbf{P}$, is shown in \figurename~\ref{Permutation-implement} that serves a buffer, an LFSR and some $q$-to-$1$ multiplexers. In this structure, an LFSR of size $\gamma=\lceil\log_2 q\rceil$ generates data control line of the $q$-to-$1$ multiplexers. For permuting the $n$-tuple vector $\boldsymbol{\lambda}''=2 \mathbf{x'}\mathbf{G_{\Lambda}}-\mathbf{1}+2\mathbf{e}$ in the last step of the encryption process, we divide it into $q$-tuple vectors $\boldsymbol{\lambda}''_i$, for $i=1, \ldots, v$. Then, the first $q$-tuple vector $\boldsymbol{\lambda}''_1$ is stored in the buffer and is given as the input of the $q$-to-$1$ multiplexers. Each component of $\boldsymbol{\lambda}''_i$ belongs to the hypercube defined in Eq. (\ref{Hypercube-region}). Therefore, each component can be considered with maximum $r=\lceil\log_2(4nL-1)\rceil$ bits. Then, we need $r$ multiplexers with $q$ inputs in order to the $r$ bits of each component of $\boldsymbol{\lambda}''_i$ be permuted simultaneously and result in the same component after permutation. In this way, according to the control line generated by the LFSR, the multiplexers select one of the bits from the input vector $\boldsymbol{\lambda}''_{1_j}$, for $j=1, \ldots, q$, as the output. By the next output of the LFSR, the multiplexer selects another component of the input vector. Finally, the $q$-tuple vector $\boldsymbol{\lambda}''_1$ is permuted at the end of the first period of the LFSR which is $2^{\gamma}-1= q$, where $\gamma$ is the size of the initial vector. Then, the second $q$-tuple vector $\boldsymbol{\lambda}''_2$ is stored in the buffer and the initial value of the LFSR is changed. In the same way, $\boldsymbol{\lambda}''_2$ is permuted after reaching the period of the LFSR. Therefore, each of $\boldsymbol{\lambda}''_i$, for $i=1, \ldots, v$, is permuted at the end of a period of the LFSR. Indeed, each permutation matrix $\boldsymbol{\pi}_i$, for $i=1, \ldots, v$, is controlled by the corresponding initial vector of the LFSR to determine the selection logic of the multiplexers. Since the $q\times q$ permutation sub-matrices $\boldsymbol{\pi}_i$, for $i=1, \ldots, v$, are saved instead of the permutation matrix $\mathbf{P}$, it is needed to save only the corresponding initial vector of the LFSR. Thus, the required memory bits for storing the permutation matrix $\mathbf{P}$ is $l_4=v \lceil\log_2 q\rceil$ bits. Hence, the actual key length of the proposed cryptosystem is equal to $l_1+l_2+l_3+l_4=\lceil\log_2 n\rceil + 7\lceil\log_2 n\rceil +d_v\lceil\log_2 b\rceil n_0+ v \lceil\log_2 q\rceil$ bits. For the proposed QC-LDPC lattice with $(k, n)=(215, 258)$ and parameters $n_0=6$, $d_v=3$ and $b=43$, we can choose $q=43$ for the permutation matrix $\mathbf{P}$ and $l_2=61$ for the vector $\mathbf{h}$. Therefore, the key size of the proposed scheme is equal to $214$ bits. This key size is small comparing with those of the proposed code and lattice based cryptography. We summarize the operation characteristics of the proposed scheme in terms of its parameters in \tablename~\ref{table2}. \begin{table}[!ht] \caption{Operation characteristics of the proposed scheme.} \centering \begin{tabular}{|c||c|} \hline Plaintext size (bit) & $n\lceil\log_2(2L)\rceil$ \\ \hline Ciphertext size (bit) & $(n-k)\lceil\log_2(4nL-1)\rceil +k\lceil\log_2(2nL+3)\rceil$ \\ \hline \hspace{-0.4 cm} Key size (bit) & $8\lceil\log_2 n\rceil +d_v\lceil\log_2 b\rceil n_0+ v \lceil\log_2 q\rceil$ \\ \hline Information rate & $R=\log_2(2L)$ \\ \hline Decryption Ops. & $O(n^2)$ \\ \hline Encryption Ops. & $O(n^2)$ \\ \hline \end{tabular} \label{table2} \end{table} \section{Security of the proposed Scheme}~\label{sec:attacks} In general, security of the RN-like cryptosystems is considered against four potential attacks reported in the literature including brute force attack, differential-style attack \cite{Differential-Cryptanalysis}, Rao-Nam attack \cite{Rao-Nam}, Struik-Tilburg attack \cite{STRUIK} and message-resend attack \cite{Berson}. The last three attacks are performed based on the linearity of the encoding step in the encryption process. They are not applicable here because the use of the nonlinear function $F$ in the encryption algorithm prevents such attacks from being successful. Rao-Nam attack is applied on any RN-like cryptosystems to estimate the encryption matrix from a large set of plaintext-ciphertext pairs \cite{Rao-Nam}. The security of the RN-like schemes against this kind of attacks depends mostly on the Hamming weight of the intentional error vectors. This attack succeeds only if the ratio of the Hamming weight of the intentional error vector over $n$ is small and it does not if its average Hamming weight is approximately $ n/2$ \cite{Rao-Nam}. According to the applied method for producing the intentional error $\mathbf{e}$ in our scheme, it has the Hamming weight $ n/2$ on average. In this method, the length of $\mathbf{e}$ is equal to the period of the LFSR. Indeed, the output string (one cycle) of the LFSR is considered as the intentional error $\mathbf{e}$. On the other hand, applying the nonlinear function $F$ on the plaintext before its encoding, does not allow to estimate the encryption matrix from a large set of plaintext-ciphertext pairs. Therefore, Rao-Nam attack can not be applied on the proposed scheme. Struik-Tilburg attack requires enciphering an arbitrary message $\mathbf{m}$ until all distinct ciphertexts are obtained \cite{STRUIK}. This attack is based on deriving the rows of the encryption matrix $\mathbf{G_{\Lambda}}$ by constructing unit vectors from the chosen plaintext or by solving a set of linear equations. The proposed scheme is not vulnerable to Struik-Tilburg attack and message-resent attack \cite{Berson}, because the plaintext is transformed by means of an invertible and nonlinear function $F$ before its encoding. It is known that the security of nonlinear cryptosystems is determined by the intentionally random error vectors and the nonlinear function $F$ \cite{Differential-Cryptanalysis}. Indeed, the encoding step and the permutation step increase further the security of the nonlinear system. The main attack against nonlinear cryptosystems is a differential-style attack that is a chosen plaintext attack \cite{Differential-Cryptanalysis}. In the sequel, the security of the proposed cryptosystem is analyzed against Brute-Force and Differential attacks. \subsection{Brute-Force Attacks} The purpose of this attack is the enumeration of all possible secret keys $ \{\mathbf{s}, \mathbf{h}, \mathbf{H}_{qc}, \mathbf{t}\}$ in the proposed scheme until a meaningful message is obtained. \begin{enumerate} \item The matrix $\mathbf{H}_{qc}$ is the parity-check matrix (free of length-$4$ cycles) of an RDF-QC-LDPC code with code rate $R=(n_0- 1)/n_0$, code length $n=bn_0$ and column weight $d_v$. An attacker looks for the parity-check matrix corresponding to the used RDF-QC-LDPC code having public parameters $b, d_v, n_0$. For large enough parameters $b$ and $n_0$, it has been demonstrated that there are a large number of different RDF-QC-LDPC codes with the same code length, dimension and row/column weight of the parity-check matrices \cite{Baldi-book}. The number of different QC-LDPC codes free of length-$4$ cycles with the parameters $b, d_v, n_0$ that can be designed through the RDF-based approach, is lower bounded by \cite[Theorem 4.12]{Baldi-book} \begin{align*} N_{RDF}(& b, d_v, n_0) \ge \frac{1}{b}{b\choose d_v}^{n_0}\prod\limits_{l = 0}^{{n_0} - 1} {\prod\limits_{j = 1}^{{d_v} - 1} {\frac{b}{{b - j}}} } - \frac{{j\left[ {2 - b\,\bmod \,2 + ({j^2} - 1)/2 + l \cdot {d_v} \cdot ({d_v} - 1)} \right]}}{{b - j}}. \end{align*} For the proposed parameter $b=43, d_v=3$ and $n_0=6$, there are $2^{61}$ different RDF-QC-LDPC codes with $n=258$ and code rate $R=5/6$. \item We use an LFSR with $l_1=\lceil\log_2 n\rceil$-bit initial vector and a modular division circuit to generate the vector $\mathbf{e}$. With a suitable choice of the feedback polynomial used in the circuit, the total choice of random vector $\mathbf{e}$ is $(2^{l_1}-1)^2\approx (2^{\lceil\log_2 n\rceil})^2$. For our example, this number is approximately equal to $2^{18}$. \item The $l_2$-bit vector $\mathbf{h}$ determines the image of the nonlinear mapping $F$. The total number of the different vectors $\mathbf{h}$ is $2^{l_2}$ that is $2^{61}$, for our cryptosystem. \item Each permutation matrix $\boldsymbol{\pi}_i$, for $i=1, \ldots, v$, of the block diagonal permutation matrices $\mathbf{P}$ is controlled by different initial vectors of the LFSR of size $\lceil\log_2 q\rceil$. The number of different initial vectors for this LFSR is $2^{\lceil\log_2 q\rceil}$. Therefore, there are $2^{\lceil\log_2 q\rceil}$ different candidates for each $\boldsymbol{\pi}_i$, for $i=1, \ldots, v$. Hence, the total number of different permutation matrices $\mathbf{P}$ is equal to $\left(2^{\lceil\log_2 q\rceil}\right)^v$, that is approximately $2^{36}$ for $q=43$ and $v=6$. \end{enumerate} Consequently, the complexity of the brute force attack is approximately $2^{176}$ which indicates a high order of security. \subsection{Differential Cryptanalysis} The $j$th instance of the ciphertext in our cryptosystem is considered as \begin{align*} \mathbf{y}_j&=\Big(2F\big((\mathbf{m}_j+\mathbf{\overline{e}}_{(j)_{N_e}}), \mathbf{h}_{(j)_{N_h}}\big) \mathbf{G_{\Lambda}}-\mathbf{1}+2\mathbf{e}_{(j)_{N_e}}\Big)\mathbf{P}_{(j)_{N_p}}, \end{align*} which varies with the number of clock cycles. The first round of the encryption is only used in the chosen plaintext attack proposed in \cite {Differential-Cryptanalysis}. Indeed, the ciphertexts are computed for each message after resetting the encryption machine. Since, an attacker call $\mathbf{y}_1$ for different chosen plaintexts, the subscripts of $ \mathbf{m}_i$ and $\mathbf{y}_i$ are ignored for the time being and $ \mathbf{m}^{(i)}$ and $ \mathbf{y}^{(i)}$ represent the plaintext and the corresponding ciphertext used in the $i$th call of $\mathbf{y}_1$. In our scheme, $ \mathbf{y}^{(\beta)}$, for $\beta=0, \ldots, 2^l$, is considered as the $\beta$th instance of the ciphertext corresponding to the plaintext $ \mathbf{m}^{(\beta)}$ as follows \begin{equation*} \mathbf{y}^{(\beta)}= \Big(2\left(F\big((\mathbf{m}^{(\beta)}+\mathbf{\overline{e}}_1), \mathbf{h}_1\big) \right)'\mathbf{G_{\Lambda}}-\mathbf{1}+2\mathbf{e}_1\Big)\mathbf{P}_1. \end{equation*} This attack has three steps: estimate the permuted generator matrix $\mathbf{G_{\Lambda}}\mathbf{P}_1$, recover the intentional vector $\mathbf{e}_1$, and decode the ciphertext. In the first step, the attacker computes the ciphertext corresponding to the first round of the encryption for the binary plaintext $ \mathbf{m}^{(\beta)}$, for $\beta=0, \ldots, 2^l$, in which the last $(n-k)$ bit of message is equal to zero. Since, \begin{align*} \mathbf{y}^{(\beta)}&=\Big(2 \mathbf{x'}^{(\beta)}\mathbf{G_{\Lambda}}-\mathbf{1}+2\mathbf{e}_1\Big)\mathbf{P}_1\\ &=\Big(2 (\mathbf{x}^{(\beta)}-\mathbf{z}\mathbf{L})\mathbf{G_{\Lambda}}-\mathbf{1}+2\mathbf{e}_1\Big)\mathbf{P}_1, \end{align*} the attacker computes \begin{align*} \mathbf{y}^{(\beta)} ~ (\textrm{mod}~ \mathbf{L})&=\left(2 \mathbf{x}^{(\beta)}\mathbf{G_{\Lambda}} -\mathbf{1}+2\mathbf{e}_1\right)\mathbf{P}_1\\ &=\left(2F((\mathbf{m}^{(\beta)}+\mathbf{\overline{e}}_1), \mathbf{h}_1) \mathbf{G_{\Lambda}}-\mathbf{1}+2\mathbf{e}_1\right)\mathbf{P}_1. \end{align*} Then, for $\beta=0, \ldots, 2^l$, the attacker has \begin{align*} \mathbf{v}^{(\beta)}=\dfrac{\mathbf{y}^{(\beta)}~ (\textrm{mod}~ \mathbf{L})+\mathbf{1}}{2} = F((\mathbf{m}^{(\beta)}+\mathbf{\overline{e}}_1), \mathbf{h}_1) \mathbf{G_{\Lambda}}\mathbf{P}_1+\mathbf{e}_1\mathbf{P}_1. \end{align*} Indeed, the attacker computes \begin{align*} \mathbf{v}^{(i)}= F((\mathbf{m}^{(i)}+\mathbf{\overline{e}}_1), \mathbf{h}_1) \mathbf{G_{\Lambda}}\mathbf{P}_1+\mathbf{e}_1\mathbf{P}_1, \end{align*} for $i=1, \cdots, 2^l$, to obtain \begin{align*} \sum\nolimits_{\beta= 1}^{{2^l}} {\mathbf{v}^{(\beta)}}&=\sum\nolimits_{\beta= 1}^{{2^l}} {F((\mathbf{m}^{(\beta)}+\mathbf{\overline{e}}_1), \mathbf{h}_1) \mathbf{G_{\Lambda}}\mathbf{P}_1+\mathbf{e}_1\mathbf{P}_1}\\ &=\sum\nolimits_{\beta= 1}^{{2^l}} {F((\mathbf{m}^{(\beta)}+\mathbf{\overline{e}}_1), \mathbf{h}_1) \mathbf{G_{\Lambda}}\mathbf{P}_1}+ \sum\nolimits_{\beta= 1}^{{2^l}} {\mathbf{e}_1\mathbf{P}_1}. \end{align*} On the other hand, according to Eq. (\ref{generator matrix}), we have \begin{align*} F((\mathbf{m}^{(\beta)}+\mathbf{\overline{e}}_1), \mathbf{h}_1)& \mathbf{G_{\Lambda}}\mathbf{P}_1 = F((\mathbf{m}^{(\beta)}+\mathbf{\overline{e}}_1), \mathbf{h}_1)_{[1:k]}\mathbf{G_{\mathcal{C}}}\mathbf{P}_1 +F((\mathbf{m}^{(\beta)}+\mathbf{\overline{e}}_1), \mathbf{h}_1)_{[k+1:n]} \left[\begin{array}{cc} \mathbf{0} & 2\mathbf{I_{n-k}} \end{array}\right]\mathbf{P}_1, \end{align*} where $\mathbf{G_{\mathcal{C}}}$ is the systematic form of the generator matrix of the used QC-LDPC code (Eq. (\ref{G-qc})) and $\mathbf{x}_{[1:k]}$ denotes the entries $1$ to $k$ of the vector $\mathbf{x}$. Therefore, recovering $\mathbf{G_{\mathcal{C}}}$ is sufficient for determining the $\mathbf{G_{\Lambda}}$ and the attacker has the following steps to recover $\mathbf{G_{\Lambda}}\mathbf{P}_1$ \begin{align} \sum\nolimits_{\beta= 1}^{{2^l}} {\mathbf{v}^{(\beta)}} \nonumber &\equiv\left(\sum\nolimits_{\beta= 1}^{{2^l}} {F'((\mathbf{m}^{(\beta)}+\mathbf{\overline{e}}_1), \mathbf{h}_1)} \right) \mathbf{G_{\mathcal{C}}}\mathbf{P}_1 ~ (\textrm{mod} ~ 2) \end{align} where $F'(\mathbf{a}, \mathbf{b})=\{f_1(\mathbf{a}, \mathbf{b})~(\textrm{mod} ~2), \ldots, f_k(\mathbf{a}, \mathbf{b})~(\textrm{mod} ~2)\}$ and $f_i(\mathbf{a}, \mathbf{b})~ (\textrm{mod} ~2)$'s are the Boolean functions defined in Eq. (\ref{function-F}). The algebraic degree of each component function and their nonzero linear combination is $d+1$ \cite{Function-f}. Therefore, the algebraic degree of function $F'$ is equal to $d+1$. Let $L[\mathbf{\mathfrak{u}}_{1}, \ldots, \mathbf{\mathfrak{u}}_{l}]$ be the list of all $2^l$ possible linear combinations of $\mathbf{\mathfrak{u}}_{1}, \ldots, \mathbf{\mathfrak{u}}_{l}$ where $\mathbf{\mathfrak{u}}_{i}\in \mathbb{F}_2^n$ is a vector with a $1$ in the $i$th position and zeros in all the other positions. We recall that the $l$th derivative of a Boolean function $f(\mathbf{x})$ is defined as $\Delta^{(l)}_{\mathbf{\mathfrak{u}}_{i_1}, \ldots,\mathbf{\mathfrak{u}}_{i_l}} f(\mathbf{x})= \sum\nolimits_{c \in L[\mathbf{\mathfrak{u}}_{1}, \ldots, \mathbf{\mathfrak{u}}_{l}]} {f(\mathbf{x} + \mathbf{c})} $ \cite{Higher-order-derivatives}. Therefore, since $ \mathbf{m}^{(\beta)}$s are binary vectors with zero components in the last $(n-k)$ positions, \small \begin{align} \sum\nolimits_{\beta= 1}^{{2^l}} {\mathbf{v}^{(\beta)}} ~ (\textrm{mod} ~ 2)\nonumber &=\left(\sum\limits_{\mathbf{m}^{(\beta)}\in L[\mathbf{\mathfrak{u}}_{i_1}, \ldots, \mathbf{\mathfrak{u}}_{i_l}]} {F'((\mathbf{m}^{(\beta)}+\mathbf{\overline{e}}_1), \mathbf{h}_1)} \right) \mathbf{G_{\mathcal{C}}}\mathbf{P}_1\\ \label{differential-attack} &=\left( \Delta^{(l)}_{\mathbf{\mathfrak{u}}_{i_1}, \ldots, \mathbf{\mathfrak{u}}_{i_l}} F'(\mathbf{\overline{e}}_1, \mathbf{h}_1) \right) \mathbf{G_{\mathcal{C}}}\mathbf{P}_1. \end{align} \normalsize When $l = deg(F')$ and $\mathbf{\mathfrak{u}}_{i_1}, \ldots, \mathbf{\mathfrak{u}}_{i_l}$ are chosen in which, for $\rho=1, \ldots, l$, $i_\rho\leq k$, then $\Delta^{(l)}_{\mathbf{\mathfrak{u}}_{i_1}, \ldots, \mathbf{\mathfrak{u}}_{i_l}} F'(\mathbf{\overline{e}}_1, \mathbf{h}_1)$ is a constant vector independent of $\mathbf{\overline{e}}_1$. Hence, Eq. (\ref{differential-attack}) returns a linear equation with respect to $\mathbf{G_{\mathcal{C}}}\mathbf{P}_1$. If the attacker has $k$ such linear independent equations, then he can find $\mathbf{G_{\mathcal{C}}}\mathbf{P}_1$. Therefore, the attacker computes Eq. (\ref{differential-attack}) for other messages, at least $k$ times, to prepare a system of $k$ linear equations with respect to $\mathbf{G_{\mathcal{C}}}\mathbf{P}_1$ and then solve it. The complexity of the first step of the attack is $O(k \times 2^{deg(F')})$. Since the vector $\mathbf{h}$ is secret, the attacher needs $2^{d-1}$ guesses. Hence, the overall complexity of recovering $\mathbf{G_{\mathcal{C}}}\mathbf{P}_1$ is of order $O(k \times 2^{d-1} \times 2^{deg(F')})=O(k \times 2^{d-1} \times 2^{d+1})=O(k \times 2^{2d})$. For the proposed QC-LDPC lattice with $(k, n)=(215, 258)$ and $d=61$, the complexity of the attack is $2^{129}$. The next steps of this attack involve recovering $\mathbf{e}_1$ and decrypting the ciphertext using $\mathbf{P}_1$. The first instance of the ciphertext is given as \begin{eqnarray}\label{attack-on-s1-m} \mathbf{v}^{(1)} = F((\mathbf{m}^{(1)}+\mathbf{\overline{e}}_1), \mathbf{h}_1)\mathbf{G_{\Lambda}}\mathbf{P}_1+\mathbf{e}_1\mathbf{P}_1. \end{eqnarray} The attacker applies it to $\mathbf{m}^{(1)}=(0, \ldots, 0)$, obtaining \begin{eqnarray}\label{attack-on-s1} \mathbf{v}^{(1)} &\equiv& F'(\mathbf{\overline{e}}_1, \mathbf{h}_1)\mathbf{G_{\mathcal{C}}}\mathbf{P}_1 +\mathbf{e}_1 \mathbf{P}_1 ~(\textrm{mod} ~2). \end{eqnarray} Since $\mathbf{G_{\mathcal{C}}}\mathbf{P}_1 $ has been estimated in the previous step, the attacker should estimate $F'(\mathbf{\overline{e}}_1, \mathbf{h}_1)$ and $F'(\mathbf{\overline{e}}_1, \mathbf{h}_1)\mathbf{G_{\mathcal{C}}}\mathbf{P}_1$ for all possible vectors $\mathbf{e}_1$ and $\mathbf{h}_1$. The corresponding $\mathbf{e}_1 \mathbf{P}_1$ can be computed using Eq. (\ref{attack-on-s1}), that is, $\mathbf{v}^{(1)} ~(\textrm{mod} ~2)\oplus F'(\mathbf{\overline{e}}_1, \mathbf{h}_1)\mathbf{G_{\mathcal{C}}}\mathbf{P}_1=\mathbf{e}_1 \mathbf{P}_1$. Recovering the matrix $\mathbf{P}_1$, based on this equation, requires $vq^2$ search for the different choices for $(\mathbf{e}_1, \mathbf{h}_1)$. Indeed, Eq. (\ref{attack-on-s1}) constructs a linear system of equations $\mathbf{x}=\mathbf{e}_1 \mathbf{P}_1$ in terms of the $\mathbf{P}_1$ entries as its variables. With $\mathbf{P}_1$ as a block diagonal matrix, we have $\mathbf{x}= ({\mathbf{e}_1}_{[1:q]}\mathbf{\pi}_{1}, {\mathbf{e}_1}_{[q+1:2q]}\mathbf{\pi}_{2}, \ldots, {\mathbf{e}_1}_{[(v-1)q+1:vq]}\mathbf{\pi}_{v})$, where ${\mathbf{e}_1}_{[(i-1)q+1:iq]}$ is the $i$th $q$ bits of $\mathbf{e}_1$. Moreover, each sub-permutation matrix has one nonzero component in each column, leading to the equation $\mathbf{x}_j={\mathbf{e}_1}_{[(j-1)q+1:jq]}\mathbf{\pi}_{j}$ has $q^2$ solutions. Therefore, there are $vq^2$ solutions for $\mathbf{P}_1$ in this system. The complexity of finding $\{\widetilde{\mathbf{e}_1}, \widetilde{\mathbf{h}_1}, \widetilde{\mathbf{P}_1}\}$ that satisfy Eq. (\ref{attack-on-s1}) is $O(2^{(l_1+l_2)}\times vq^2)$. The attacker repeats the same work to find $\{\overline{\mathbf{e}_1}, \overline{\mathbf{h}_1}, \overline{\mathbf{P}_1}\}$ satisfying Eq. (\ref{attack-on-s1-m}) using an arbitrary message with complexity $O(2^{(l_1+l_2)}\times vq^2)$. Then, the attacker compares $\{\widetilde{\mathbf{e}_1}, \widetilde{\mathbf{h}_1}, \widetilde{\mathbf{P}_1}\}$ and $\{\overline{\mathbf{e}_1}, \overline{\mathbf{h}_1}, \overline{\mathbf{P}_1}\}$ in order to verify the suitable set for this step. Hence, the complexity of estimating $\{\mathbf{e}_1, \mathbf{h}_1, \mathbf{P}_1\}$ is approximately $O(2^{(l_1+l_2+1)}\times 2vq^2)$, which is almost $O(2^{84})$ for the proposed scheme. At this moment, the attacker can decrypt any $\mathbf{v}^{(1)}$ using $\{\mathbf{e}_1, \mathbf{h}_1, \mathbf{P}_1\}$ and $\mathbf{G_{\mathcal{C}}}\mathbf{P}_1$. Hence, the overall complexity for decrypting $\mathbf{v}^{(1)}$ is $O(k \times 2^{2d}+2^{(l_1+l_2+1+1)}\times 2vq^2)\approx O(2^{129})$. Since the intentional error vector and permutation matrix change with each message, the encryption matrix $\mathbf{G_{\mathcal{C}}}\mathbf{P}_i$ and each vector $\mathbf{e}_i\mathbf{P}_i$ change in the $i$th round of encryption, while $\mathbf{h}_i$s are known after estimation of $\mathbf{h}_1$. Therefore, for recovering all keys, the attacker can consider the zero vector as a message and compute the ciphertext $\mathbf{v}^{(2)} = F(\mathbf{\overline{e}}_2, \mathbf{h}_2)\mathbf{G_{\Lambda}}\mathbf{P}_2+\mathbf{e}_2\mathbf{P}_2$. Next, $\mathbf{G_{\mathcal{C}}}\mathbf{P}_2$ is estimated with complexity of order $O(k \times 2^{deg(F')})=O(k \times 2^{d+1})$, approximately $O(2^{70})$ in our case. Furthermore, $\mathbf{P}_2$ is computed based on the above equation of $\mathbf{v}^{(2)}$ in the similar way as mentioned above. The complexity of computing the other encryption matrix $\mathbf{G_{\mathcal{C}}}\mathbf{P}_i$, for $i=3, \ldots $, in each round is $O(2^{70})$. Thus, the overall complexity of this attack is $O( 2^{129}+N_p\times 2^{70})$, where $N_p$ is the number of possible permutations. As a consequence, the overall complexity for the proposed parameters is $O( 2^{129}+2^{36}\times 2^{70}) \approx O( 2^{129})$. Therefore, with the proposed parameters, we achieve a security level of $128$-bit. \section{Comparison}~\label{sec:Comparison} In this section, we compare our proposed lattice based cryptosystem with \cite{Hooshmand}, \cite{Deepthi-Nonlinear} and\cite{GLOBECOM}, in which \cite{Hooshmand} is a lattice based joint scheme (based on LDLC lattices) and the others are based on error correcting codes. Moreover, in \tablename~\ref{comparison}, we review a number of previous schemes that join error correction and encryption in one process to enable efficient implementations. Although, the existing schemes based on lattices and error correcting codes are not in the same category, we also point out the results of the joint schemes based on error correcting codes to provide an intuition about the counterpart of lattice based schemes. The recent work of Stuart and Deepthi \cite{Deepthi-Nonlinear} is an RN-like scheme based on QC-LDPC codes that strengthen the cryptosystem against differential attacks. It has the smallest key size among other RN-like schemes and its complexity of encryption and decryption is of $O(n^2)$ due to the used nonlinear function in its design. Similar to other RN-like schemes, the output of this scheme is fed into a modulator to transmit through an AWGN channel. \begin{table*}[!ht] \scriptsize \caption{Comparison of the proposed scheme with other secure channel coding schemes.} \centering \begin{tabular}{|c||c|c|c|c|} \hline Cryptosystem & Underlying code, $\mathcal{C}(n,k)$ & Information rate & key size \\ \hline \hline Rao \cite{Rao} & Goppa code, $\mathcal{C}(1024, 524)$, coding rate$=0.51$ & N/A & $2$ Mbits \\ \hline Rao and Nam \cite{Rao-Nam} & Hamming code, $\mathcal{C}(72, 64)$, coding rate$=0.89$ & N/A & $18$ kbits \\ \hline Sobhi Afshar et al. \cite{Eghlidos} & EG-QC-LDPC code, $\mathcal{C}(2044, 1024)$, coding rate$=0.5$ & N/A & $2.5$ kbits \\ \hline Hooshmand et al. \cite{Hooshmand-ISC} & EDF-QC-LDPC code, $\mathcal{C}(2470, 2223)$, coding rate$=0.9$ & N/A & $3.55$ kbits \\ \hline Esmaeiliet et al. \cite{Esmaeili1} & QC-LDPC code, $\mathcal{C}(2048, 1536)$, coding rate$=0.75$ & N/A & $2.191$ kbits \\ \hline Esmaeili and Gulliver \cite{Esmaeili2} & QC-LDPC code, $\mathcal{C}(2048, 1536)$, coding rate$=0.75$ & N/A & $2.22$ kbits \\ \hline Adamo et al. (ECBC) \cite{ECBC} & LDPC code, $\mathcal{C}(256, 128)$, coding rate$=0.5$ & N/A & 82 kbits.\\ \hline Pisek et al. \cite{GLOBECOM} & QC-LDPC code, $\mathcal{C}(128, 256)$, coding rate$=0.5$ & N/A & $128$ bits\\ \hline Stuart and Deepthi \cite{Deepthi-Nonlinear} & EDF-QC-LDPC code, $\mathcal{C}(124, 248)$, coding rate$=0.5$ & N/A & $182$ bits \\ \hline LDLC lattice based cryptosystem \cite{Hooshmand} & Latin square LDLC lattice, $n=10^4$ symbols & N/A & $3$ Mbits \\ \hline The proposed lattice based cryptosystem & RDF-QC-LDPC code, $\mathcal{C}(258, 215)$, $L=16$ & $5$ & $214$ bits \\ \hline \end{tabular} \label{comparison} \end{table*} \normalsize The most efficient joint AES-coding scheme is proposed in \cite{GLOBECOM}, where QC-LDPC codes are embedded in each round of the AES encryption and decryption. This scheme consists of two parts for encryption and channel coding, with the encryption part which is more powerful than classical AES. The coding part of the proposed scheme outperforms other conventional joint AES-coding schemes. It applies the same parity-check matrix for the encryption and encoding parts. Promising ideas such as using lower triangular matrices and the quasi-cyclic structure of the LDPC code and using the same hardware resource for both parts, reduce power consumption compared to other joint AES-coding schemes \cite{GLOBECOM}. Encryption and channel coding cannot be applied simultaneously in \cite{GLOBECOM} and the output of encryption is fed into the encoder and then the resulting data is passed through the QPSK modulator to transmit via an AWGN channel. Unlike the proposed schemes in \tablename~\ref{comparison}, we have merged these three steps into a single step using efficient lattices in our cryptosystem. This provides less delay, lower implementation complexity and better error performance in overall for high SNR or bandlimited channels. The column three in \tablename~\ref{comparison} describes the average information bits per symbol in the transmission which is not available for other schemes. If we want compute the average information bits per symbol in the transmission of a joint scheme, the coding rate of the used code in the structure of the scheme should multiply with the rate of a modulation that will be applied after. Since after encoding the rate of the joint schemes is less than $1$, they should use high order modulation to compensate this low rate for bandlimited AWGN channels. For example, with the proposed parameters in \tablename~\ref{comparison}, the information rate of our scheme is $5$. To reach the same information rate with the code based schemes like \cite{Deepthi-Nonlinear} and \cite{GLOBECOM}, which have coding rate $0.5$, should use a high order modulation like $1024-$QAM after coding step ($0.5\times 10=5$). However, applying high order modulation makes the error performance weaker. Therefore, code based schemes are not appropriate for bandlimited channels without combining them with high order modulation. In contrast, the lattice codes are high order modulation schemes with error correction capability and provide high information rate. Since there are not such a complete setting about concatenation of AES-joint schemes or RN-like schemes and a high order modulation in the literature, we can not have a fair comparison about the overall error performance of joint schemes based on codes and our proposed scheme. Our lattice based scheme is the first candidate introducing a scheme for secure communication on bandlimited channels. In the sequel, we compare the key size of our cryptosystem with the LDLC lattice based scheme. In \cite{Hooshmand}, Latin square LDLCs are used to provide a joint encryption and encoding scheme. The encryption and decryption complexity of the proposed LDLC based scheme is $O(n^2\beta)$ and $O(n^2\delta)$, respectively, where $\beta$ and $\delta$ are the maximum required memory to save each entry of its rational generator matrix and its secret key in binary form, respectively, and $n$ is the lattice dimension \cite{Hooshmand}. On the other hand, the ciphertext $\textbf{c}$ is transmitted through an ``unconstrained'' power AWGN channel. Indeed, the shaping is removed to decrease the encryption complexity, while the computational complexity of the encryption/encoding grows rapidly due to the existence of unbounded lattice points and its average transmitted power becoming too large The Latin square LDLC lattices are introduced by the parity-check matrix $\textbf{H}$ which is an $n\times n$ Latin square. This matrix is determined by a generating sequence set $\mathcal{H}=\{h_1, h_2, \ldots, h_d\}$, where $h_i$s are nonzero values at the appropriate locations of the used Latin square $\textbf{H}$. The generating sequence set $\mathcal{H}$ is considered as the secret key of the LDLC based scheme, instead of its corresponding parity-check matrix $\textbf{H}$ \cite{Hooshmand}. In this way, the legitimate receiver has to construct the same parity-check matrix $\textbf{H}$ using the secret key $\mathcal{H}$ and is able to recover the original message in decryption. It can be shown that the generating set $\mathcal{H}$ does not result in a unique parity-check matrix for the Latin square LDLC that is used for decryption, and then the qualified receiver is not able to decrypt the ciphertexts correctly. As there are $\mathcal{L}(n)=n! \sum\nolimits_{\textbf{A}\in B_n}{(-1)^{\sigma_0(\textbf{A})}}{per(\textbf{A})\choose n}$, $n \times n$ Latin squares, where $ B_n$ is the set of all binary $n \times n$ matrices, $\sigma_0(\textbf{A})$ is the number of zero entries in matrix $\textbf{A}$ and $per(\textbf{A})$ is the permanent of matrix $\textbf{A}$ \cite{Latin-squares}, there are at least $\mathcal{L}(n)/(n-d)!$ different parity-check matrices for Latin square LDLCs with the given generating set $\mathcal{H}$. Thus, for successful decryption, the generating set $\mathcal{H}$ should be replaced with the parity-check matrix $\textbf{H}$ as the secret key in \cite{Hooshmand}. In this way, since the position of each non-zero entry along with its value has to be saved, the memory consumption for saving $\textbf{H}$ is $ nd\big(r+2\lceil\log_2\left( n\right)\rceil\big) $ bits, , where $r$ is the maximum number of bits required for saving $h_i$, for $i=1,\ldots, d$. The secret key of the proposed LDLC based scheme is $\mathcal{K}=\{\mathcal{H},\mathcal{ P}\}$, where $\mathcal{P} =\{p_1, p_2, \ldots, p_d\}$ is the set of indexes such that $1\leq p_i\leq n$, for $1\leq i\leq d$ \cite{Hooshmand}. Therefore, the key size of an LDLC based cryptosystem, when considering the parity-check matrix $\textbf{H}$, is at most $d \big( n(r+2\lceil\log_2\left( n\right)\rceil)+ \lceil\log_2\left( n\right)\rceil \big)$ bits. In the same level of security (128 bits), the key size of the LDLC based cryptosystem for an LDLC with parameters $ n=10^4, d=7$ and $r=16$ is $3080098$ bits; while the key size for our cryptosystem is equal to $214$ bits with a $(258, 215)$-QC-LDPC code, $b=q=43, d_v=3, n_0=6$ and $d_c=18$ that is much smaller. As a consequence, our proposed cryptosystem has a small key size compared to other RN-like cryptosystems that can also do modulation simultaneously. \section{Conclusion}~\label{sec:Conclusion} In this paper, we have proposed a new RN-like encryption scheme using QC-LDPC lattices. Moreover, we have exploited lattice codes related to these lattices to join encryption, channel coding and modulation in a single step that is suitable for resource limited applications. The proposed nonlinear cryptosystem is secure against all variants of chosen plaintext attacks against RN-like encryption schemes. The main advantages of the proposed scheme are its high information rate, small key size and low hardware complexity. As a consequence, the joint scheme provides high speed and efficient implementation as well as secure and reliable data transmission for bandlimited AWGN channels. \ifCLASSOPTIONcaptionsoff \newpage \fi
{'timestamp': '2019-06-17T02:16:54', 'yymm': '1906', 'arxiv_id': '1906.06280', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06280'}
arxiv
\section{Introduction} The basic task of a command and control (C\&C) interface is to convert a language user's unstructured input into some structured format that can be unambiguously interpreted by a controller. Except for the simplest of devices, this requires at some point in the processing chain some kind of syntactic component that is aware of such issues as compositionality and word order. For example, in the home automation C\&C phrase {\em turn on the lights}, the system needs to at least be aware that the input language is SVO to trigger the difference between action and patient. In many cases, this is done through the use of a context-free grammar in the decoding process \cite{Jurafsky95usinga}, as illustrated in Figure \ref{cfgex} for the task of controlling a television using natural language. \begin{figure*} \small \begin{center} \begin{tabular}{ll} {\tt $<$sentence$>$} & {\tt = $<$volume\_command$>$ $|$ $<$channel\_command$>$}\\ {\tt $<$volume\_command$>$} & {\tt = (set $|$ change) volume [VOL] to $<$number$>$}\\ {\tt $<$channel\_command$>$} & {\tt = (select $|$ change to) channel [CH] ($<$number$>$ | $<$name$>$)}\\ {\tt $<$number$>$} & {\tt = one [1] $|$ two [2] $|$ three [3] $|$ four [4] $|$ five [5]}\\ {\tt $<$name$>$} & {\tt = BBC [4] $|$ CNN [2] $|$ EuroSports [1]}\\ \end{tabular} \end{center} \caption{Context-free grammar for a television command \& control interface.} \label{cfgex} \end{figure*} While this approach has proved to be quite effective for many applications, such devices are limited in the sense that they require the user to adhere to the grammar and lexicon as predefined by the designers of the device. This paper describes research conducted in the context of the ALADIN project, which investigates a command and control interface that is not bound by predefined linguistic constraints, but rather adapts to the user in a language and domain independent way. The aim of the project is to find techniques that minimize the training phase for such a self-learning system, so that it can be easily deployed as a home automation C\&C system for people with a physical impairment, who are often challenged by (progressively aggravating) speech impediments. A self-learning C\&C interface that is able to automatically learn and adapt to an individual user's linguistic characteristics, can provide an important means for a physically impaired person to regain some independence in a domestic setting. In this paper, we will investigate the syntactic component of the ALADIN-system, where we define ``syntax'' loosely as a means to interface between the surface utterance and its underlying semantic representation. Our semantic representation of choice is that of a semantic frame with slots that need to be filled with values (Section \ref{data}). Previous research efforts show that this can be done with a fair degree of accuracy using a hierarchical hidden markov model architecture (Section \ref{related}) under a minimal amount of supervision. The research described in this paper improves on this accuracy, through means of retraining using two different techniques: a shallow approach using sequence labeling (Section \ref{seqlabel}) and a more traditional parsing approach employing stochastic context-free grammar induction (Section \ref{cfg}). We will quantitatively and qualitatively evaluate these techniques on the basis of comparative experiments (Section \ref{exp}) and finish with a discussion of the results and pointers to future work (Section \ref{conclusion}). \section{The {\sc patcor} Corpus} \label{data} The experiments described in this paper were conducted on the {\sc patcor} corpus\footnote{\url{https://github.com/clips/patcor}}. {\sc patcor} is a collection of command and control utterances for the single-player card game {\em Patience}. This control task was chosen because the disambiguation of these types of sentences requires awareness of compositionality and word order, while at the same time the domain and vocabulary are fairly restricted. The corpus contains audio recordings of nine players, totaling around 3000 spoken commands (Belgian Dutch) and their associated action in the game (represented as a semantic frame; cf. infra). All of the spoken commands were manually transcribed. {\sc patcor} consists of a core data set of eight speakers, for which around 250 utterances were collected. We will refer to this core set as the {\sc p1-8} set. Additional data was gathered for one player to study the effect of increasing training sizes. This data set, referred to as the {\sc p9} set contains over 1,000 utterances. In the experiments below, {\sc p1-8} is used for development purposes, while {\sc p9} is used for evaluation in learning curve experiments. More details about the data set and the command structures that were used by the speakers are described in \newcite{nlp4ita}. The semantic representation of the controls in {\sc patcor} takes the form of semantic frames. This is illustrated in Figure \ref{patexample}: the semantic frame describes the card that is moved (as a suit/value pair), the card that it is moved onto, as well as the respective columns that are involved in the move. Additional slots are available for moves from the hand and the foundation (respectively at the bottom and top of Figure \ref{patexample}). An action on the playing field is thus described as a collection of slot-value pairs. There are two types of semantic frames: the {\em movecard} frame exemplified in Figure \ref{patexample} and an additional {\em dealcard} frame that denotes the action of asking for a new hand of cards. The latter frame has no slots or values to be filled. Note that the automatically generated semantic frame is overspecified with respect to the command: in the command in Figure \ref{patexample}, columns are not mentioned, although this information is included in the automatically generated frame. We will use the utterances and their associated frames as training material to trigger the mapping from words onto slot-value pairs. The difficulty for the induction task therefore lies in identifying which words can be linked to which slots and associated values. Furthermore, a word might underspecify its slot-value in the semantic frame: for instance in Figure \ref{patexample}, the word ``rood'' ({\em red}) can refer to suits {\em hearts} and {\em diamonds} alike, while only the former is represented in the associated semantic frame. \begin{figure} \begin{center} {\em Put the jack of clubs on the red queen} \adjustbox{valign=m}{ \includegraphics[width=4.5cm]{fig/playingfield.png}} \small \begin{tabular}{|l|l|}\hline \multicolumn{2}{|c|}{{\em movecard}}\\\hline Slot & value \\\hline $<$FS$>$& c \\\hline $<$FV$>$ & 11 \\\hline $<$FF$>$& -\\\hline $<$FC$>$& 3 \\\hline $<$FH$>$& -\\\hline $<$TS$>$& h \\\hline $<$TV$>$& 12 \\\hline $<$TF$>$& -\\\hline $<$TC$>$& 4 \\\hline \end{tabular} \end{center} \caption{Example of a Patience command in {\sc patcor}, the corresponding action on the playing field and the associated semantic frame. A move is defined as a combination of a from slot ($<$F?$>$) and a to slot ($<$T?$>$). A card is defined as the combination of a suit ($<$?S$>$) and a value ($<$?V$>$). Also defined are slots for the `hand' at the bottom ($<$FH$>$), the seven columns ($<$?C$>$) in the playing field and the four foundation stacks at the top right ($<$?F$>$).} \label{patexample} \end{figure} \section{Related Research} \label{related} In this section we will provide some pointers to related research on mapping tokens to semantic frames in C\&C interfaces. We will also discuss previous research efforts on the {\sc patcor} data using two different techniques. \subsection{Semantic frame induction} There are many studies in spoken language understanding that use semantic frames or an equivalent to encode the meaning of utterances. Mapping new utterances to these semantic representations has been attempted using a variety of techniques, such as generatively associating word sequences with concept sequences \cite{Pieraccini1991,Wang2011}, using a discriminative technique to perform concept tagging \cite{Hahn2011}, or applying alignment techniques from the field of statistical machine translation to relate words with semantic concepts \cite{Epstein1996,Macherey2001}. The research described in this paper differs from these previous approaches in that our semantic representation is overspecified with respect to the utterance and that we do not assume the ready availability of gold-standard alignments between tokens and concepts. With respect to the latter issue, our research is more akin to the unsupervised alignment of utterances and concepts in the {\sc atis} corpus, as described in \newcite{Huet2011}. The {\sc patcor} task itself on the other hand, is more similar to that of the ROBOCUP data \cite{Chen2008}, for which a variety of approaches have been coined, ranging from learning the alignment between utterances and frames \cite{Liang2009} to learning semantic parsers \cite{Chen2010}. \subsection{Supervised concept tagging} \label{nlp4ita} Previous work on {\sc patcor} data is described in \newcite{nlp4ita} and \newcite{SMIAE}. These papers approach the problem of inducing semantic frame slots from (transcribed) utterances as a concept/sequence labeling task that can be learned by a machine learning classifier. To this end, the transcriptions of {\sc patcor} were manually annotated with IOB-concept tags, where each word is associated with a concept tag that denotes its association to a specific type of frame slot and its relative position in the text chunk ({\bf I}nside, {\bf O}utside or at the {\bf B}eginning). This is illustrated in the following command (English: {\em put the hearts five on the clubs six}) which denotes a move from a $<${\bf F}rom\_{\bf S}uit$>$ $<${\bf F}rom\_{\bf V}alue$>$ card to a $<${\bf T}arget\_{\bf S}uit$>$ $<${\bf T}arget\_{\bf V}alue$>$ card. \begin{exe} \ex leg$^{O}$ de$^{O}$ harten$^{I\_FS}$ vijf$^{I\_FV}$ op$^{O}$ de$^{O}$ klaveren$^{I\_TS}$ zes$^{I\_TS}$ \label{taggedexe} \end{exe} The eight data sets of the {\sc p1-8} set were each used individually as training data for a memory-based concept tagger and learning curves were plotted using the last 50 utterances in the respective data sets. Almost all of the data sets achieve an I-chunk F-score between 95\% and 100\% after around 130 training utterances, underlining the learnability of the task. However, this approach relies on the existence of a gold-standard mapping between the observed tokens and their relevant frame slots and values. This type of supervision is not available in a C\&C interface that is to be trained through the association of an utterance in its entirety with an (overspecified) semantic frame. Furthermore, \cite{nlp4ita,SMIAE} only report tag and chunk accuracy scores, which only gives us an indirect indication of how well semantic frame slots and values can be filled by this technique. In the experiments below, we consider this supervised sequence labeler as the upperbound of the level of performance that can be expected for this data set. \subsection{FramEngine} Research on the acoustic part of {\sc patcor} focuses on finding descriptive word units in the utterances, using non-negative matrix factorization. To map observed units to frame slots (frame decoding), early research \cite{Gemmeke2012b} employed a hand-crafted grammar, which encoded expected word order patterns. This approach obtained slot-value recall scores between 37\% and 85\% on the {\sc p1-8} set. One of the major bottlenecks in achieving higher accuracies was the method's limited ability to build a robust acoustic representation on the basis of a limited amount of training data. To streamline frame decoding, a semantic frame induction engine was developed (\textit{FramEngine}) that uses a combination of non-negative matrix factorization and a hierarchical hidden markov model (\textit{HHMM}) to simultaneously detect recurring patterns in commands (words, morphemes, acoustic units) and relate them to their relevant slots and values in semantic frames. This is a weakly supervised induction task, as there is only supervision at the utterance level and no relations between the components of the utterances and the semantic frame slots are specified in advance. Previous work \cite{ons2013self} demonstrated the performance of an early implementation of this system on pathological speech input for a simple home automation command \& control task and non-pathological {\sc patcor} speech data. The results show that the system has a promising learning potential even with small amounts of training data, but that enhancements are needed in order to produce practically usable accuracies for more complex utterances, such as the ones found in {\sc patcor}. Work described in \newcite{1901.10680} focused on improvements with respect to the system architecture. Extensions regarding the HMM structure and a technique called ``expression sharing'' were added to FramEngine's workings and were shown to significantly improve on the frame-slot filling abilities on transcribed {\sc patcor} data. \newcite{1901.10680} describes parameter selection experiments on {\sc p1-8}, while a final evaluation was conducted on the basis of learning curve experiments on the {\sc p9} set. FramEngine was able to score over 95\% frame-slot F-score using around 200 utterances as training data. While these results are encouraging, there are reasons to believe we can still increase accuracy by means of retraining. FramEngine's slot-value allocation technique is limited in the context that it can consider during disambiguation. And while word order is indirectly modeled through the structural setup of the hierarchical hidden markov model, a further explicitation of the syntactic properties of the observed utterances may provide additional insights into the induction process proper. In the context of this paper, we refer to retraining as the process of using an automatically labeled data set as input data for another inductive processing step. Typically, retraining techniques attempt to label large volumes of unlabeled data to increase the volume of available training data ({\em self-training} \cite{mcclosky-charniak-johnson:2006:HLT-NAACL06-Main}) or adapt a classifier to a new domain ({\em co-training} \cite{Blum:1998:CLU:279943.279962}). The work in this paper investigates retraining as the process of using successive classifiers on the same training data to improve results. This approach has been successfully applied to a variety of problems, including morphological analysis \cite{DePauw2008d} and spoken language understanding \cite{wu-EtAl:2006:EMNLP}. \section{Retraining} \label{retraining} This paper explores two different retraining techniques: inductive sequence labeling (Section \ref{seqlabel}) and stochastic context-free grammar induction (Section \ref{cfg}). As described in \newcite{1901.10680}, FramEngine can be shown to exhibit a more than decent performance on the task of frame-slot filling for the {\sc patcor} data. For retraining purposes, we can use FramEngine to decode its own training set, linking each word in the training set with a frame slot/value label through Viterbi decoding of the utterance. This means we can now also associate each word with an automatically assigned IOB-tag, expressing its frame-slot and in addition also its value: \begin{exe} \ex leg$^{O}$ de$^{O}$ harten$^{I\_FS=h}$ vijf$^{I\_FV=5}$ op$^{O}$ de$^{O}$ klaveren$^{I\_TS=c}$ zes$^{I\_TS=6}$ \label{autotagex} \end{exe} \noindent This information is consequently used as source data for retraining purposes. \subsection{Sequence Labeling} \label{seqlabel} The first type of retraining technique recalls the research described in Section \ref{nlp4ita}: words annotated with IOB-tags are considered as training material for a discriminative sequence tagger. Fully supervised (i.e. with manually attributed IOB-tags), this approach can be observed to obtain near perfect accuracy scores on the {\sc patcor} data. Using training data labeled by a weakly supervised technique (i.e. FramEngine), a sequence labeler can be expected to perform less accurately than the fully supervised approach, but more accurately than FramEngine itself, since it can take into account more contextual information. We consider two different machine learning techniques driving the sequence labeler: we compare a memory-based tagger ({\sc mbt} \cite{mbt}) with one based on conditional random fields ({\sc wapiti} \cite{lavergne2010practical}). \begin{figure} \includegraphics[trim=50 180 50 250,clip,width=\linewidth]{fig/lc1step.pdf} \caption{Learning curves for {\sc p9} data FramEngine vs Single-Step Sequence labeling.} \label{1step} \end{figure} Figure \ref{1step} displays learning curves for exploratory experiments, in which we compared fully supervised sequence labeling (using gold-standard labels), weakly supervised decoding using FramEngine, and retrained sequence labelers. As expected, the accuracy of the retrained sequence labeler eventually ends up somewhere between that of the supervised labeler and that of FramEngine. But this result is not obtained until rather late in the learning curve, and even the fully supervised labeler trails compared to the weakly supervised FramEngine until training data hits around 400 utterances. This is due to the fact that the sequence labelers consider the IOB-tags holistically. FramEngine as described in \newcite{1901.10680}, uses the method of {\em expression sharing}, in which the hidden markov model is aware of the fact that certain frame slots (such as the suit or value of a card) may be expressed using the same tokens, regardless of whether it occurs in a {\em from}-clause or a {\em target}-clause. This means that if a certain value has only occurred in one particular context in the training set (e.g. vijf$^{I\_FV=5}$), the tagger would not be able to predict the correct tag when it occurs in the other context in held-out data (e.g. vijf$^{I\_TV=5}$), as it is simply unaware this tag even exists. \begin{figure*} \begin{center} \includegraphics*[width=13cm]{fig/2step.png} \end{center} \caption{Illustration of the two-step tagging approach.} \label{aladinFramework} \end{figure*} We therefore implement a two-step tagging approach that implicitly introduces expression sharing in the workings of the sequence labelers. The process is illustrated in Figure \ref{aladinFramework}. The tags are decomposed into two parts: first a tagger attributes to the words slot-value tags that generalize over slots of the same type (in this case: ignoring `from' and `target' information). In the second step, a tagger is trained using the slot-portion of the tag from step 1 as the token to be tagged and the remainder of the original tag as the target tag. The original word in the utterance is used as an extra information layer towards disambiguation. The tags of both steps are then combined into the conglomerate tag. In case of incompatible tag-parts, the word is attributed the {\bf O}-tag. We will use the two-step tagging approach in the experiments described in Section \ref{exp}. \subsection{PCFG Induction} \label{cfg} The utterances tagged automatically by FramEngine (cf. Example \ref{autotagex}) can also be transformed into tree-structures, given information about which expressions can be shared. Slot-values ({\tt =?} in Example \ref{autotagex}) can be considered as terminals, while suit/value and from/target indicators can function as nonterminals. Two consecutive clauses headed by the same nonterminal are joined. As such, the tagged sentence in Example \ref{autotagex} can be algorithmically transformed into the phrase structure in Figure \ref{pstree}. These phrase structures can then be transformed into a (probabilistic) context free grammar (Figure \ref{excfg}), by observing the productions used to construct the tree structures for the utterances in the training set. Finally, a Viterbi parser is used to assign tree structures to new utterances and a reversal of the tree construction process outlined above, can be used to assign IOB-labels that refer to frame slot/value pairs. \begin{figure} \small \Tree [.ROOT [.O {\em leg} {\em de} ] [.F [.S [.h {\em harten} ] ] [.V [.5 {\em vijf} ] ] ] [.O {\em op} {\em de} ] [.T [.S [.c {\em klaveren} ] ] [.V [.6 {\em zes} ] ] ] ] \caption{Phrase-Structure tree derived from Example \ref{autotagex}.} \label{pstree} \end{figure} \section{Experimental Results} \label{exp} \begin{figure} \small \begin{center} \begin{tabular}{lll} {\tt ROOT} & $\rightarrow$ & {\tt O F O T}\\ {\tt F} & $\rightarrow$ & {\tt S V}\\ {\tt T} & $\rightarrow$ & {\tt S V}\\ {\tt S} & $\rightarrow$ & {\tt h $\vert$ c}\\ {\tt V} & $\rightarrow$ & {\tt 5 $\vert$ 6}\\ {\tt O} & $\rightarrow$ & {\em leg de $\vert$ op de}\\ \hline {\tt h} & $\rightarrow$ & {\em harten}\\ {\tt c} & $\rightarrow$ & {\em klaveren}\\ {\tt 5} & $\rightarrow$ & {\em vijf}\\ {\tt 6} & $\rightarrow$ & {\em zes}\\ \end{tabular} \end{center} \label{excfg} \caption{Context-free grammar sample and lexicon derived from Figure \ref{pstree}.} \end{figure} \begin{figure*}[ht] \begin{center} \begin{tabular}{cc} \includegraphics[trim=50 180 50 200,clip,width=7.5cm]{fig/lc2steptaggers.pdf} & \includegraphics[trim=50 180 50 200,clip,width=7.5cm]{fig/lc2steppcfgb.pdf}\\ (a) & (b) \end{tabular} \end{center} \caption{Learning curve experiments for the original FramEngine labeling, supervised and retrained sequence labeling (a) and retraining using PCFG induction (B)} \label{lcurves} \end{figure*} \subsection{Experimental Setup} We compare four different approaches on the basis of their ability to fill slots with the correct values in semantic frames: \begin{enumerate} \item{Fully supervised sequence labeling ({\sc mbt} and {\sc wapiti})} \item{FramEngine} \item{Retraining using sequence labeling ({\sc mbt} and {\sc wapiti})} \item{Retraining using PCFG-induction} \end{enumerate} FramEngine fills frame slots by choosing slot-value tags with the highest summed probability observed during decoding, exceeding a certain threshold (established during development experiments). If no slot value tag with sufficient probability mass occurs in the utterance, the slot remains empty. Approaches 1, 3 and 4 fill frames in a similar vein, except that these techniques predict for each token in the utterance a single slot-value tag without a probability score (i.e. probability = 1). To solve ties, we add a small bias proportional to the time index to each single tag probability (t * 10\textsuperscript{-5}). \subsection{Evaluation} An important requirement for the ALADIN system is that the amount of effort involved for the user in training the system be kept to a minimum. To evaluate our techniques in this vein, we perform learning curve experiments to see which techniques learn the required task the fastest with the least amount of training data. The experiments were performed on the {\sc p9} set, which consists of 1142 commands and corresponding action frames of one single speaker. The last third of the data set is used as evaluation data, while the remaining training data is divided into partitions of 50 utterances. We preserve the order of the training utterances as they have been recorded, to mimic how the actual system would be trained in practice. The training partitions in the {\sc p9} set are used incrementally as training data for FramEngine. Optimal parameters and information sources for FramEngine were obtained during expansive experiments on the {\sc p1-8} \cite{1901.10680}. The trained hierarchical hidden markov model is then used to transcode the training utterances into slot-value tag sequences. These automatically tagged utterances, derived through a weakly supervised induction process, are then used to train the memory-based and CRF-based sequence taggers and to induce a PCFG respectively. Finally, the retrained techniques are evaluated on the held-out data, creating a data point on the learning curve. We evaluate against gold-standard semantic frames in which only the slots mentioned in the utterance have been specified (in contrast to the overspecified frame in Figure \ref{patexample}) and which slot values can be ambiguous: e.g. in the case of 'aas opzij leggen' (`put ace aside'), the reference frame includes all four possible foundation values (target\_foundation={1,2,3,4}), because no specific value is specified in the command. We use frame slot F-score as our metric of choice, which is calculated as follows: \begin{itemize} \item{slot precision: \#correctly filled slots / \#total filled slots in predicted frame} \item{slot recall: \#correctly filled slots / \#total filled slots in reference frame} \item{slot F$_{\beta=1}$-score: 2* slot precision * slot recall /(slot precision + slot recall)} \end{itemize} Finally, as FramEngine's performance is affected by random initializations of the system, the experiments with FramEngine and the retrained systems are carried out ten times, with different random initializations. Scores are averaged across the ten runs and 95\% confidence levels for the scores are reported as well. \subsection{Results} Figure \ref{lcurves} displays the learning curves for the {\sc p9} data. We consider the fully supervised sequence labelers as the upper bound, since they are trained on gold-standard data. We notice that they achieve optimal F-score at around 250 utterances. Before that, their accuracy scores are marred by unseen words in the evaluation set, something that the weakly supervised FramEngine approach is able to overcome through its looser generalization properties. Retraining using the sequence labelers (Figure \ref{lcurves}(a)), trained on the automatically tagged data, improves F-scores for nearly all training sizes over FramEngine. For this task, retraining using conditional random fields generally yields more favorable learning curves than using memory-based learning. The large leaps in the curves in Figure \ref{lcurves} are to a great extent related to a shift in the user's lexicon over time. In the test set (featuring recordings during the end of the data collection process), the card value `king' is always referred to as 'heer' (English: {\em Sir}), whereas initially, this card value is always referred to as 'koning' (English: `king'). The word 'heer' starts to appear in the training set after the 200th utterance, thereby causing a significant leap for all of the approaches. Retraining through PCFG induction (Figure \ref{lcurves}(b)) similarly suffers from out-of-vocabulary words and, additionally, unseen grammatical productions in the evaluation set on smaller training sizes. Its continuing performance is fairly constant, although it seldom outperforms FramEngine in a convincing manner. Figure \ref{lcurves}(b) shows two PCFG-curves: one that expresses performance of 10 individual PCFGs for each FramEngine initialization (single run) and one that joins the data from all the runs and induces one single PCFG (all runs). Joining data over initializations dramatically improves the number of structures in the evaluation set that are covered by the grammars, while precision does not seem to suffer, thereby yielding higher F-scores for most training set sizes over 250. These experiments show that, although FramEngine achieves workable F-scores using a weakly supervised approach, we can automatically increase F-scores through retraining. For this task, sequence labeling is the recommended retraining technique, although PCFGs can also be observed to increase F-scores for this task. The latter result is encouraging, since it allows for the weakly supervised induction of a classic command \& control interface that restricts the acoustic search space by means of a context-free grammar. \subsection{PCFG induction: a qualitative analysis} \begin{figure} \begin{center} \small \begin{tabular}{llll} {\tt ROOT} & $\rightarrow$ & {\tt DC} [0.0824324]\\ {\tt ROOT} & $\rightarrow$ & {\tt O DC} [0.331081]\\ {\tt ROOT} & $\rightarrow$ & {\tt F O T} [0.586486]\\ {\tt DC} & $\rightarrow$ & {\em kaarten omdraaien} [0.593054]\\ {\tt DC} & $\rightarrow$ & {\em nieuwe kaarten omdraaien} [0.131062]\\ {\tt DC} & $\rightarrow$ & {\em omdraaien} [0.275885]\\ {\tt F} & $\rightarrow$ & {\tt S V} [1.0]\\ {\tt T} & $\rightarrow$ & {\tt TF} [0.0909515]\\ {\tt T} & $\rightarrow$ & {\tt S V} [0.909049]\\ {\tt S} & $\rightarrow$ & {\tt c} [0.249707]\\ {\tt S} & $\rightarrow$ & {\tt d} [0.264478]\\ {\tt S} & $\rightarrow$ & {\tt h} [0.233763]\\ {\tt S} & $\rightarrow$ & {\tt s} [0.252052]\\ {\tt V} & $\rightarrow$ & {\tt 1} [0.0763444]\\ {\tt V} & $\rightarrow$ & {\tt 2} [0.0617492]\\ {\tt V} & $\rightarrow$ & {\tt 3} [0.0617492]\\ {\tt V} & $\rightarrow$ & {\tt 4} [0.084428]\\ {\tt V} & $\rightarrow$ & {\tt 5} [0.0911643]\\ {\tt V} & $\rightarrow$ & {\tt 6} [0.0862243]\\ {\tt V} & $\rightarrow$ & {\tt 7} [0.0739868]\\ {\tt V} & $\rightarrow$ & {\tt 8} [0.0817335]\\ {\tt V} & $\rightarrow$ & {\tt 9} [0.086112]\\ {\tt V} & $\rightarrow$ & {\tt 10} [0.0793758]\\ {\tt V} & $\rightarrow$ & {\tt 11} [0.0673627]\\ {\tt V} & $\rightarrow$ & {\tt 12} [0.0718536]\\ {\tt V} & $\rightarrow$ & {\tt 13} [0.0779162]\\ {\tt O} & $\rightarrow$ & {\em kaarten} [0.13268]\\ {\tt O} & $\rightarrow$ & {\em nieuwe} [0.252725]\\ {\tt O} & $\rightarrow$ & {\em op} [0.614595]\\ \hline {\tt 1} & $\rightarrow$ & {\em aas} [1.0]\\ {\tt 2} & $\rightarrow$ & {\em twee} [1.0]\\ {\tt 3} & $\rightarrow$ & {\em drie} [1.0]\\ {\tt 4} & $\rightarrow$ & {\em vier} [1.0]\\ {\tt 5} & $\rightarrow$ & {\em vijf} [1.0]\\ {\tt 6} & $\rightarrow$ & {\em zes} [1.0]\\ {\tt 7} & $\rightarrow$ & {\em zeven} [1.0]\\ {\tt 8} & $\rightarrow$ & {\em acht} [1.0]\\ {\tt 9} & $\rightarrow$ & {\em negen} [1.0]\\ {\tt 10} & $\rightarrow$ & {\em tien} [1.0]\\ {\tt 11} & $\rightarrow$ & {\em boer} [1.0]\\ {\tt 12} & $\rightarrow$ & {\em dame} [1.0]\\ {\tt c} & $\rightarrow$ & {\em klaveren} [1.0]\\ {\tt d} & $\rightarrow$ & {\em ruiten} [1.0]\\ {\tt h} & $\rightarrow$ & {\em harten} [1.0]\\ {\tt s} & $\rightarrow$ & {\em schoppen} [1.0]\\ \end{tabular} \end{center} \caption{Probabilistic Context-Free Grammar and lexicon (induced in a weakly supervised manner). For display purposes, only productions that occur more than 0.5\% of the time were used to compile the PCFG. The non-terminals are {\bf ROOT}, {\bf D}eal{\bf C}ard, {\bf F}rom, {\bf T}arget, {\bf S}uit, {\bf V}alue, {\bf O}. (induced in run-1 at training set size 761)} \label{pcfgexample} \end{figure} While the F-scores of the PCFG-retraining approach trail compared to those of the retrained sequence labelers, the former presents an interesting opportunity for interpretability. Looking at the induced PCFGs can provide us with further insight into how the structural properties of the language are being modeled. The grammar in Figure \ref{pcfgexample} corresponds rather well with our intuitions for this task. Apart from an artifact (production T$\rightarrow$TF cannot reach terminal nodes) and a needlessly ambiguous handling of the tokens {\em nieuwe} (new), {\em kaarten} (cards) and {\em omdraaien} (turn over), the induced PCFG presents a clean description of the grammar used in the utterances of the training set. The probabilities for the different card suits are evenly distributed, as are their card values. The two different frame types are triggered by three ROOT rules, two for the {\sc dealcard} frame, one for the {\sc movecard} frame. Interestingly, while the grammar in Figure \ref{pcfgexample} excludes infrequent rules (such as ROOT $\rightarrow$ F T O T O F O T), applying this kind of filtering in practice yields significantly lower F-scores during the experiments, as these productions provide coverage for idiosyncratic utterances containing repairs and the like. \section{Conclusion and Future work} \label{conclusion} This paper described research on data collected for a command \& control interface for the card game Patience. The task of associating components of a command to slots in semantic frame representations of the intended control was already established with a fair degree of accuracy using a semantic frame induction technique based on non-negative matrix factorization and a hierarchical hidden markov model (FramEngine). This paper improves on this result by applying retraining using a discriminative sequence labeler as a post-processing step. Additional retraining experiments using probabilistic context-free grammar induction likewise show improvements when used as a post-processing step. Next steps in this research should investigate whether these retraining techniques can yield similar accuracy increases when applied on the acoustic portion of the {\sc patcor} data. It will be particularly interesting to see whether the PCFG induction technique can yield a similarly transparent collection of productions as displayed in Figure \ref{pcfgexample}, when confronted with a noisy set of observations. We will also investigate the advantage of the retraining techniques on other data sets, such as the grammatically less complex home automation data, collected in the context of the ALADIN project \cite{ons2013self}, but also the ROBOCUP data \cite{Chen2008}, which in recent years has become an interesting benchmark to gauge advances in this field. Finally, further research efforts should investigate whether the retraining techniques, now used as a post-processing step, can be compiled into FramEngine so that decoding can be achieved in a single processing sweep. \section{Acknowledgments*} This research described in this paper was funded by IWT-SBO grant 100049 (ALADIN). The {\sc patcor} dataset is available from \url{https://github.com/clips/patcor}. We would like to thank Jort Gemmeke, Hugo Van hamme and Bart Ons for their valued input on the research described in this paper. \bibliographystyle{acl}
{'timestamp': '2019-06-18T02:06:09', 'yymm': '1906', 'arxiv_id': '1906.06493', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06493'}
arxiv
\section{Experiment details} \paragraph{} \subsection{Dataset description} \par \textbf{MNIST}: The classic MNIST dataset \cite{lecun1998gradient}, randomly split into 10 different sections. Note that this dataset has not been generated in a real federated setting having IID client samples. \par \textbf{Permuted MNIST (P-MNIST)}: The MNIST dataset is randomly split into 10 sections, and a random permutation of the pixels is applied on every section. First used in \cite{zenke2017continual} in the context of CL. \par \textbf{FEMNIST}: This dataset consists of a federated version of the EMNIST dataset \cite{cohen2017emnist}, maintained by the \emph{LEAF} project \cite{caldas2018leaf} Different clients correspond to different writers. We sub-sample 10 random writers from those with at least 300 samples. \par \textbf{Vehicle Sensors Network (VSN)}\footnote{\url{http://www.ecs.umass.edu/~mduarte/Software.html}}: A network of 23 different sensors (including seismic, acoustic and passive infra-red sensors) are place around a road segment in order to classify vehicles driving through. \cite{duarte2004vehicle}. The raw signal is featurized in the original paper into 50 acoustic and 50 seismic features. We consider every sensor as a client and perform binary classification of assault amphibious vehicles and dragon wagon vehicles. \par \textbf{Human Activity Recognition (HAR)}\footnote{\url{https://archive.ics.uci.edu/ml/datasets/Human+Activity+Recognition+Using+Smartphones}}: Recordings of 30 subjects performing daily activities are collected using a waist-mounted smart-phone with inertial sensors. The raw signal is divided into windows and featurized into a 561-length vector \cite{anguita2013public}. Every individual correspond to a different client and we perform classification of 6 different activities (e.g. sitting, walking). A comprehensive description of the statistics of the datasets used is available in \Cref{tab:dataset}. \subsection{Experiment setting} All networks employed are multilayer perceptrons (MLP) with two hidden dense flipout layers \cite{wen2018flipout} with 100 units and ReLU activation functions. Dropout with parameter 0.3 is used before every dense layer. The Monte Carlo estimate of the gradient is performed in all the experiment using 20 samples. In all the experiments, {\tt VIRTUAL} has been evaluated training the clients in an incremental fashion, in fixed order, with 3 refinements per client. \par Using the notation of the original paper \cite{mcmahan2017communication}, {\tt FedAvg} has been evaluated in all experiments with a fraction of updated clients per round $C=0.2$ and a number of epochs per round $E=1$, that has been show to guarantee converge in all scenarios \cite{mcmahan2017communication,caldas2018leaf}. The total number of rounds is chosen such that every client is trained on average for a number of epochs that is equal to that of the {\tt VIRTUAL} experiments. \par We further compare our algorithm with \emph{Local} and \emph{Global} baselines that are obtained respectively training one separate model per client, and training one single model on centralized data. Global does not comply with the generic federated setting and is reported only as a comparison. \par Implementation of {\tt VIRTUAL} is based on \emph{tensorflow} \cite{abadi2016tensorflow} and \emph{tensorflow distributions} \cite{dillon2017tensorflow} packages. \footnote{Code and full details on the hyper-parameter used are available at \url{https://github.com/lucori/virtual}} The implementation of {\tt FedAvg} is taken from the \emph{Leaf} benchmark for federated learning settings \cite{caldas2018leaf}. \subsection{Results} In \Cref{tab:results} we show the advantages given by the multi-task learning framework in the federated setting. In the table we measure the average categorical accuracy over all tasks of the respective dataset. Every experiment has been repeated over 5 random 25\% train test splits, and we report mean and standard deviation over the runs. \par We can see that the performance of all the algorithms strongly depend on the degree of heterogeneity of the dataset considered. In particular the \emph{Global} baseline is among the top performing methods only on the MNIST dataset, that has been generated in IID fashion. Strongly non-IID scenarios are depicted by the P-MNIST and VSN datasets, that have significantly dissimilar feature spaces among clients (P-MNIST features are given by random permutations, while VSN encompasses a wide spectrum of different sensors). In these scenarios the performance of both \emph{Global} and {\tt FedAvg} degrades while $\emph{Local}$ models enjoy high performances, being tuned to the specific data distribution. \par We can see that {\tt VIRTUAL} maintain the top performance in the whole sprectrum of federated scenarios, being on par with \emph{Global} and {\tt FedAvg} on IID datasets, and with \emph{Local} models on strongly non-IID settings. It also outperforms other methods on FEMNIST and HAR, that are datasets that best represent the multi-task learning setting, as they encompass different users gathering data in very similar but distinct conditions. \begin{table*} \caption{Multi-task average test accuracy. Mean and standard deviation over 5 train-test splits.} \label{tab:results} \centering\ra{1.3} \begin{tabular}{@{}rrrrrrr@{}} \toprule \B Method & \B MNIST$^*$ & \B FEMNIST & \B P-MNIST& \B VSN & \B HAR\\ \midrule \emph{Global}$^*$ &\B 0.9678\footnotesize{\rpm0.0007} & 0.44\footnotesize{\rpm0.02} &0.919\footnotesize{\rpm0.004} & 0.926\footnotesize{\rpm0.005} &0.797\footnotesize{\rpm0.006}\\ \emph{Local} &0.9511\footnotesize{\rpm0.0020} & 0.51\footnotesize{\rpm0.01} & \B 0.950\footnotesize{\rpm0.003} &\B 0.960\footnotesize{\rpm0.003} &0.940\footnotesize{\rpm0.001} \\ {\tt FedAvg} &\B 0.9675\footnotesize{\rpm0.0004} &0.45\footnotesize{\rpm0.05}& 0.905\footnotesize{\rpm0.002} & 0.916\footnotesize{\rpm0.007} & \B 0.944\footnotesize{\rpm0.004} \\ {\tt Virtual} &\B 0.9666\footnotesize{\rpm0.0017} & \B 0.56\footnotesize{\rpm0.01} & \B0.949\footnotesize{\rpm0.001} & \B 0.960\footnotesize{\rpm0.002} &\B 0.944\footnotesize{\rpm0.001} \\ \bottomrule \end{tabular} \end{table*} \section{Introduction} \label{section:intro} \input{introduction.tex} \section{The {\tt VIRTUAL} algorithm} \input{VIRTUAL_algorithm.tex} \section{Related Work} \input{related_work.tex} \section{Experiments} \input{experiments.tex} \section{Conclusion} \input{conclusion.tex} \printbibliography \end{document} \subsection{The Bayesian network} Assume a star-shaped Bayesian network with a server $S$ with model parameters $\bm{\theta}$, as well as $K$ clients with model parameters $\{\bm{\phi}_i\}_{i=1}^K$. Assume that every client is a discriminative model distribution over the input given by $p(y_i^{(n)}| \bm{x}_i^{(n)}, \bm{\theta}, \bm{\phi}_i)$ (a naive extension of the work could consider also generative models). Each dataset $\mathcal{D}_i$ is private to client $i$, hence it is not accessible to any other client or the central server $S$, and has a likelihood that factorizes as $p(\mathcal{D}_i| \bm{\theta},\bm{\phi_i}) = \prod_{n=1}^{N_i}p(y_i^{(n)}| \bm{x}_i^{(n)},\bm{\theta}, \bm{\phi}_i)$. Following a Bayesian approach, we assume a prior distribution over all the network parameters $p(\bm{\theta},\bm{\phi_1},\dots,\bm{\phi_K})$. The posterior distribution over all parameters, given \emph{all} datasets $\mathcal{D}_{1:K} = \{\mathcal{D}_1,\dots,\mathcal{D}_k\}$ reads then \begin{equation} \label{eq:posterior} p(\bm{\theta},\bm{\phi_1},\dots,\bm{\phi_K} | \mathcal{D}_{1:K}) \propto \frac{1}{p(\bm{\theta})^{K-1}} \prod_{i=1}^K p(\bm{\theta},\bm{\phi_i} | \mathcal{D}_i) \end{equation} where we enforce that client-data is conditionally independent given server and client parameters, $p(\mathcal{D}_{1:K}| \bm{\theta},\bm{\phi_1},\dots,\bm{\phi_K}) = \prod_{i=1}^K p(\mathcal{D}_i| \bm{\theta},\bm{\phi_i})$, and a factorization of the prior as $p(\bm{\theta},\bm{\phi_1},\dots,\bm{\phi_K}) = p(\bm{\theta}) \prod_{i=1}^K p(\bm{\phi_i})$. The Bayesian network is illustrated in \Cref{fig:bayesian_net}. \input{bayesian_net.tex} \subsection{The optimization procedure} The posterior given in \Cref{eq:posterior} is in general intractable and hence we have to rely on an approximation inference scheme (e.g.\ variational inference, sampling, expectation propagation \cite{bishop2006pattern}). Here we propose an expectation propagation ({\tt EP}) like approximation algorithm \cite{minka2001expectation} that has been shown to be effective and to outperform other methods when applied in the continual learning (CL) setting \cite{bui2018partitioned,nguyen2017variational}. Let us denote the collection of all the client parameters by $\bm{\phi} = (\bm{\phi}_1,\dots,\bm{\phi}_K)$. Then we define a \emph{proxy} posterior distribution that factorizes into a server and a client contribution for every client $i$ as \begin{equation} \label{eq:factorization} q(\bm{\theta},\bm{\phi}) = s(\bm{\theta}) c(\bm{\phi}) = \left(\prod_{i=1}^K s_i(\bm{\theta}) \right) \left(\prod_{i=1}^K c_i(\bm{\phi}_i) \right). \end{equation} The fully factorization of both server and client parameters allows us in the following to perform a client update that is independent from other clients, and to perform a server update in the form of an aggregated posterior that preserves the privacy. \par Given a factorization of this kind, the general {\tt EP} algorithm refines one factor at each step. It first computes a refined posterior distribution where the refining factor of the proxy is replaced with the respective factor in the true posterior distribution. It then performs the update minimizing the Kullback-Leibler (KL) divergence between the full proxy posterior distribution and the refined posterior. The optimization to be performed for our particular Bayesian network and factorization is given by the following. \begin{proposition} Assuming that at step $t$ the factor $i$ is refined, then the proxi pdf $s_i^{(t)}(\bm{\theta})$ and $c^{(t)}_i(\bm{\phi}_i)$ are found minimizing the variational free energy function \begin{align} \mathcal{L}(s_i(\bm{\theta}),c_i(\bm{\phi}_i)) = D_{KL}\left(s_i(\bm{\theta}) \frac{s^{(t-1)}(\bm{\theta})}{s^{(t-1)}_i(\bm{\theta})}\bigg|\bigg| p(\bm{\theta})\frac{s^{(t-1)}(\bm{\theta})}{s^{(t-1)}_i(\bm{\theta})} \right) + &D_{KL}\left(c_i(\bm{\phi}_i) || p(\bm{\phi}_i) \right) + \nonumber\\ &-\mathbb{E}_{\substack{s^{(t)}(\bm{\theta})\\c_i(\bm{\phi}_i)}} \log p(\mathcal{D}_i|\bm{\theta},\bm{\phi}_i) \label{eq:free_energy} \end{align} where $s^{(t)}(\bm{\theta}) = s_{i}(\bm{\theta})\prod_{j \ne i}^K s_j^{(t-1)}(\bm{\theta})$ is the new posterior over server parameters. \end{proposition} \begin{proof} At step $t$ the global posterior for server parameters is $s^{(t)}(\bm{\theta}) = s_{i}(\bm{\theta})\prod_{j \ne i}^K s_j^{(t-1)}(\bm{\theta})$ and analogously the client parameters distribution reads $c^{(t)}(\bm{\phi}) = c_{i}(\bm{\phi}_i)\prod_{j\ne i}^K c_j^{(t-1)}(\bm{\phi}_j)$. Then the {\tt EP}-like update for the model described is given by minimizing the following KL divergence w.r.t $ s_{i}(\bm{\theta})$ and $c_{i}(\bm{\phi}_{i})$ \begin{equation*} \begin{split} D_{KL}&\left(s^{(t)}(\bm{\theta}) c^{(t)}(\bm{\phi}) \bigg|\bigg| \frac{s^{(t)}(\bm{\theta}) c^{(t)}(\bm{\phi})}{s_{i}(\bm{\theta}) c_{i} (\bm{\phi}_i)} p(\bm{\theta},\bm{\phi}_i | \mathcal{D}_i) \right) = \\ &= \!\begin{multlined}[t] \int d \bm{\theta} \ s^{(t)}(\bm{\theta}) \log s_{i}(\bm{\theta}) \int d \bm{\phi} \ c^{(t)}(\bm{\phi}) + \int d \bm{\theta}\ s^{(t)}(\bm{\theta}) \int d \bm{\phi}\ c^{(t)}(\bm{\phi}) \log c_{i}(\bm{\phi}_i) + \\ - \int d \bm{\theta}\ d \bm{\phi}\ s^{(t)}(\bm{\theta}) c^{(t)}(\bm{\phi}) \log p(\bm{\theta},\bm{\phi}_i | \mathcal{D}_i) = \end{multlined} \\ &= \!\begin{multlined}[t] \int d \bm{\theta}\ s^{(t)}(\bm{\theta}) \log \frac{s_{i}(\bm{\theta}) s^{(t)}(\bm{\theta}) }{s^{(t)}(\bm{\theta}) p(\bm{\theta})} + \int d \bm{\phi}_i\ c^{(t)}_i(\bm{\phi}_i) \log \frac{c_{i}^{(t)}(\bm{\phi}_i)}{p(\bm{\phi}_i)} + \\ - \int d \bm{\theta}\ s^{(t)}(\bm{\theta}) \int d \bm{\phi}_i\ c^{(t)}_i(\bm{\phi}_i) \log p(\mathcal{D}_i|\bm{\theta},\bm{\phi}_i) \end{multlined} \end{split} \end{equation*} where the second equality comes from the normalization of client and server pdfs and from Bayes rule $p(\bm{\theta},\bm{\phi}_i|\mathcal{D}_i) \propto p(\mathcal{D}_i|\bm{\theta},\bm{\phi}_i) p(\bm{\phi}_i) p(\bm{\theta})$. Notice also that $\frac{s_{i}(\bm{\theta})} {s^{(t)}(\bm{\theta})} = \frac{s_{i}^{(t-1)}(\bm{\theta})}{s^{(t-1)}(\bm{\theta})}$ because of the factorization in \Cref{eq:factorization}, and hence \Cref{eq:free_energy} is proved. \end{proof} We can see that the variational free energy in \Cref{eq:free_energy} decomposes naturally into two parts. The terms that involve the client parameters $c_i(\bm{\phi}_i)$ correspond to the variational free energy terms of \emph{Bayes by backprop} \cite{blundell2015weight}. Note that, except for the natural complexity cost given by the second KL term, no additional regularization is applied on the client parameters, that can hence be trained efficiently and network agnostic. The terms that involve the server posterior are instead the likelihood cost and the first KL term. This regularization restricts the server to learn an overall posterior that does not drift from a posterior distribution obtained replacing the current refining factor by the prior. This constraint effectively forces the server to progress in a CL fashion \cite{nguyen2017variational}, learning from new federated datasets and avoiding catastrophic forgetting of the ones already seen. \par The whole free energy in \Cref{eq:free_energy} can be optimized using gradient descent and unbiased Monte Carlo estimates of the gradients with reparametrization trick \cite{kingma2013auto}. For simplicity we use a Gaussian mean-field approximation of the posterior, hence for server and client parameters the factorization reads respectively $s_i(\bm{\theta}) = \prod_{d=1}^{D^s} \mathcal{N}(\theta_{d}| \mu_{id}^s, \sigma_{id}^s)$ and $c_i(\bm{\phi}_i) = \prod_{d=1}^{D_i^c} \mathcal{N}(\phi_{id}| \mu_{id}^c,\sigma_{id}^c)$, where $D^s$ and $\{D_i^c\}_{i=0}^K$ are the total number of parameters of the server and of the client networks. A depiction of the full graphical model of the approximated variational posterior is given in \Cref{fig:bayesian_net_proxy}. The pseudo-code of {\tt VIRTUAL} is described in \Cref{alg:virtual}. Notice that similarly to {\tt FedAvg}, privacy is preserved since at any time the server get access only to the overall posterior distribution $s(\bm{\theta})$ and never to the individual factor $s_i(\bm{\theta})$ and $c_i(\bm{\theta})$, that are visible only to the respective client. \begin{algorithm} \caption{{\tt VIRTUAL}} \label{alg:virtual} \begin{algorithmic}[1] \Require{datasets $\{\mathcal{D}_1,\dots,\mathcal{D}_k\}$, $N$ number of total refinements, priors $p(\bm{\theta}), \{p(\bm{\phi}_i)\}_{i=1}^K$} \Statex \State initialize all the pdfs $c_i^{(0)}(\bm{\phi}_i)$ and $s_i^{(0)}(\bm{\theta})$ \State $s^{(0)}(\bm{\theta}) \gets \prod_i s_i^{(0)}(\bm{\theta})$ \For{ $t = 1,2 \dots, N$ } \State choose a client $i$ to be refined \State client computes the new server prior $p(\bm{\theta})\frac{s^{(t-1)}(\bm{\theta})}{s^{(t-1)}_i(\bm{\theta})}$ \State $s_i^{(t)}(\bm{\theta}),c^{(t)}_i(\bm{\phi}_i) \gets$ joint optimization of the variational free energy in \cref{eq:free_energy} on client $i$ \State client computes the new server posterior $s^{(t)}(\bm{\theta}) \gets \frac{s^{(t-1)}(\bm{\theta})}{s_i^{(t-1)}(\bm{\theta})} s_i^{(t)}(\bm{\theta})$ \State client sends $s^{(t)}(\bm{\theta})$ to the server \State server sends its new posterior $s^{(t)}(\bm{\theta})$ to all clients. \EndFor \end{algorithmic} \end{algorithm} We can further notice an interesting similarity of the {\tt VIRTUAL} algorithm to the \emph{Progress\&Compress} method for CL introduced in \cite{schwarz2018progress}, where a similar free energy is obtained heuristically by composing CL regularization terms and distillation cost functions \cite{hinton2015distilling}. \subsection{The server-client architecture} \label{sec:server_client_arch} The model for $p(\mathcal{D}_i | \bm{\theta},\bm{\phi}_i)$ has to be chosen in order to allow the client model to reuse knowledge extracted from the server and enlarging the effective sample size available for client $i$. In this work we use a model inspired by \emph{Progressive Networks} \cite{rusu2016progressive} that has been proved effective in CL, with lateral connections between server and client layers. Lateral connections feed the activations of the server at a given layer as an additive input to the client layer. Formally, for a multi-layer perceptron (MLP) model we can denote by $h^s_{l-1}$ the activation of the server layer at a depth $l-1$, then the subsequent activation of client $i$, $h^c_{il}$ reads \begin{equation} h^c_{il} = \sigma\left(\bm{\phi}_{il}^w h^c_{l-1} + \bm{\phi}^{\alpha}_{il} \odot \bm{\phi}^u_{il} \sigma(h^s_{l-1} + \bm{\phi}^b_{il}) + \bm{\phi}^c_{il}\right) \end{equation} where $\bm{\phi}_{il}^w, \bm{\phi}_{il}^u$ are weight matrices, $\bm{\phi}^{\alpha}_{il}$ is a weight vector that act as a gate, $\odot$ denotes the element-wise multiplication operator and $\bm{\phi}^b_{il}$ and $\bm{\phi}^c_{il}$ are trainable biases. \begin{figure} \centering \input{lateral_connection.tex} \end{figure} The client-server connection architecture for a 2 hidden-layers MLP is depicted in \Cref{fig:lateral_connection}. Note as an example that for the architecture used in \Cref{fig:lateral_connection}, the client parameter vector reads $\bm{\phi}_i = \{\bm{\phi}_{il}^w,\bm{\phi}_{il}^u,\bm{\phi}^{\alpha}_{il},\bm{\phi}^b_{il},\bm{\phi}^c_{il}\}_{l=1}^3$.
{'timestamp': '2019-06-17T02:16:38', 'yymm': '1906', 'arxiv_id': '1906.06268', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06268'}
arxiv
\section{Introduction} The classical theory of learning suggests \cite{vapnik1999overview} that a huge number of parameters of the machine learning model usually leads to the phenomenon of overfitting, i.e. to a high generalization error (a significant difference between the behavior of the model on the training and on the test samples). At the same time, modern architectures of deep neural networks are significantly overparameterized - it is not an exception when the number of trained parameters is ten times smaller than the size of the training sample (see Table \ref {DNN}, here $ train $ is the size of the training sample, $ test $ is the size of the test sample, $ k $ is the number of classes in the classification problem, $ d $ is the dimension of one element of the dataset). \begin{table}[] \centering \caption{Typical parameters of neural networks architectures and their corresponding datasets} \label{DNN} \begin{tabular}{@{}cc|cc@{}} \toprule \textbf{DNN architecture} & \textbf{Number of parameters} & \textbf{Dataset} & $(train, test, k, d)$ \\ \midrule AlexNet & 62 378 344 & ILSVRC & $(1,2\text{M}, \quad 100\text{K},\quad 1000, \quad 256 \times 256 \times 3)$ \\ LeNet & 60 213 280 & MNIST & $(55\text{K},\quad 10\text{K},\quad 10,\quad 28 \times 28)$ \\ VGG & 102 897 440 & CIFAR-10 & $(50\text{K},\quad 10\text{K},\quad 10,\quad 3 \times 32 \times 32)$ \\ GoogleNet & 11 193 984 & CIFAR-100 & $(50\text{K},\quad 10\text{K},\quad 100,\quad 3 \times 32 \times 32)$ \\ FC1024 + softmax & 814 090 & SVHN & $(73\text{K},\quad 26\text{K},\quad 10,\quad 3 \times 32 \times 32)$ \\ \bottomrule \end{tabular} \end{table} Despite this, classifiers based on deep neural networks demonstrate a high generalizing ability in classification problems. Such a gap between theory and practice requires further study of the subject field. Despite the nonconvexity and immense dimensionality of the optimization problem, it is widely believed that most local minima of the loss function in neural networks are about approximately equal in terms of the generalizing ability \cite{choromanska2015loss} \cite{kawaguchi2016deep}. In a recent article \cite{zhang2016understanding}, the authors discovered an unexpected property of many popular architectures of deep neural networks: they can fit a dataset with random labels. A classifier with such properties should have a very large $VC$-dimension, which, according to the classical result \cite{vapnik1999overview}, indicates that the upper bound of the generalization error is greatly overestimated. The growing popularity of neural networks is followed by the applying of these models of machine learning into our everyday life. In this regard, there are acute problems of understanding the limits of applicability and possible difficulties associated with their implementation, especially in areas where this may be associated with very high requirements for reliability (for example, in self-driven vehicles). In this article, we show that there are critical points of neural networks with extremely low generalizing ability. The procedure for creating such points suggests that there should be a lot of them exponentially (in terms of the training sample size), but they are almost never found in the usual learning process. We call such points \textit{points of extreme retraining}. It is important to note, that such points are not necessarily local minima, since checking the positive definiteness of Hessian weights seems impractical for the task, but the gradient norm tends to zero. \section{Construction of extreme overfitting weights} Based on the \cite{zhang2016understanding} ideas, we decided to go even further and find neural network weights that demonstrate a very low value of the loss function on the training sample and, at the same time, a high value of the loss function on the test sample. The study of such points is interesting both from algorithmic and theoretical points of view. Such points on the surface of the loss function was obtained in the process of learning the neural network and will have a low generalizing ability. The idea of obtaining points of extreme overfitting is pretty simple: with a specific neural network architecture, training and test datasets, we intentionally corrupt the labels from the test sample (see Figure \ref{fig: sad_training}) to clearly wrong ones. Duplicate this part of the sample such many times as it is necessary for the corrupted sample of the test to be comparable in size with the training sample. We add the resulting corrupted test sample to the original training sample, creating a corrupted training sample that is about twice the original training sample. After that, we train this neural network model on a corrupted training sample, using traditional stochastic first-order optimization methods. A neural network has a sufficient number of trained parameters to remember the entire data set, and during testing performance on initial test sample, almost always has to give incorrect answers, because it remembers the objects contained in it with a wrong label. \begin{figure}[h] \center{\includegraphics[width=0.41\linewidth]{sad_training.pdf}} \caption{Constructing corrupted training dataset} \label{fig:sad_training} \end{figure} Note, that the surface of the loss function depends not only on the parameters of the neural network, but also on the dataset on which the training takes place, which means that, generally speaking, the optimization problem is solved for another function. However, we note that the resulting corrupted sample completely contains the original training sample, and, in the case of 100 \% accuracy of the corrupted training sample, we will have almost zero percentage of errors on the usual training dataset. In addition, it is necessary to check what these points are in terms of their location on the true surface of the loss function (due to the initial training set). \begin{algorithm}[htb] \caption{Constructing sad points} \label{alg:Framwork} \begin{algorithmic}[1] \Require $\;\;S_{train}, S_{test}$ - usual train and test sets in $k$-class classification problem; $Loss(\mathbf{w}, S)$, which depends on weights $\mathbf{w}$ and data $S$ \Ensure Sad point $\mathbf{w_s}: Loss(\mathbf{w_s}, S_{test}) \gg Loss(\mathbf{w_s}, S_{train})$ \State Constructing corrupted test set $$\widehat{S_{test}} = \{ (x_1, \widehat{y_{x_1}}), \dots, (x_{test}, \widehat{y_{x_{test}}}) \} \;\; \textrm{, where }$$ $$\widehat{y_{x_p}} = \begin{cases} y_{x_p}, &\text{ with $0$ probability} \\ \text{other label,} &\text{ with $\frac{k-1}{k}$ probability} \end{cases} \forall p \in [1, test]$$ \State Constructing corrupted train set via concatenation train set and corrupted test set $t = \left\lfloor\frac{train}{test}\right\rfloor + 1$ times: $$\widehat{S_{train}} = \{S_{train}, \underbrace{\widehat{S_{test}}, \dots, \widehat{S_{test}}}_{t}\}$$ \State Finding critical point of $Loss$ using stochastic optimization method $$\mathbf{w_s} = \mathop{\rm argmin}\limits_{\mathbf{w}}\{Loss(\mathbf{w}, \widehat{S_{train}})\}$$ \label{code:fram:select} \Return $\mathbf{w_s}$; \end{algorithmic} \end{algorithm} \vspace*{-0.6cm} \section{Results} The graphs below shows visualization of the learning processes of different models of neural networks on corrupted datasets. As can be seen from the graphs, all the models studied in the work of all datasets in the learning process on the training set, show a result close to 100\%. A detailed description of the considered architectures, experiments, software and hardware is available in the \ref{sec:exp_par} section. The minimized loss function is cross entropy, the logarithm on the right side is taken element-wise, and $ p_s (\mathbf{w}) $ denotes the model prediction for the $ s \in S $ sample object with the model parameters $ \mathbf{w} $ representing the vector output (with dimension 10) layer softmax. \[ Loss(S, \mathbf{w}) = -\sum_{s \in S} y_{s}^\top \log\left(p_{s}(\mathbf{w})\right) =-\sum_{s \in S}\sum_{c=1}^{10} y_{s,c}\log\left(p_{s,c}(\mathbf{w})\right) \] \begin{figure}[H] \begin{minipage}[h]{0.33\linewidth} \center{\includegraphics[width=1.1\linewidth]{MLP_MNIST.pdf}} \end{minipage} \hfill \begin{minipage}[h]{0.33\linewidth} \center{\includegraphics[width=1.1\linewidth]{MLP_Fashion_MNIST.pdf}} \end{minipage} \hfill \begin{minipage}[h]{0.33\linewidth} \center{\includegraphics[width=1.1\linewidth]{MLP_CIFAR10.pdf}} \end{minipage} \begin{minipage}[h]{1\linewidth} \begin{tabular}{p{0.33\linewidth}p{0.33\linewidth}p{0.33\linewidth}} \centering a) MNIST & \centering b) Fashion MNIST & \centering c) CIFAR 10 \\ \end{tabular} \end{minipage} \vspace*{-1cm} \caption{Extreme overfitting process. MLP} \label{sad_MLP} \end{figure} Here are graphs of experiments with a fully connected network containing one hidden layer of 512 neurons (MLP) in various corrupted datasets. Neural network based on convolutional layers (CNN) and ResNet are also considered. Of the interesting features, it is worth noting that even the addition of regularization of $l_2$ does not prevent the model of finding such points, i.e. it allows an extreme overfitting of the network. In addition, the ResNet network, which demonstrates consistently higher results in image recognition tasks than the other networks, is overfitting faster than the usual fully connected network. \begin{figure}[H] \begin{minipage}[h]{0.33\linewidth} \center{\includegraphics[width=1.1\linewidth]{LeNet_MNIST.pdf}} \end{minipage} \hfill \begin{minipage}[h]{0.33\linewidth} \center{\includegraphics[width=1.1\linewidth]{LeNet_Fashion_MNIST.pdf}} \end{minipage} \hfill \begin{minipage}[h]{0.33\linewidth} \center{\includegraphics[width=1.1\linewidth]{LeNet_CIFAR10.pdf}} \end{minipage} \begin{minipage}[h]{1\linewidth} \begin{tabular}{p{0.33\linewidth}p{0.33\linewidth}p{0.33\linewidth}} \centering a) MNIST & \centering b) Fashion MNIST & \centering c) CIFAR 10 \\ \end{tabular} \end{minipage} \vspace*{-1cm} \caption{Extreme overfitting process. CNN} \label{sad_CNN} \end{figure} So, we empirically showed that on the surface of the loss function of popular neural network architectures there are critical points that provide a very poor generalizing ability of the model, that is, they show almost zero error on the training set and almost 100\% of errors on the test sample. In addition, it is very important to note that these critical points are also critical points on the surface of the loss function of neural networks in usual (not corrupted) data, since when performing a full vanilla gradient descent, the algorithm converges to a critical point with very low generalizing ability. \begin{figure}[H] \begin{minipage}[h]{0.33\linewidth} \center{\includegraphics[width=1.1\linewidth]{ResNet_MNIST.pdf}} \end{minipage} \hfill \begin{minipage}[h]{0.33\linewidth} \center{\includegraphics[width=1.1\linewidth]{ResNet_Fashion_MNIST.pdf}} \end{minipage} \hfill \begin{minipage}[h]{0.33\linewidth} \center{\includegraphics[width=1.1\linewidth]{ResNet_CIFAR10.pdf}} \end{minipage} \begin{minipage}[h]{1\linewidth} \begin{tabular}{p{0.33\linewidth}p{0.33\linewidth}p{0.33\linewidth}} \centering a) MNIST & \centering b) Fashion MNIST & \centering c) CIFAR 10 \\ \end{tabular} \end{minipage} \vspace*{-1cm} \caption{Extreme overfitting process. ResNet} \label{sad_ResNet} \end{figure} An important open question is the reason why such points are not usually encountered during the usual training procedure of a neural network. Our hypothesis is that such points are usually located quite further from the initialization in the space of weights with Euclidean distance. To do this, we measured the total Euclidean norm of vectorized neural network weights after a fixed number of iterations for normal learning and extreme overfitting. The histograms of the distribution of weights are presented in the images below: \begin{figure}[H] \begin{minipage}[h]{0.33\linewidth} \center{\includegraphics[width=1.1\linewidth]{weights_MLP_MNIST.pdf}} \end{minipage} \hfill \begin{minipage}[h]{0.33\linewidth} \center{\includegraphics[width=1.1\linewidth]{weights_MLP_FashionMNIST.pdf}} \end{minipage} \hfill \begin{minipage}[h]{0.33\linewidth} \center{\includegraphics[width=1.1\linewidth]{weights_MLP_CIFAR10.pdf}} \end{minipage} \begin{minipage}[h]{1\linewidth} \begin{tabular}{p{0.33\linewidth}p{0.33\linewidth}p{0.33\linewidth}} \centering a) MNIST & \centering b) Fashion MNIST & \centering c) CIFAR 10 \\ \end{tabular} \end{minipage} \vspace*{-1cm} \caption{The distribution of weights in the process of usual training(left) and extreme overfitting (right). MLP} \label{weights_MLP} \end{figure} Systematic empirical studies show that the points of extreme retraining are indeed located significantly farther from the initialization point of the network parameters for the same number of epochs as compared to usual training on uncorrupted dataset. \begin{figure}[H] \begin{minipage}[h]{0.33\linewidth} \center{\includegraphics[width=1.1\linewidth]{weights_LeNet_MNIST.pdf}} \end{minipage} \hfill \begin{minipage}[h]{0.33\linewidth} \center{\includegraphics[width=1.1\linewidth]{weights_LeNet_FashionMNIST.pdf}} \end{minipage} \hfill \begin{minipage}[h]{0.33\linewidth} \center{\includegraphics[width=1.1\linewidth]{weights_LeNet_CIFAR10.pdf}} \end{minipage} \begin{minipage}[h]{1\linewidth} \begin{tabular}{p{0.33\linewidth}p{0.33\linewidth}p{0.33\linewidth}} \centering a) MNIST & \centering b) Fashion MNIST & \centering c) CIFAR 10 \\ \end{tabular} \end{minipage} \vspace*{-1cm} \caption{The distribution of weights in the process of usual training(left) and extreme overfitting (right). CNN} \label{weights_CNN} \end{figure} Note, that the stochastic gradient descent algorithm launched from the point of extreme overfitting usually converges to a critical point with a good generalizing ability familiar to such algorithms, which indicates that such points are very narrow indentations on the surface of the neural network loss function. The concept of local minimum width for neural networks is discussed, for example, in \cite{dinh2017sharp}. \begin{figure}[h!] \begin{minipage}[h]{0.33\linewidth} \center{\includegraphics[width=1.1\linewidth]{weights_ResNet_MNIST.pdf}} \end{minipage} \hfill \begin{minipage}[h]{0.33\linewidth} \center{\includegraphics[width=1.1\linewidth]{weights_ResNet_Fashion_MNIST.pdf}} \end{minipage} \hfill \begin{minipage}[h]{0.33\linewidth} \center{\includegraphics[width=1.1\linewidth]{weights_ResNet_CIFAR10.pdf}} \end{minipage} \begin{minipage}[h]{1\linewidth} \begin{tabular}{p{0.33\linewidth}p{0.33\linewidth}p{0.33\linewidth}} \centering a) MNIST & \centering b) Fashion MNIST & \centering c) CIFAR 10 \\ \end{tabular} \end{minipage} \vspace*{-0.7cm} \caption{The distribution of weights in the process of usual training(left) and extreme overfitting (right). ResNet} \label{weights_ResNet} \end{figure} \section{Experimental setup} \label{sec:exp_par} \subsection{Neural Networks architectures and datasets} \begin{figure}[H] \begin{minipage}[h]{0.4\linewidth} \center{\includegraphics[width=0.95\linewidth]{mlp.eps}} \end{minipage} \hfill \begin{minipage}[h]{0.4\linewidth} \center{\includegraphics[width=0.95\linewidth]{cnn.eps}} \end{minipage} \hfill \begin{minipage}[h]{0.19\linewidth} \center{\includegraphics[width=1.2\linewidth]{block.pdf}} \end{minipage} \begin{minipage}[h]{1\linewidth} \begin{tabular}{p{0.4\linewidth}p{0.4\linewidth}p{0.19\linewidth}} \centering a) & \centering b) & \centering c) \\ \end{tabular} \end{minipage} \vspace*{-1cm} \caption{Studied DNN architectures: a) MLP, b) CNN, c) ResNet block\cite{he2016deep}.} \label{architectures} \end{figure} The following neural network architectures were considered: a fully connected neural network, a convolutional neural network that is inspired by LeNet \cite{le1989 handwritten} architecture, and also ResNet \cite{he2016deep}. Schemes of the considered architectures are shown in the figure \ref{architectures}. For a fully connected neural network (MLP), we used three layers with nonlinear activations of the form $ ReLU (x) = \ max \{0, x \} $, the dimension of the input layer is equal to the dimension of the vectorized image for the classification supplied to the input, i.e. 784 for MNIST and Fashion MNIST and 3072 for CIFAR 10. The number of neurons in the hidden layer is 512. The number of neurons in the output layer corresponds to the number of classes, i.e. 10 for all data sets. For the convolutional neural network (CNN), we used an architecture similar to LeNet \cite{le1989handwritten}. Three convolutional layers with a convolution core size of $ 5 \times 5 $ each contain 16, 32, and 64 filters, respectively. After the first two layers, the image size is reduced using the pooling method with a maximum function. The nonlinear activation function of the $ ReLU $ type is applied to the images obtained at the output of these layers. After the convolutional layers, the representation of the image is vectorized and fed to the input of a fully connected layer with the number of neurons 84, then $ ReLU $, then the last fully connected layer of $ softmax $ from among the neurons corresponding to the number of classes in the classification problem, i.e. 10 for all data sets. For the ResNet neural network, the classical architecture presented in the \cite{he2016deep} article was used with 64 neurons in the penultimate fully connected layer and 10 neurons in the last fully connected layer. Also note that the architecture has been changed to apply it to data sets from black and white images MNIST and Fashion MNIST (it was originally created to work with color images in CIFAR 10 and ImageNet) \begin{figure}[H] \begin{minipage}[h]{0.4\linewidth} \center{\includegraphics[width=0.95\linewidth]{MnistExamples.png}} \end{minipage} \hfill \begin{minipage}[h]{0.2\linewidth} \center{\includegraphics[width=0.95\linewidth]{fashion_mnist.png}} \end{minipage} \hfill \begin{minipage}[h]{0.39\linewidth} \center{\includegraphics[width=0.95\linewidth]{cifar10.png}} \end{minipage} \begin{minipage}[h]{1\linewidth} \begin{tabular}{p{0.4\linewidth}p{0.2\linewidth}p{0.39\linewidth}} \centering a) & \centering b) & \centering c) \\ \end{tabular} \end{minipage} \vspace*{-1cm} \caption{Images from datasets: a) MNIST, b) Fashion MNIST, c) CIFAR 10.} \label{dataset} \end{figure} The study was conducted using widely known in academic community datasets: MNIST \cite{lecun-mnisthandwrittetendigit-2010} Fashion MNIST \cite{xiao2017 / online}, CIFAR 10 \cite{krizhevsky2009learning}. Examples of images contained in these datasets for clarity, shown in the figure \ref{dataset}. The MNIST dataset contains 60,000 grayscale images with sizes of $ 28 \times 28$ in a training sample and 10,000 images of the same size in a test sample. It includes images of handwritten digits, divided into 10 classes corresponding to Arabic numerals. The Fashion MNIST dataset was created to test the machine learning algorithms created for the tasks of classifying images of a MNIST dataset in a new way, so it repeats the shape of the original dataset: 60,000 images of the same size in a training set and 10,000 in a test set. Images are divided into 10 classes: T-shirt/top, Trouser, Pullover, Dress, Coat, Sandal, Shirt, Sneaker, Bag, Ankle boot. The CIFAR 10 dataset contains 50,000 color images of $ 32 \times 32 \times 3$ in a training sample and 10,000 images of the same size in a test sample. Images are divided into 10 classes: airplane, car, bird, cat, deer, dog, frog, horse, ship, truck. \subsection{Software and hardware} The numerical experiments were conducted on the basis of the computing cluster of the Skolkovo Institute of Science and Technology NVIDIA DGX-1 with 8 V100 video cards and an Intel (R) Xeon (R) E5-2698 v4 @ 2.20 GHz processor with 80 logical cores. The software is written in Python using the PyTorch \cite{paszke2017automatic} library. The experiments carried out allow a parallel launch, which allowed us to run different models on different video cards to speed up the learning process. \subsection{Experimental methodology} Neural networks were trained using stochastic first-order optimization algorithms. In particular, all the graphs presented in the work were obtained using the Adam \cite{kingma2014adam} optimization algorithm with a constant length step of 0.001 and a batch size of 128. The choice of these hyperparameters is due to the stability of the results in the study. In addition, experiments were conducted with the classical algorithm of stochastic gradient descent \cite{robbins1951stochastic}, however, the experimental results did not change qualitatively. For each neural network architecture and for each dataset, we conducted 200 training sessions on a regular dataset and 200 training sessions on a corrupted dataset to obtain the typical weights that neural networks receive during usual training, as well as extreme overfitting points for further research. After each launch, the weights of the neural networks were initialized using the \texttt{torch.nn.init.xavier\_uniform} \cite{glorot2010understanding} method. The resulting weights were saved using the \texttt{torch.save} method for further analysis. \section{Related Work} Due to their extraordinary efficiency in practical tasks, neural networks became the focus of researches in a wide range of areas. Therefore, many works about different aspects of training neural networks were published. Here we will overview only small part of them, grouped by subject. Vapnik \cite{vapnik1999overview} obtained results about bounding generalization error using $VC$-dimension concept. Some estimations on $VC$-dimension of neural networks were also obtained \cite{sontag1998vc}. Zhang \cite{zhang2016understanding} showed through extensive systematic experiments, that modern DNN architectures can fit random labels. Choromanska et al.\cite{choromanska2015loss} investigated loss surfaces of multilayer networks using spin-glass model. Under uniformity, independence and redundancy assumptions they showed, that there is an area, that band local minima with lowest critical values of random loss function. Also, they showed, that number of local minima outside such area decreases exponentially. Moreover, they numerically performed, that most local minima are equivalent in terms of test accuracy. Kawaguchi \cite{kawaguchi2016deep} enhanced statement, mentioned in \cite{choromanska2015loss}. He also considered linear networks with squared loss function and proved that every local minima of such loss surface is a global minima. Despite the usual assumption of similarity of nature of training and test data, we still can obtain sad points of neural networks. \section{Conclusion} The article proposes a method for obtaining \textit{points of extreme overfitting} - weights of modern deep neural networks, at which they demonstrate accuracy close to 100 \% to the training set, simultaneously with almost zero accuracy on the test sample. Such critical points of the loss function of the neural network, despite the widespread opinion that the vast majority of them have equally good generalizing abilities, have a large generalization error. In this paper, their properties were investigated, in particular, it was empirically shown that, on average, they are located much farther from the initialization weights than the points obtained during normal training. In addition, they do not interfere with stochastic gradient descent, since the initialization of such an algorithm for optimizing points leads to a critical point, which is not an extreme point of retraining. The work contains systematic numerical experiments for modern models of deep neural networks, which are well suited for practical problems of image classification: fully connected networks, convolutional networks, and ResNet. For all data sets, we managed to get extreme overfitting points and study their properties. The presence of such points in neural networks is a good reason for further analytical study of the issue of training neural networks.
{'timestamp': '2019-07-04T02:12:34', 'yymm': '1906', 'arxiv_id': '1906.06295', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06295'}
arxiv
\section{Appendices} \label{sec:appendix} Here, we explain our experiment setup for the three tasks: machine comprehension, natural language inference, and text chunking. For each task, we describe the model setup, hyperparameters, and data splits. For all three tasks, we used Adam~\cite{paszke2017automatic} for training and use 300 dimensional GloVe~\cite{pennington2014glove} vectors (trained on 840B tokens) as word embeddings. \subsection{Machine Comprehension} The SQuAD (v1.1) dataset consists of $87,599$ training instances and $10,570$ development examples. Firstly, for a specific percentage of training data, we sample from the original training set. Then we split the sampled set into 9/1 folds for training and development. The original development set is reserved for testing only. This is because that the official test set is hidden, and the number of models we need to evaluate is impractical for accessing official test set. In our implementation of the BiDAF model, we use a learning rate $0.001$ to train the model for $20$ epochs. Dropout~\cite{srivastava2014dropout} rate is $0.2$. The hidden size of each direction of BiLSTM encoder is $100$. For ELMo models, we train for $25$ epochs with learning rate $0.0002$. The rest hyperparameters are the same as in ~\cite{peters2018deep}. Note that we did neither pre-tune nor post-tune ELMo embeddings. The best model on the development split is selected for evaluation. No exponential moving average method is used. The scaling factor $\rho$'s are manually grid-searched in \{$1,2,4,8,16$\} without extensively tuning. \subsection{Natural Language Inference} We use Stanford Natural Language Inference (SNLI) dataset which has $549,367$ training, $9,842$ development, and $9,824$ test examples. For each of the percentages of training data, we sample the same proportion from the orginal development set for validation. To have reliable model selection, we limit the minimal number of sampled development examples to be $1000$. The original test set is only for reporting. In our implimentation of the BiLSTM variant of the Decomposable Attention (DAtt) model, we adopt learning rate $0.0001$ for $100$ epochs of training. The dropout rate is $0.2$. The best model on the development split is selected for evaluation. The scaling factor $\rho$'s are manually grid-searched in \{$0.5,1,2,4,8,16$\} without extensively tuning. \subsection{Text Chunking} The CoNLL2000 dataset consists of $8,936$ examples for training and $2,012$ for testing. From the original training set, both of our training and development examples are sampled and split (by 9/1 folds). Performances are then reported on the original full test set. In our implementation, we set hidden size to $100$ for each direction of BiLSTM encoder. Before the final linear layer, we add a dropout layer with probability $0.5$ for regularization. Each model was trained for $100$ epochs with learning rate $0.0001$. The best model on the development split is selected for evaluation. The scaling factor $\rho$'s are manually grid-searched in \{$1,2,4,8,16,32,64$\} without extensively tuning. \section{Appendices} \label{sec:appendix} \paragraph{Setup for Machine Comprehension} The SQuAD (v1.1.) dataset consists of $87,599$ training instances and $10,570$ development examples. Firstly, for a specific percentage in Table~\ref{tab:mc}, we sample from the original train set. Then we split the sampled set into 9/1 folds for training and development. The original development set is reserved for testing only. In our implementation of the BiDAF, we adopt Adam~\cite{paszke2017automatic} with learning rate $0.001$ for $20$ epochs. Input word embeddings are GloVe~\cite{pennington2014glove} 300d vectors while the hidden size of each direction of BiLSTM encoder is $100$. For the rest hyperparameters, we use the same as BiDAF. Unlike the original BiDAF, we evaluate the best model across different epochs instead of the exponential moving average one. In our development experiments, we found the scaling term $\rho=8$ (in Equation~\ref{eq:constrained-neural-layer}) achieved the best results among all percentages. \paragraph{Setup for Natural Language Inference} We use Stanford Natural Language Inference (SNLI) dataset which has $549,367$ training, $9,842$ development, and $9,824$ testing examples. For each of the percentages in Table~\ref{tab:nli}, we sample corresponding proportion from the orginal train set for training and from the original development set for validation. To have reliable model selection, we limit the minimal number of development examples being sampled to be $1000$. The original test set is only for reporting. In our implimentation of the Decomposable Attention (DAtt) model, we use Adam~\cite{paszke2017automatic} with learning rate $0.0001$ for $200$ epochs. Word embeddings are 300 dimentional from GloVe~\cite{pennington2014glove}. For the rest hyperparameters, we adopt the same setting as~\citet{parikh2016decomposable}. We set different scaling factors (in Equation~\ref{eq:constrained-neural-layer}) for different statements. In development experiments, we found for percentage 1 and 2, $\rho=16$ performed strongly for statement $T_1$ and $T_2$, while $\rho=8$ with higher percentages. For statement $T_{3}$, we use $\rho=1$ across all percentages. \paragraph{Setup for Text Chunking} The CONLL2000 dataset consists of $8,936$ examples for training and $2,012$ for testing. From the original training set, both of our training and development examples in Table~\ref{tab:tc} are sampled and split (by 9/1 folds). Performances are then reported on the test set. In our implementation, we set hidden size to $100$ for each direction of BiLSTM encoder. Input word embeddings are $300$ dimentional GloVe~\cite{pennington2014glove} vectors. Before the final linear layer, we add a dropout layer~\cite{srivastava2014dropout} with probability $0.5$ for regularization. The learning algorithm is Adam~\cite{paszke2017automatic} with learning rate $0.0001$ for $100$ epochs. Again, we use different scaling factors (in Equation~\ref{eq:constrained-neural-layer}) for different statements. For statements $T_{1-4}$, we found $\rho=8$ worked the best in development experiments, while $\rho=16$ for the statements $T_{5-6}$. The same scaling term is applied across different percentages for each statement. \subsection{Text Chunking} \label{sec:tc} Attention layers are a modeling choice that do not always exist in all networks. To illustrate that our framework is not necessarily grounded to attention, we turn to an application where we use knowledge about the output space to constrain predictions. We focus on the sequence labeling task of text chunking using the CoNLL2000 dataset~\cite{tjong2000introduction}. In such sequence tagging tasks, global inference is widely used, e.g., BiLSTM-CRF~\cite{huang2015bidirectional}. Our framework, on the other hand, aims to promote local decisions. To explore the interplay of global model and local decision augmentation, we will combine CRF with our framework. \paragraph{Model} Our baseline is a BiLSTM tagger: \begin{align} \bx &= \text{BiLSTM}(x) \\ \by &= \sigma(\text{linear}(\bx)) \end{align} where $x$ is the input sentence, $\sigma$ is softmax, $\by$ are the output probabilities of BIO tags. \paragraph{Augmentation} We define the following predicates for input and output neurons: \begin{tabular}{rp{0.75\linewidth}} $Y_{t,l}$ & The unconstrained decision that $t^{th}$ word has label $l$.\\ $Y^\prime_{t,l}$ & The constrained decision that $t^{th}$ word has label $l$.\\ $N_t$ & The $t^{th}$ word is a noun. \end{tabular} Then we can write rules for pairwise label dependency. For instance, if word $t$ has B/I- tag for a certain label, word $t$+$1$ can not have an I- tag with a different label. \begin{tabular}{rp{0.75\linewidth}} $C_1$: & $\forall t, ~Y_{t, \text{B-VP}}\rightarrow \neg Y^\prime_{t+1, \text{I-NP}}$ \\ $C_2$: & $\forall t, ~Y_{t, \text{I-NP}} \rightarrow \neg Y^\prime_{t+1, \text{I-VP}}$ \\ $C_3$: & $\forall t, ~Y_{t, \text{I-VP}} \rightarrow \neg Y^\prime_{t+1, \text{I-NP}}$ \\ $C_4$: & $\forall t, ~Y_{t, \text{B-PP}} \rightarrow \neg Y^\prime_{t+1, \text{I-VP}}$ \end{tabular} Our second set of rules are also intuitive: A noun should not have non-NP label. \begin{tabular}{rp{0.75\linewidth}} $C_5$: $\forall t, N_t \rightarrow \bigwedge_{l\in \{\text{\small{B-VP,I-VP,B-PP,I-PP}}\}} \neg Y^\prime_{t, l}$ \\ \end{tabular} While all above rules can be applied as hard constraints in the output space, our framework provides a differentiable way to inform the model during training and prediction. \paragraph{How does local augmentation compare with global inference?} We report performances in Table~\ref{tab:tc}. While a first-order Markov model (\eg, the BiLSTM-CRF) can learn pairwise constraints such as $C_{1:4}$, we see that our framework can better inform the model. Interestingly, the CRF model performed even worse than the baseline with $\leq$40\% data. This suggests that global inference relies on more training examples to learn its scoring function. In contrast, our constrained models performed strongly even with small training sets. And by combining these two orthogonal methods, our locally augmented CRF performed the best with full data. \begin{table}[] \centering \begin{tabular}{rcccc} \toprule {\small \%Train} & {\small BiLSTM} & {\small +CRF} & {\small +$C_{1:5}$} & {\small +CRF,$C_{1:5}$} \\ \midrule {5\%} & 87.2 & 86.6 & \textbf{88.9} & 88.6 \\ {10\%} & 89.1 & 88.8 & \textbf{90.7} & 90.6 \\ {20\%} & 90.9 & 90.8 & \textbf{92.1} & \textbf{92.1} \\ {40\%} & 92.5 & 92.5 & 93.4 & \textbf{93.5} \\ {100\%} & 94.1 & 94.4 & 94.8 & \textbf{95.0} \\ \bottomrule \end{tabular} \caption{Impact of constraints on BiLSTM tagger. Each score represents the average accuracy on test set of $3$ random runs. The columns of +CRF, +$C_{1:5}$, and +CRF,$C_{1:5}$ are on top of the BiLSTM baseline. For $C_{1:4}$, $\rho=4$ for all percentages. For $C_5$, $\rho=16$.} \label{tab:tc} \end{table} \section{Conclusions} \label{sec:conclusions} In this paper, we presented a framework for introducing constraints in the form of logical statements to neural networks. We demonstrated the process of converting first-order logic into differentiable components of networks without extra learnable parameters and extensive redesign. Our experiments were designed to explore the flexibility of our framework with different constraints in diverse tasks. As our experiments showed, our framework allows neural models to benefit from external knowledge during learning and prediction, especially when training data is limited. \section{Experiments} \label{sec:experiments} In this section, we will answer the research questions raised in \S\ref{sec:intro} by focusing on the effectiveness of our augmentation framework. Specifically, we will explore three types of constraints by augmenting: 1) intermediate decisions (i.e. attentions); 2) output decisions constrained by intermediate states; 3) output decisions constrained using label dependencies. To this end, we instantiate our framework on three tasks: machine comprehension, natural language inference, and text chunking. Across all experiments, our goal is to study the modeling flexibility of our framework and its ability to improve performance, especially with decreasing amounts of training data. To study low data regimes, our augmented networks are trained using varying amounts of training data to see how performances vary from baselines. For detailed model setup, please refer to the appendices. \input{machcomp} \input{nli} \input{chunking} \section{Introduction} \label{sec:intro} Neural models demonstrate remarkable predictive performance across a broad spectrum of NLP tasks: \eg, natural language inference~\cite{parikh2016decomposable}, machine comprehension~\cite{seo2016bidirectional}, machine translation~\cite{bahdanau2014neural}, and summarization~\cite{rush2015neural}. These successes can be attributed to their ability to learn robust representations from data. However, such end-to-end training demands a large number of training examples; for example, training a typical network for machine translation may require millions of sentence pairs~\cite[\eg][]{luong2015effective}. The difficulties and expense of curating large amounts of annotated data are well understood and, consequently, massive datasets may not be available for new tasks, domains or languages. In this paper, we argue that we can combat the data hungriness of neural networks by taking advantage of domain knowledge expressed as first-order logic. As an example, consider the task of reading comprehension, where the goal is to answer a question based on a paragraph of text (Fig.~\ref{fig:example}). Attention-driven models such as BiDAF~\cite{seo2016bidirectional} learn to align words in the question with words in the text as an intermediate step towards identifying the answer. While alignments (e.g. \example{author} to \example{writing}) can be learned from data, we argue that models can reduce their data dependence if they were guided by easily stated rules such as: \example{Prefer aligning phrases that are marked as similar according to an external resource, \eg, ConceptNet~\cite{liu2004conceptnet}}. If such declaratively stated rules can be incorporated into training neural networks, then they can provide the inductive bias that can reduce data dependence for training. \begin{figure} \centering \fbox{\includegraphics[width=0.92\linewidth]{example}} \caption{An example of reading comprehension that illustrates alignments/attention. In this paper, we consider the problem of incorporating external knowledge about such alignments into training neural networks.} \label{fig:example} \end{figure} That general neural networks can represent such Boolean functions is known and has been studied both from the theoretical and empirical perspectives~\cite[\eg][]{maass1994comparison,anthony2003boolean,PanSr2016}. Recently, \citet{hu2016harnessing} exploit this property to train a neural network to mimic a teacher network that uses structured rules. In this paper, we seek to directly incorporate such structured knowledge into a neural network architecture without substantial changes to the training methods. We focus on three questions: \begin{enumerate} \item Can we integrate declarative rules with end-to-end neural network training? \item Can such rules help ease the need for data? \item How does incorporating domain expertise compare against large training resources powered by pre-trained representations? \end{enumerate} The first question poses the key technical challenge we address in this paper. On one hand, we wish to guide training and prediction with neural networks using logic, which is non-differentiable. On the other hand, we seek to retain the advantages of gradient-based learning without having to redesign the training scheme. To this end, we propose a framework that allows us to systematically augment an {\em existing} network architecture using constraints about its nodes by deterministically converting rules into differentiable computation graphs. To allow for the possibility of such rules being incorrect, our framework is designed to admit soft constraints from the ground up. Our framework is compatible with off-the-shelf neural networks without extensive redesign or any additional trainable parameters. To address the second and the third questions, we empirically evaluate our framework on three tasks: machine comprehension, natural language inference, and text chunking. In each case, we use a general off-the-shelf model for the task, and study the impact of simple logical constraints on observed neurons (e.g., attention) for different data sizes. We show that our framework can successfully improve an existing neural design, especially when the number of training examples is limited. In summary, our contributions are: \begin{enumerate} \item We introduce a new framework for incorporating first-order logic rules into neural network design in order to guide both training and prediction. \item We evaluate our approach on three different NLP tasks: machine comprehension, textual entailment, and text chunking. We show that augmented models lead to large performance gains in the low training data regimes.\footnote{The code used for our experiments is archived here: \url{https://github.com/utahnlp/layer_augmentation}} \end{enumerate} \subsection{Machine Comprehension} \label{sec:mc} Attention is a widely used intermediate state in several recent neural models. To explore the augmentation over such neurons, we focus on attention-based machine comprehension models on SQuAD (v1.1) dataset~\cite{rajpurkar2016squad}. We seek to use word relatedness from external resources (\ie, ConceptNet) to guide alignments, and thus to improve model performance. \paragraph{Model} We base our framework on two models: BiDAF~\cite{seo2016bidirectional} and its ELMo-augmented variant~\cite{peters2018deep}. Here, we provide an abstraction of the two models which our framework will operate on: \begin{align} \bp, \bq &= \text{encoder}(p), \text{encoder}(q)\\ \overleftarrow{\ba}, \overrightarrow{\ba} &= \sigma(\text{layers}(\bp, \bq)) \label{eq:bidafatt}\\ \by, \bz &= \sigma(\text{layers}(\bp, \bq, \overleftarrow{\ba}, \overrightarrow{\ba})) \end{align} where $p$ and $q$ are the paragraph and query respectively, $\sigma$ refers to the softmax activation, $\overleftarrow{\ba}$ and $\overrightarrow{\ba}$ are the bidirectional attentions from $q$ to $p$ and vice versa, $\by$ and $\bz$ are the probabilities of answer boundaries. All other aspects are abstracted as $encoder$ and $layers$. \paragraph{Augmentation} By construction of the attention neurons, we expect that related words should be aligned. In a knowledge-driven approach, we can use ConceptNet to guide the attention values in the model in Eq.~\ref{eq:bidafatt}. We consider two rules to illustrate the flexibility of our framework. Both statements are in first-order logic that are dynamically grounded to the computation graph for a particular paragraph and query. First, we define the following predicates: \begin{tabular}{rp{0.8\linewidth}} $K_{i,j}$ &word $p_i$ is related to word $q_j$ in ConceptNet via edges \{\emph{Synonym}, \emph{DistinctFrom}, \emph{IsA}, \emph{Related}\}. \\ $\overleftarrow{A}_{i,j}$ &unconstrained model decision that word $q_j$ best matches to word $p_i$. \\ $\overleftarrow{A}^\prime_{i,j}$ &constrained model decision for the above alignment. \end{tabular} Using these predicates, we will study the impact of the following two rules, defined over a set $C$ of content words in $p$ and $q$: \begin{tabular}{rp{0.7\linewidth}} $R_1$: & $\forall i,j \in C,~ K_{i,j} \rightarrow\overleftarrow{A}^\prime_{i,j}$. \\ $R_2$: & $\forall i,j \in C,~ K_{i,j} \wedge \overleftarrow{A}_{i,j} \rightarrow \overleftarrow{A}^\prime_{i,j}$. \end{tabular} The rule $R_1$ says that two words should be aligned if they are related. Interestingly, compiling this statement using the distance functions in Table~\ref{tab:tab1} is essentially the same as adding word relatedness as a static feature. The rule $R_2$ is more conservative as it also depends on the unconstrained model decision. In both cases, since $K_{i,j}$ does not map to a node in the network, we have to create a new node $k_{i,j}$ whose value is determined using ConceptNet, as illustrated in Fig.~\ref{fig:mcflow}. \begin{figure}[h] \centering \includegraphics[width=\linewidth]{mcflow} \caption{ (a) The computation graph of BiDAF where attention directions are obmitted. (b) The augmented graph on attention layer using $R_2$. Bold circles are extra neurons introduced. Constrained attentions and scores are $\ba^\prime$ and $\bs^\prime$ respectively. In the augmented model, graph (b) replaces the shaded part in (a). } \label{fig:mcflow} \end{figure} \paragraph{Can our framework use rules over named neurons to improve model performance?} The answer is yes. We experiment with rules $R_1$ and $R_2$ on incrementally larger training data. Performances are reported in Table~\ref{tab:mc} with comparison with baselines. We see that our framework can indeed use logic to inform model learning and prediction without any extra trainable parameters needed. The improvement is particularly strong with small training sets. With more data, neural models are less reliant on external information. As a result, the improvement with larger datasets is smaller. \begin{table}[] \centering \setlength{\tabcolsep}{1.5pt} \begin{tabular}{rccc|cc} \toprule {\%Train} & { BiDAF} & { +$R_1$} & { +$R_2$} & { +ELMo} & { +ELMo,$R_1$} \\ \midrule {10\%} & 57.5 & \textbf{61.5} & 60.7 & 71.8 & \textbf{73.0}\\ {20\%} & 65.7 & \textbf{67.2} & 66.6 & 76.9 & \textbf{77.7}\\ {40\%} & 70.6 & \textbf{72.6} & 71.9 & 80.3 & \textbf{80.9}\\ {100\%} & 75.7 & \textbf{77.4} & 77.0 & 83.9 & \textbf{84.1}\\ \bottomrule \end{tabular} \caption{Impact of constraints on BiDAF. Each score represents the average span $F_1$ on our test set (i.e. official dev set) among $3$ random runs. Constrained models and ELMo models are built on top of BiDAF. We set $\rho=2$ for both $R_1$ and $R_2$ across all percentages.} \label{tab:mc} \end{table} \paragraph{How does it compare to pretrained encoders?} Pretrained encoders (e.g. ELMo and BERT~\cite{devlin2018bert}) improve neural models with improved representations, while our framework augments the graph using first-order logic. It is important to study the interplay of these two orthogonal directions. We can see in Table~\ref{tab:mc}, our augmented model consistently outperforms baseline even with the presence of ELMo embeddings. \paragraph{Does the conservative constraint $R_2$ help?} We explored two options to incorporate word relatedness; one is a straightforward constraint (i.e. $R_1$), another is its conservative variant (i.e. $R_2$). It is a design choice as to which to use. Clearly in Table~\ref{tab:mc}, constraint $R_1$ consistently outperforms its conservative alternative $R_2$, even though $R_2$ is better than baseline. In the next task, we will see an example where a conservative constraint performs better with large training data. \section{Acknowledgements} We thank members of the NLP group at the University of Utah for their valuable insights and suggestions; and reviewers for pointers to related works, corrections, and helpful comments. We also acknowledge the support of NSF SaTC-1801446, and gifts from Google and NVIDIA. \bibliographystyle{style/acl_natbib} \section{A Framework for Augmenting Neural Networks with Constraints} \label{sec:framework} To create constraint-aware neural networks, we will extend the computation graph of an existing network with additional edges defined by constraints. In \S\ref{sec:workflow}, we will focus on the case where the antecedent is conjunctive/disjunctive and the consequent is a single literal. In \S\ref{sec:general-framework}, we will cover more general antecedents. \subsection{Constraints Beget Distance Functions} \label{sec:workflow} Given a computation graph, suppose we have a acyclic conditional statement: $Z\rightarrow Y$, where $Z$ is a conjunction or a disjunction of literals and $Y$ is a single literal. We define the neuron associated with $Y$ to be $y = g\p{\bW\bx}$, where $g$ denotes an activation function, $\bW$ are network parameters, $\bx$ is the immediate input to $y$. Further, let the vector $\bz$ represent the neurons associated with the predicates in $Z$. While the nodes $\bz$ need to be named neurons, the immediate input $\bx$ need not necessarily have symbolic meaning. \paragraph{Constrained Neural Layers} Our goal is to augment the computation of $y$ so that whenever $Z$ is true, the pre-activated value of $y$ increases if the literal $Y$ is not negated (and decreases if it is). To do so, we define a {\em constrained neural layer} as \begin{equation} \label{eq:constrained-neural-layer} y = g\p{\bW\bx +\rho d\p{\bz}}. \end{equation} Here, we will refer to the function $d$ as the \emph{distance function} that captures, in a differentiable way, whether the antecedent of the implication holds. The importance of the entire constraint is decided by a real-valued hyper-parameter $\rho \geq 0$. The definition of the constrained neural layer says that, by compiling an implicative statement into a distance function, we can regulate the pre-activation scores of the downstream neurons based on the states of upstream ones. \paragraph{Designing the distance function} The key consideration in the compilation step is the choice of an appropriate distance function for logical statements. The ideal distance function we seek is the indicator for the statement $Z$: \begin{equation*} d_{ideal}(\bz) = \begin{cases} 1, & \mbox{if $Z$ holds}, \\ 0, & \mbox{otherwise}. \end{cases} \end{equation*} However, since the function $d_{ideal}$ is not differentiable, we need smooth surrogates. In the rest of this paper, we will define and use distance functions that are inspired by probabilistic soft logic~\cite[c.f.][]{klement2013triangular} and its use of the \L{}ukasiewicz T-norm and T-conorm to define a soft version of conjunctions and disjunctions.\footnote{The definitions of the distance functions here as surrogates for the non-differentiable $d_{ideal}$ is reminiscent of the use of hinge loss as a surrogate for the zero-one loss. In both cases, other surrogates are possible.} Table~\ref{tab:tab1} summarizes distance functions corresponding to conjunctions and disjunctions. In all cases, recall that the $z_i$'s are the states of neurons and are assumed to be in the range $[0,1]$. Examining the table, we see that with a conjunctive antecedent (first row), the distance becomes zero if even one of the conjuncts is false. For a disjunctive antecedent (second row), the distance becomes zero only when all the disjuncts are false; otherwise, it increases as the disjuncts become more likely to be true. \begin{table} \centering \begin{tabular}{rl} \toprule Antecedent & Distance $d(\bz)$ \\ \midrule $\Land_i Z_i$ & $ \max(0, \sum_i z_i - |Z| + 1)$ \\ $\Lor_i Z_i$ & $ \min(1, \sum_i z_i)$ \\ $\neg \Lor_i Z_i$ & $ \max(0, 1 - \sum_i z_i)$ \\ $\neg \Land_i Z_i$ & $ \min(1, N - \sum_i z_i)$ \\ \bottomrule \end{tabular} \caption{Distance functions designed using the \L{}ukasiewicz T-norm. Here, $|Z|$ is the number of antecedent literals. $z_i$'s are upstream neurons associated with literals $Z_i$'s.} \label{tab:tab1} \end{table} \paragraph{Negating Predicates} Both the antecedent (the $Z$'s) and the consequent ($Y$) could contain negated predicates. We will consider these separately. For any negated antecedent predicate, we modify the distance function by substituting the corresponding $z_i$ with $1-z_i$ in Table~\ref{tab:tab1}. The last two rows of the table list out two special cases, where the entire antecedents are negated, and can be derived from the first two rows. To negate consequent $Y$, we need to reduce the pre-activation score of neuron $y$. To achieve this, we can simply negate the entire distance function. \paragraph{Scaling factor $\rho$} In Eq.~\ref{eq:constrained-neural-layer}, the distance function serves to promote or inhibit the value of downstream neuron. The extent is controlled by the scaling factor $\rho$. For instance, with $\rho = +\infty$, the pre-activation score of the downstream neuron is dominated by the distance function. In this case, we have a hard constraint. In contrast, with a small $\rho$, the output state depends on both the $\bW\bx$ and the distance function. In this case, the \emph{soft} constraint serves more as a suggestion. Ultimately, the network parameters might overrule the constraint. We will see an example in \S\ref{sec:experiments} where noisy constraint prefers small $\rho$. \subsection{General Boolean Antecedents} \label{sec:general-framework} So far, we exclusively focused on conditional statements with either conjunctive or disjunctive antecedents. In this section, we will consider general antecedents. As an illustrative example, suppose we have an antecedent $(\neg A \vee B) \wedge (C \vee D)$. By introducing auxiliary variables, we can convert it into the conjunctive form $P \wedge Q$, where $(\neg A \vee B) \leftrightarrow P$ and $(C \vee D) \leftrightarrow Q$. To perform such operation, we need to: \begin{inparaenum}[(1)] \item introduce auxiliary neurons associated with the auxiliary predicates $P$ and $Q$, and, \item define these neurons to be exclusively determined by the biconditional constraint. \end{inparaenum} To be consistent in terminology, when considering biconditional statement $(\neg A \vee B) \leftrightarrow P$, we will call the auxiliary literal $P$ the consequent, and the original literals $A$ and $B$ the antecedents. Because the implication is bidirectional in biconditional statement, it violates our acyclicity requirement in \S\ref{sec:workflow}. However, since the auxiliary neuron state does not depend on any other nodes, we can still create an acyclic sub-graph by defining the new node to be the distance function itself. \paragraph{Constrained Auxiliary Layers} With a biconditional statement $Z \leftrightarrow Y$, where $Y$ is an auxiliary literal, we define a \emph{constrained auxiliary layer} as \begin{equation} \label{eq:constrained-intermediate-layer} y = d\p{\bz} \end{equation} where $d$ is the distance function for the statement, $\bz$ are upstream neurons associated with $Z$, $y$ is the downstream neuron associated with $Y$. Note that, compared to Eq.~\ref{eq:constrained-neural-layer}, we do not need activation function since the distance, which is in $[0,1]$, can be interpreted as producing normalized scores. Note that this construction only applies to auxiliary predicates in biconditional statements. The advantage of this layer definition is that we can use the same distance functions as before (\ie, Table~\ref{tab:tab1}). Furthermore, the same design considerations in \S\ref{sec:workflow} still apply here, including how to negate the left and right hand sides. \paragraph{Constructing augmented networks} To complete the modeling framework, we summarize the workflow needed to construct an augmented neural network given a conditional statement and a computation graph: \begin{inparaenum}[(1)] \item Convert the antecedent into a conjunctive or a disjunctive normal form if necessary. \item Convert the conjunctive/disjunctive antecedent into distance functions using Table~\ref{tab:tab1} (with appropriate corrections for negations). \item Use the distance functions to construct constrained layers and/or auxiliary layers to augment the computation graph by replacing the original layer with constrained one. \item Finally, use the augmented network for end-to-end training and inference. \end{inparaenum} We will see complete examples in \S\ref{sec:experiments}. \subsection{Discussion} \label{sec:combine} Not only does our design not add any more trainable parameters to the existing network, it also admits efficient implementation with modern neural network libraries. When posing multiple constraints on the same downstream neuron, there could be combinatorial conflicts. In this case, our framework relies on the base network to handle the consistency issue. In practice, we found that summing the constrained pre-activation scores for a neuron is a good heuristic (as we will see in \S\ref{sec:tc}). For a conjunctive consequent, we can decompose it into multiple individual constraints. That is equivalent to constraining downstream nodes independently. Handling more complex consequents is a direction of future research. \subsection{Natural Language Inference} \label{sec:nli} Unlike in the machine comprehension task, here we explore logic rules that bridge attention neurons and output neurons. We use the SNLI dataset~\cite{bowman2015large}, and base our framework on a variant of the decomposable attention~\cite[DAtt,][]{parikh2016decomposable} model where we replace its projection encoder with bidirectional LSTM (namely L-DAtt). \paragraph{Model} Again, we abstract the pipeline of L-DAtt model, only focusing on layers which our framework works on. Given a premise $p$ and a hypothesis $h$, we summarize the model as: \begin{align} \bp, \bh & = \text{encoder}(p), \text{encoder}(h) \\ \overleftarrow{\ba}, \overrightarrow{\ba} & = \sigma(\text{layers}(\bp, \bh)) \\ \by & = \sigma(\text{layers}(\bp,\bh,\overleftarrow{\ba},\overrightarrow{\ba})) \end{align} Here, $\sigma$ is the softmax activation, $\overleftarrow{\ba}$ and $\overrightarrow{\ba}$ are bidirectional attentions, $\by$ are probabilities for labels \emph{Entailment}, \emph{Contradiction}, and \emph{Neutral}. \paragraph{Augmentation} We will borrow the predicate notation defined in the machine comprehension task (\S\ref{sec:mc}), and ground them on premise and hypothesis words, e.g. $K_{i,j}$ now denotes the relatedness between premise word $p_i$ and hypothesis word $h_j$. In addition, we define the predicate $Y_l$ to indicate that the label is $l$. As in \S\ref{sec:mc}, we define two rules governing attention: \begin{tabular}{rp{0.7\linewidth}} $N_1$: & $\forall i,j \in C,~ K_{i,j} \rightarrow {A}^\prime_{i,j}$. \\ $N_2$: & $\forall i,j \in C,~ K_{i,j} \wedge {A}_{i,j} \rightarrow {A}^\prime_{i,j}$. \end{tabular} where $C$ is the set of content words. Note that the two constraints apply to both attention directions. Intuitively, if a hypothesis content word is not aligned, then the prediction should not be \emph{Entailment}. To use this knowledge, we define the following rule: \begin{tabular}{rp{0.7\linewidth}} $N_3$: & $Z_1 \vee Z_2 \rightarrow \neg Y_{\text{Entail}}^\prime$, where\\ & $\exists j \in C,~ \neg \p{\exists i \in C,~ \overleftarrow{A}^\prime_{i,j}} \leftrightarrow Z_1$,\\ & $\exists j \in C,~ \neg \p{\exists i \in C,~ \overrightarrow{A}^\prime_{i,j}} \leftrightarrow Z_2$. \end{tabular} where $Z_1$ and $Z_2$ are auxiliary predicates tied to the $Y^\prime_{\text{Entail}}$ predicate. The details of $N_3$ are illustrated in Fig.~\ref{fig:nliflow}. \begin{figure}[h] \centering \includegraphics[width=\linewidth]{nliflow} \caption{(a) The computation graph of the L-DAtt model (attention directions obmitted). (b) The augmented graph on the $\emph{Entail}$ label using $N_{3}$. Bold circles are extra neurons introduced. Unconstrained pre-activation scores are $\bs$ while $\bs_e^\prime$ is the constrained score on \emph{Entail}. Intermediate neurons are $z_1$ and $z_2$. constrained attentions $\ba^\prime$ are constructed using $N_1$ or $N_2$. In our augmented model, the graph (b) replaces the shaded part in (a). } \label{fig:nliflow} \end{figure} \paragraph{How does our framework perform with large training data?} The SNLI dataset is a large dataset with over half-million examples. We train our models using incrementally larger percentages of data and report the average performance in Table~\ref{tab:nli}. Similar to \S\ref{sec:mc}, we observe strong improvements from augmented models trained on small percentages ($\leq$10\%) of data. The straightforward constraint $N_1$ performs strongly with $\leq$2\% data while its conservative alternative $N_2$ works better with a larger set. However, with full dataset, our augmented models perform only on par with baseline even with lowered scaling factor $\rho$. These observations suggest that if a large dataset is available, it may be better to believe the data, but with smaller datasets, constraints can provide useful inductive bias for the models. \paragraph{Are noisy constraints helpful?} It is not always easy to state a constraint that all examples satisfy. Comparing $N_2$ and $N_3$, we see that $N_3$ performed even worse than baseline, which suggests it contains noise. In fact, we found a significant amount of counter examples to $N_3$ during preliminary analysis. Yet, even a noisy rule can improve model performance with $\leq$10\% data. The same observation holds for $N_1$, which suggests conservative constraints could be a way to deal with noise. Finally, by comparing $N_2$ and $N_{2,3}$, we find that the good constraint $N_2$ can not just augment the network, but also amplify the noise in $N_3$ when they are combined. This results in degrading performance in the $N_{2,3}$ column starting from 5\% of the data, much earlier than using $N_3$ alone. \begin{table}[] \centering \setlength{\tabcolsep}{4pt} \begin{tabular}{rrrr|rr} \toprule \%Train & L-DAtt & +$N_1$ & +$N_2$ & +$N_3$ & +$N_{2,3}$ \\ \midrule 1\% & 61.2 & \textbf{64.9} & 63.9 & 62.5 & 64.3 \\ 2\% & 66.5 & \textbf{70.5} & 69.8 & 67.9 & 70.2 \\ 5\% & 73.4 & 76.2 & \textbf{76.6} & 74.0 & 76.4 \\ 10\% & 78.9 & 80.1 & \textbf{80.4} & 79.3 & 80.3 \\ 100\% & \textbf{87.1} & 86.9 & \textbf{87.1} & 87.0 & 86.9 \\ \bottomrule \end{tabular} \caption{Impact of constraints on L-DAtt network. Each score represents the average accuracy on SNLI test set among $3$ random runs. For both $N_1$ and $N_2$, we set $\rho=(8,8,8,8,4)$ for the five different percentages. For the noisy constraint $N_3$, $\rho=(2,2,1,1,1)$. } \label{tab:nli} \end{table} \section{Problem Setup} \label{sec:prelim} In this section, we will introduce the notation and assumptions that form the basis of our formalism for constraining neural networks. Neural networks are directed acyclic computation graphs $G=(V,E)$, consisting of nodes (i.e. neurons) $V$ and weighted directed edges $E$ that represent information flow. Although not all neurons have explicitly grounded meanings, some nodes indeed can be endowed with semantics tied to the task. Node semantics may be assigned during model design (\eg attention), or incidentally discovered in post hoc analysis~\cite[\eg,][and others]{le2011building,radford2017learning}. In either case, our goal is to augment a neural network with such \concept{named neurons} using declarative rules. The use of logic to represent domain knowledge has a rich history in AI~\cite[\eg][]{russell2016artificial}. In this work, to capture such knowledge, we will primarily focus on conditional statements of the form $L \rightarrow R$, where the expression $L$ is the antecedent (or the left-hand side) that can be conjunctions or disjunctions of literals, and $R$ is the consequent (or the right-hand side) that consists of a single literal. Note that such rules include Horn clauses and their generalizations, which are well studied in the knowledge representation and logic programming communities~\cite[\eg][]{chandra1985horn}. Integrating rules with neural networks presents three difficulties. First, we need a mapping between the predicates in the rules and nodes in the computation graph. Second, logic is not differentiable; we need an encoding of logic that admits training using gradient based methods. Finally, computation graphs are acyclic, but user-defined rules may introduce cyclic dependencies between the nodes. Let us look at these issues in order. As mentioned before, we will assume named neurons are given. And by associating predicates with such nodes that are endowed with symbolic meaning, we can introduce domain knowledge about a problem in terms of these predicates. In the rest of the paper, we will use lower cased letters (\eg, $a_i, b_j$) to denote nodes in a computation graph, and upper cased letters (\eg, $A_i, B_j$) for predicates associated with them. To deal with the non-differentiablity of logic, we will treat the post-activation value of a named neuron as the degree to which the associated predicate is true. In \S\ref{sec:framework}, we will look at methods for compiling conditional statements into differentiable statements that augment a given network. \paragraph{Cyclicity of Constraints} Since we will augment computation graphs with compiled conditional forms, we should be careful to avoid creating cycles. To formalize this, let us define cyclicity of conditional statements with respect to a neural network. Given two nodes $a$ and $b$ in a computation graph, we say that the node $a$ is \emph{upstream} of node $b$ if there is a directed path from $a$ to $b$ in the graph. \begin{mydef}[Cyclic and Acyclic Implications] \label{def:cyclic-implications} Let $G$ be a computation graph. An implicative statement $L \rightarrow R$ is \emph{cyclic} with respect to $G$ if, for any literal $R_i \in R$, the node $r_i$ associated with it is upstream of the node $l_j$ associated with some literal $L_j \in L$. An implicative statement is \emph{acyclic} if it is not cyclic. \end{mydef} \begin{figure} \centering \includegraphics[width=\linewidth]{flow1} \caption{An example computation graph. The statement $A_1 \land B_1 \rightarrow A_2 \land B_2$ is cyclic with respect to the graph. On the other hand, the statement $A_1 \land A_2 \rightarrow B_1 \land B_2$ is acyclic.} \label{fig:flow1} \end{figure} Fig.~\ref{fig:flow1} and its caption gives examples of cyclic and acyclic implications. A cyclic statement sometimes can be converted to an equivalent acyclic statement by constructing its contrapositive. For example, the constraint $B_1 \rightarrow A_1$ is equivalent to $\neg A_1 \rightarrow \neg B_1$. While the former is cyclic, the later is acyclic. Generally, we can assume that we have acyclic implications.\footnote{As we will see in \S\ref{sec:combine}, the contrapositive does not always help because we may end up with a complex right hand side that we can not yet compile into the computation graph.} \section{Related Work and Discussion} \label{sec:related} \paragraph{Artificial Neural Networks and Logic} Our work is related to neural-symbolic learning~\cite[\eg][]{besold2017neural} which seeks to integrate neural networks with symbolic knowledge. For example,~\citet{cingillioglu2018deeplogic} proposed neural models that multi-hop logical reasoning. KBANN~\cite{towell1990refinement} constructs artificial neural networks using connections expressed in propositional logic. Along these lines, \citet[CILP++]{francca2014fast} build neural networks from a rule set for relation extraction. Our distinction is that we use first-order logic to {\em augment} a given architecture instead of designing a new one. Also, our framework is related to~\citet[PSL]{kimmig2012short} which uses a smooth extension of standard Boolean logic. ~\citet{hu2016harnessing} introduced an imitation learning framework where a specialized teacher-student network is used to distill rules into network parameters. This work could be seen as an instance of knowledge distillation~\cite{hinton2015distilling}. Instead of such extensive changes to the learning procedure, our framework retains the original network design and augments existing interpretable layers. \paragraph{Regularization with Logic} Several recent lines of research seek to guide training neural networks by integrating logical rules in the form of additional terms in the loss functions~\cite[\eg,][]{rocktaschel2015injecting} that essentially promote constraints among output labels~\cite[\eg,][]{du2019consistent,mehta2018towards}, promote agreement~\cite{hsu2018unified} or reduce inconsistencies across predictions~\cite{minervini2018adversarially}. Furthermore, \citet{pmlr-v80-xu18h} proposed a general design of loss functions using symbolic knowledge about the outputs. ~\citet{fischer2019dl2} described a method for for deriving losses that are friendly to gradient-based learning algorithms. ~\citet{wang2018deep} proposed a framework for integrating indirect supervision expressed via probabilistic logic into neural networks. \paragraph{Learning with Structures} Traditional structured prediction models~\cite[\eg][]{smith2011linguistic} naturally admit constraints of the kind described in this paper. Indeed, our approach for using logic as a template-language is similar to Markov Logic Networks~\cite{richardson2006markov}, where logical forms are compiled into Markov networks. Our formulation augments model scores with constraint penalties is reminiscent of the Constrained Conditional Model of \citet{chang2012structured}. Recently, we have seen some work that allows backpropagating through structures~\cite[\eg][and the references within]{huang2015bidirectional,kim2017structured,yogatama2017learning,niculae2018sparsemap,peng2018backpropagating}. Our framework differs from them in that structured inference is not mandantory here. We believe that there is room to study the interplay of these two approaches. Also related to our attention augmentation is using word relatedness as extra input feature to attention neurons~\cite[\eg][]{chen2018neural}. \section{Machine Comprehension} The SQuAD (v1.1) dataset consists of $87,599$ training instances and $10,570$ development examples. Firstly, for a specific percentage of training data, we sample from the original train set. Then we split the sampled set into 9/1 folds for training and development. The original development set is reserved for testing only. This is because that the official test set is hidden, and the number of models we need to evaluate is impractical for accessing official test set. In our implementation of the BiDAF model, we use a learning rate $0.001$ to train the model for $20$ epochs. Dropout~\cite{srivastava2014dropout} rate is $0.2$. The hidden size of each direction of BiLSTM encoder is $100$. For ELMo models, we train for $25$ epochs with learning rate $0.0002$. The rest hyperparameters are the same as in ~\cite{peters2018deep}. Note that we did neither pre-tune nor post-tune ELMo embeddings. The best model on the development split is selected for evaluation. No exponential moving average method is used. The scaling factor $\rho$'s are manually grid-searched in \{$1,2,4,8,16$\} without extensively tuning. \section{Natural Language Inference} We use Stanford Natural Language Inference (SNLI) dataset which has $549,367$ training, $9,842$ development, and $9,824$ test examples. For each of the percentages of training data, we sample the same proportion from the orginal development set for validation. To have reliable model selection, we limit the minimal number of sampled development examples to be $1000$. The original test set is only for reporting. In our implimentation of the BiLSTM variant of the Decomposable Attention (DAtt) model, we adopt learning rate $0.0001$ for $100$ epochs of training. The dropout rate is $0.2$. The best model on the development split is selected for evaluation. The scaling factor $\rho$'s are manually grid-searched in \{$0.5,1,2,4,8,16$\} without extensively tuning. \section{Text Chunking} The CoNLL2000 dataset consists of $8,936$ examples for training and $2,012$ for testing. From the original training set, both of our training and development examples are sampled and split (by 9/1 folds). Performances are then reported on the original full test set. In our implementation, we set hidden size to $100$ for each direction of BiLSTM encoder. Before the final linear layer, we add a dropout layer with probability $0.5$ for regularization. Each model was trained for $100$ epochs with learning rate $0.0001$. The best model on the development split is selected for evaluation. The scaling factor $\rho$'s are manually grid-searched in \{$1,2,4,8,16,32,64$\} without extensively tuning. \bibliographystyle{style/acl_natbib}
{'timestamp': '2019-08-13T02:24:15', 'yymm': '1906', 'arxiv_id': '1906.06298', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06298'}
arxiv
\section{VAEs with correlations} In this section, we provide a brief overview of \acrlongpl{VAE} (\acrshortpl{VAE}) \citep{kingma2013auto,rezende2014stochastic} as well as \acrlongpl{CVAE} (\acrshortpl{CVAE}) \citep{tang2019correlated} which take the correlation structure among data points into consideration. \subsection{Variational Auto-Encoders} We use a latent variable model to fit data $\bm x=\{\bm x_1,\ldots,\bm x_n\}\subset\mathbb R^D$. The model assumes that there exist low-dimensional latent embeddings for each data point $\bm z=\{\bm z_1,\ldots,\bm z_n\}\subset\mathbb R^d$ ($d\ll D$), which come from a prior distribution $p_0(\cdot)$, and $\bm x_i$'s are drawn conditionally independently given $\bm z_i$. Denote the model parameters as $\bm\theta$. The likelihood of this model is $p_{\bm\theta}(\bm x)=\prod\limits_{i=1}^n\int p_0(\bm z_i)p_{\bm\theta}(\bm x_i | \bm z_i)d\bm z_i$. To simultaneously learn the model parameter $\bm\theta$ as well as a mapping from the observed data $\bm x$ to the latent embeddings $\bm z$, \glspl{VAE} \citep{kingma2013auto,rezende2014stochastic} apply a data-dependent variational approximation $q_{\bm\lambda}(\bm z | \bm x)=\prod\limits_{i=1}^n q_{\bm\lambda}(\bm z_i |\bm x_i)$, where $\bm\lambda$ denotes the variational parameters, and maximize the \textit{evidence lower-bound} (ELBO) on the log-likelihood of the data, $\log p_{\bm\theta}(\bm x)$: \begin{align} L(\bm\lambda,\bm\theta) &=\mathbb E_{q_{\bm\lambda}(\bm z | \bm x)}\left[\log p_{\bm\theta}(\bm x | \bm z) \right]-\text{KL}(q_{\bm\lambda}(\bm z | \bm x)||p_0(\bm z)). \label{eqn:elbo} \end{align} \subsection{\acrlongpl{CVAE}} \label{sec:cvae} Standard \glspl{VAE} are capable of learning compact low-dimensional embeddings for high-dimensional data. However, due to the i.i.d. assumption, they fail to account for the correlations between data points when \emph{a priori} we know correlations exist. \glspl{CVAE} \citep{tang2019correlated} mitigate the issue by employing a structured prior as well as a structured variational posterior to take advantage of the structured correlation information. Formally, assume we are given an undirected correlation graph $G=(V, E)$, where $(v_i, v_j)\in E$ represents that the data points $x_i$ and $x_j$ are correlated, \glspl{CVAE} apply a correlated prior $p^\textrm{corr}_0(\bm z)$ on the latent variables $\bm z_i$'s which satisfies \begin{equation} p_0^{\textrm{corr}}(\bm z_i)=p_0(\bm z_i)\text{ for all }v_i\in V,\quad p_0^{\textrm{corr}}(\bm z_i,\bm z_j)=p_0(\bm z_i, \bm z_j)\text{ if }(v_i, v_j)\in E.\\ \label{eqn:prior-pair-acyclic} \end{equation} Here $p_0(\cdot)$ and $p_0(\cdot,\cdot)$ are parameter-free functions that capture the singleton and pairwise marginal distributions of the latent variables. For example, we can set $p_0(\cdot)$ to be the density of a standard multivariate normal distribution and $p_0(\cdot,\cdot)$ to be a multivariate normal density that has high values if the two inputs are close to each other. With such a prior, we again assume $\bm x_i$'s are drawn conditionally independently given $\bm{z}_i$. When $G$ is acyclic, such a prior $p_0^{\text{corr}}(\bm z)$ does exist \citep{wainwright2008graphical}: \begin{equation} p_0^{\textrm{corr}}(\bm z)=\prod\limits_{i=1}^np_0(\bm z_i)\prod\limits_{(v_i,v_j)\in E}\frac{p_0(\bm z_i,\bm z_j)}{p_0(\bm z_i)p_0(\bm z_j)}. \label{eqn:prior-acyclic} \end{equation} However, when $G$ is not acyclic, \Cref{eqn:prior-acyclic} is not necessarily a valid probability density function. To deal with this issue, \glspl{CVAE} propose constructing a prior that is a mixture over the set $\mathcal{A}_G$ of all of $G$'s \textit{maximal acyclic subgraphs}, which are defined as follows: \begin{definition}[Maximal acyclic subgraph] For an undirected graph $G=(V,E)$, an acyclic subgraph $G'=(V', E')$ is a maximal acyclic subgraph of $G$ if: \begin{itemize} \item $V'=V$, i.e., $G'$ contains all vertices of $G$. \item Adding any edge from $E/E'$ to $E'$ will create a cycle in $G'$. \end{itemize} \end{definition} Each of the maximal acyclic subgraphs $G' \in \mathcal{A}_G$ can partially approximates the correlation structure in $G$, and \glspl{CVAE} set the prior $p_0^{\textrm{corr}_g}(\bm z)$ to be the uniform average over all of these tractable densities: \begin{equation} p_0^{\textrm{corr}_g}(\bm z)=\frac{1}{|\mathcal A_G|}\sum\limits_{G'=(V,E')\in\mathcal A_G} p_0^{G'}(\bm z), \label{eqn:prior} \end{equation} where $p_0^{G'}(\bm z)=\prod\limits_{i=1}^np_0(\bm z_i)\prod\limits_{(v_i,v_j)\in E'}\frac{p_0(\bm z_i,\bm z_j)}{p_0(\bm z_i)p_0(\bm z_j)}$ is a prior on a maximal acyclic subgraph $G'=(V,E')$ with the same form as in \Cref{eqn:prior-acyclic}. For each $G' \in \mathcal{A}_G$, we can similarly define a structured variational approximation $q_{\bm\lambda}^{G'}(\bm z | \bm x)$ following the form of \Cref{eqn:prior-acyclic} (see appendix for details) . With this structured prior as well as variational posterior, \glspl{CVAE} optimize a different form of ELBO: \begin{align} \log p_{\bm\theta}(\bm x)&=\log\mathbb E_{p_0^{\textrm{corr}_g}(\bm z)}[p_{\bm\theta}(\bm x | \bm z)]\ge\frac1{|\mathcal A_G|}\sum\limits_{G'\in\mathcal A_G}\mathbb E_{p_0^{G'}(\bm z)}[\log p_{\bm\theta}(\bm x | \bm z)]\nonumber\\ &\ge\frac1{|\mathcal A_G|}\sum\limits_{G'\in\mathcal A_G}\Big(\mathbb E_{q_{\bm\lambda}^{G'}(\bm z | \bm x)}[\log p_{\bm\theta}(\bm x | \bm z)]-\text{KL}(q_{\bm\lambda}^{G'}(\bm z | \bm x) || p_0^{G'}(\bm z))\Big).\label{eqn:lb1} \end{align} Even though empirically \citet{tang2019correlated} show that \glspl{CVAE} are capable of capitalizing on the correlation structure as auxiliary information when learning latent embeddings, there are a few limitations to this approach. First of all, the ELBO in \Cref{eqn:lb1} is defined as a uniform average over individual ELBOs for all of the maximal acyclic subgraph $G' \in \mathcal{A}_G$, and each $G'$ posits a different variational approximation $q_{\bm\lambda}^{G'}(\bm z | \bm x)$. As a result, we can not obtain a holistic variational distribution $q_{\bm\lambda}(\bm z | \bm x)$ as the approximation to the posterior distribution $p(\bm z | \bm x)$. Moreover, not every maximal acyclic subgraph is capable of capturing the correlation well, hence taking a uniform average over all of them can be sub-optimal. Last but not least, from a computational standpoint, to mitigate the intractable average over $\mathcal{A}_G$ which can contain exponentially many elements, the algorithm proposed in \citet{tang2019correlated} requires a $O(|{V}|^3)$ pre-processing step. This prevents the algorithm from being applied to large-scale datasets. In the next section, we will propose fixes to all of these limitations. \section{Adaptive Correlated VAEs} \subsection{A non-uniform mixture prior} As motivated in \Cref{sec:cvae}, rather than using a uniform average, we instead employ a categorical distribution $\bm\pi\in\triangle^{|\mathcal A_G|-1}$ representing the normalized weights over all maximal acyclic subgraphs $G'\in\mathcal A_G$ of $G$. Recall the ELBO in \Cref{eqn:lb1}, we can replace the uniform average in the prior $p_0^{\textrm{corr}_g}(\bm z)$ in \Cref{eqn:prior} with the non-uniform distribution $\bm\pi$, which gives us the following ELBO: \begin{equation} \begin{aligned} &\mathbb E_{G' \sim \bm\pi}\left[\mathbb E_{q_{\bm\lambda}^{G'}(\bm z | \bm x)}[\log p_{\bm\theta}(\bm x | \bm z)]-\text{KL}(q_{\bm\lambda}^{G'}(\bm z | \bm x) || p_0^{G'}(\bm z))\right]\\ \le~&\mathbb E_{G' \sim \bm\pi}\left[\mathbb E_{p_0^{G'}(\bm z)}[\log p_{\bm\theta}(\bm x | \bm z)]\right]:=\mathbb E_{p_0^{\bm\pi}(\bm z)}[\log p_{\bm\theta}(\bm x | \bm z)]\le\log p_{\bm\pi,\bm\theta}(\bm x). \end{aligned} \label{eqn:lb2} \end{equation} Here we define the non-uniform prior $p_0^{\bm\pi}(\bm z) = \mathbb{E}_{G' \sim \bm\pi}[p_0^{G'}(\bm z)]$. From the above inequality we can see that, using the non-uniform prior $p_0^{\bm\pi}$, we are still able to obtain a lower bound of the log-likelihood $\log p_{\bm\pi,\bm\theta}(\bm x)$, which is now also parametrized by the weight parameter $\bm\pi$. If we optimize this categorical distribution $\bm\pi$ together with all the other parameters, the above loss function implies that we are optimizing with an adaptive prior. Hence, we call the above model \glspl{ACVAE}. If we replace $\bm\pi$ with a uniform distribution over all subgraphs in $\mathcal A_G$, we recover \glspl{CVAE}. Plugging $q_{\bm\lambda}^{G'}(\bm z | \bm x)$ and $p_0^{G'}(\bm z)$ from \Cref{sec:cvae} into \Cref{eqn:lb2}, yields the following ELBO for \glspl{ACVAE}: \begin{equation} \begin{aligned} &\mathcal L^{\textrm{ACVAE}}(\bm\pi,\bm\lambda, \bm\theta):=\sum\limits_{i=1}^n\Big(\mathbb E_{q_{\bm\lambda}(\bm z_i | \bm x_i)}\left[\log p_{\bm\theta}(\bm x_i | \bm z_i) \right]-\text{KL}(q_{\bm\lambda}(\bm z_i | \bm x_i)||p_0(\bm z_i))\Big)-\sum\limits_{(v_i,v_j)\in E}w^{\text{MAS}}_{G, \bm\pi, (v_i, v_j)}\\ &\ \ \ \ \cdot\Big(\text{KL}(q_{\bm\lambda}(\bm z_i, \bm z_j | \bm x_i, \bm x_j)||p_0(\bm z_i, \bm z_j))-\text{KL}(q_{\bm\lambda}(\bm z_i | \bm x_i)||p_0(\bm z_i)) - \text{KL}(q_{\bm\lambda}(\bm z_j | \bm x_j)||p_0(\bm z_j))\Big). \end{aligned} \label{eqn:loss-acvae} \end{equation} Similar to \glspl{CVAE}, we have edge weights $w^{\text{MAS}}_{G, \bm\pi, (v_i, v_j)}$ representing the expected appearance probability for edge $(v_i, v_j)$ over the set of maximal acyclic subgraphs $\mathcal{A}_G$ given the distribution $\bm\pi$. In the following definition, we abusively write $\bm\pi(G')$ as the probability of $G'$ being sampled from $\mathcal{A}_G$. \begin{definition}[Non-uniform maximal acyclic subgraph edge weight] For an undirected graph $G=(V, E)$, an edge $e\in E$ and a distribution $\bm\pi$ on the set $\mathcal A_G$ of maximal acyclic subgraphs of $G$, define $w^{\text{MAS}}_{G, \bm\pi, e}$ to be the expected appearance probability of the edge $e$ in a random maximal acyclic subgraph $G'=(V,E') \sim \bm\pi$, i.e., $w^{\text{MAS}}_{G, \bm\pi, e}:=\sum\limits_{G'\in\mathcal A_G, e\in E'}\bm\pi(G')$. \label{def:numasew} \end{definition} \subsection{A minimax objective} \label{sec:minimax} With the loss function in \Cref{eqn:loss-acvae}, an intuitive direction would be to perform empirical Bayes \citep{efron2012large} and directly maximize $\mathcal L^{\textrm{ACVAE}}(\bm\pi, \bm\lambda, \bm\theta)$ with respect to all the parameters $\bm\pi$, $\bm\lambda$ and $\bm\theta$. An important observation is that for fixed $\bm\lambda$ and $\bm\theta$, the loss function $\mathcal L^{\textrm{ACVAE}}$ is linear w.r.t. the weight parameter $\bm\pi$. Therefore, if optima for $\mathcal L^{\textrm{ACVAE}}(\bm\pi,\bm\lambda, \bm\theta)$ exist, then at least one optimum will have a $\bm\pi^*$ which puts all of its probability mass on a single subgraph $G'^*$. This optimum drastically simplifies the structured prior $p_0^{\bm\pi}$. However, empirically we observe that it often fails to generalize the learned correlations well. On the other hand, we can achieve more robust inference by considering a minimax saddle-point optimization: \begin{equation} \max\limits_{\bm\lambda,\bm\theta}\min\limits_{\bm\pi}\mathcal L^{\textrm{ACVAE}}(\bm\pi,\bm\lambda, \bm\theta).\label{eqn:opt} \end{equation} As the optimization objective indicates, we are optimizing the ELBO under the prior that produces the \textit{lowest} lower bound. The intuition is that if we can even optimize the worst lower bound well, the variational distribution and the model distribution we learn would be robust and generalize better. This is similar to the \emph{least favorable prior}, under which a Bayes estimator can achieve minimax risk \citep{lehmann2006theory}. In \Cref{sec:expe}, we show the effectiveness of this saddle-point optimization, compared to the empirical Bayes procedure. \begin{proposition}[Optimum for $\bm\pi$]\label{prop:optimal} If the saddle-point optimization in \Cref{eqn:opt} has global optima, then at least one optimum $(\bm\pi^*,\bm\lambda^*,\bm\theta^*)$ will have a $\bm\pi^*$ that places all of its probability mass on a single maximal acyclic subgraph $G'^*\in\mathcal A_G$. \end{proposition} By this proposition, we know that the optimization in \Cref{eqn:opt} will return us a single subgraph $G'^*$, similar to empirical Bayes. At this optimum, the loss function becomes the ELBO on a single acyclic subgraph $G'^*$, with $q_{\bm\lambda^*}^{G'^*}(\bm z | \bm x)$ as the variational distribution. Therefore, we have a holistic variational approximation, overcoming one of the limitations of \glspl{CVAE}. We will show in \Cref{sec:bp} that we can further refine the variational approximation by making use of the single-acyclic-subgraph structure for $q_{\bm\lambda^*}^{G'^*}(\bm z | \bm x)$. \subsection{Learning with alternating updates} Direct optimization of the saddle-point problem is non-trivial. Following similar saddle-point optimization for a spanning tree structured upper bound for the log-partition function of undirected graphical models \citep{wainwright2002stochastic,wainwright2005new}, we perform an alternating optimization on the parameters $\bm\lambda$, $\bm\theta$ and $\bm\pi$. Details are shown in \Cref{alg:updates}. \paragraph{Updates for $\bm\pi$} When the variational parameter $\bm\lambda$ and the model parameter $\bm\theta$ are fixed, the loss function $\mathcal L^{\textrm{ACVAE}}(\bm\pi,\bm\lambda, \bm\theta)$ is linear in $\bm\pi$. However, we cannot directly optimize over $\bm\pi\in\triangle^{|\mathcal A_G|-1}$, as it may contain exponentially many dimensions. We can instead update the edge weights $w^{\text{MAS}}_{G, \bm\pi, (v_i, v_j)}$ as the loss function is also linear in the edge weights. By definition, we know that each maximal acyclic subgraph $G'$ of $G$ is a forest, consisting of one spanning tree for each connected component of $G$. Therefore, the domain for the edge weights $\bigcup\limits_{e\in E}\{w^{\text{MAS}}_{G, \bm\pi, e}\}$ is the projection of the Cartesian product of the spanning tree polytopes for all connected components of $G$ \citep{wainwright2002stochastic,wainwright2005new} to the edge weight space. This Cartesian product on the polytopes is convex and its boundary is determined by potentially exponentially many linear inequalities. Despite that, directly optimizing $\mathcal L^{\textrm{ACVAE}}(\bm\pi,\bm\lambda, \bm\theta)$ with respect to these weights $\bigcup\limits_{e\in E}\{w^{\text{MAS}}_{G, \bm\pi, e}\}$ is in fact tractable: the optimum for $\min_{\bm\pi}\mathcal L^{\textrm{ACVAE}}(\bm\pi,\bm\lambda, \bm\theta)$ is obtained at $\hat{\bm\pi}$ that has all the mass on a single maximal acyclic subgraph $\hat G'$. This means the optimum for these edges weights can be obtained from a single subgraph $\hat G'$. By re-arranging terms in \Cref{eqn:loss-acvae} with respect to $\bigcup\limits_{e\in E}\{w^{\text{MAS}}_{G, \bm\pi, e}\}$, it is not difficult to see that $\hat G'$ should have the smallest ``edge mass'' sum over all maximal acyclic subgraphs $\mathcal A_G$, where the ``edge mass'' $m_{(v_i,v_j)}$ of edge $e=(v_i,v_j)$ is: \begin{equation} m_{(v_i,v_j)}:=\text{KL}(q_{\bm\lambda}(\bm z_i, \bm z_j | \bm x_i, \bm x_j)||p_0(\bm z_i, \bm z_j))-\text{KL}(q_{\bm\lambda}(\bm z_i | \bm x_i)||p_0(\bm z_i)) - \text{KL}(q_{\bm\lambda}(\bm z_j | \bm x_j)||p_0(\bm z_j)), \label{eqn:mass} \end{equation} which means $\hat{G}'$ is the combination of the minimum spanning trees of all connected components of the graph with $m_{(v_i, v_j)}$ as the weights. Once we identify $\hat{G}'$, the optimal weights $\hat w^{\text{MAS}}_{G, \bm{\hat\pi}, e}$ are either 1 (if the edge $e$ is selected) or 0 (otherwise). Instead of directly updating the weights to the optimal values, we perform a soft update with step size $\alpha^t$ at iteration $t$, similar to \citet{wainwright2002stochastic,wainwright2005new}: \begin{equation} w^{\text{MAS}^{t+1}}_{G, \bm\pi, e}\leftarrow (1-\alpha^t)w^{\text{MAS}^t}_{G, \bm\pi, e}+\alpha^t\hat w^{\text{MAS}}_{G, \bm{\hat\pi}, e}. \label{eqn:soft-update} \end{equation} This soft update helps prevent the algorithm from becoming trapped in bad local optima early in the optimization procedure. The step size $\alpha^t$ can be either a constant or dynamically adjusted during optimization. We set it to be a constant in our experiments. One of the limitations of \glspl{CVAE} mentioned in \Cref{sec:cvae} is the $O(|V|^3)$ pre-processing step to compute all the edge weights $w^{\text{MAS}}_{G, e}$. We alleviate this bottleneck in \glspl{ACVAE}, as it only takes $O(\min(|V|^2,|E|\log|V|))$ operations per initialization to update on the weights, which ensures that \glspl{ACVAE} can scale to datasets with many more vertices than would be feasible with \glspl{CVAE}. \paragraph{Updates for $\bm\lambda$ and $\bm\theta$} When $\bm\pi$ is fixed, $\bm\lambda$ and $\bm\theta$ can be updated by taking a stochastic gradient step following $\nabla_{\bm\lambda,\bm\theta}\mathcal L^{\textrm{ACVAE}}(\bm\pi,\bm\lambda, \bm\theta)$ with reparametrization gradient \citep{kingma2013auto,rezende2014stochastic}, as done in standard \glspl{VAE}. \begin{algorithm}[tb] \caption{\glspl{ACVAE} learning} \label{alg:updates} \begin{algorithmic} \STATE {\bfseries Input:} data $\bm x_1,\ldots,\bm x_n\in\mathbb R^D$, undirected graph $G=(V=\{v_1,\ldots,v_n\}, E)$, parameter $\gamma>0$. \STATE Initialize the parameters $\bm\lambda$, $\bm\theta$. Initialize the weights $w^{\text{MAS}^{t+1}}_{G, \bm\pi, e}$ for each $e\in E$. \WHILE {not converged} \STATE Optimize the parameters $(\bm\lambda, \bm\theta)$ using the gradients $\nabla_{\bm\lambda,\bm\theta}\mathcal L^{\textrm{ACVAE}}(\bm\pi,\bm\lambda, \bm\theta)$. \STATE Compute the mass $m_{(v_i,v_j)}$ for each edge $e\in E$ with \Cref{eqn:mass}. \STATE Compute a minimum spanning tree of the graph with the masses $m_{(v_i,v_j)}$'s as the edge weights and update the weights $w^{\text{MAS}}_{G, \bm\pi, e}$ for each $e\in E$ according to \Cref{eqn:soft-update}. \ENDWHILE \STATE {\bfseries Return:} The parameters $\bm\lambda$, $\bm\theta$, the weights $w^{\text{MAS}}_{G, \bm\pi, e}$ for each $e\in E$. \end{algorithmic} \end{algorithm} It is difficult to make any general statement about the convergence of \Cref{alg:updates} as they perform a saddle-point optimization with non-convex objective. Empirically we find that \Cref{alg:updates} is stable and performs well on multiple real datasets. \subsection{Refine posterior approximation with belief propagation}\label{sec:bp} From \Cref{prop:optimal}, we know the weights $w^{\text{MAS}}_{G, \bm\pi, e}$ returned from \Cref{alg:updates} are from a single maximal acyclic subgraph $G' \in \mathcal{A}_G$. Consequently, we have a holistic variational approximation $q_{\bm\lambda}^{G'}(\bm z | \bm x)$. The acyclic structure of $G'$ makes it possible to further refine the pairwise marginal approximation between any pair of vertices via a belief-propagation-style \citep{pearl1982reverend} message-passing algorithm, which is not possible for \glspl{CVAE}, as it does not have a single joint variational distribution on $\bm z$. This can be crucial in tasks in which we need an accurate pairwise marginal approximation, e.g., link prediction. Consider any $v_i\neq v_j\in V$ that are in the same connected component of $G'$. Since $G'$ is acyclic there is a unique path from $v_i$ to $v_j$. Denote it as $v_i=u^{i,j}_0\rightarrow u^{i,j}_1\rightarrow\ldots\rightarrow u^{i,j}_{k_{i,j}}=v_j$. The refined pairwise marginal $r_{\bm\lambda}(\bm z_i, \bm z_j | \bm x_i, \bm x_j)$ is defined to be: \begin{equation} r_{\bm\lambda}(\bm z_i, \bm z_j | \bm x_i, \bm x_j)=\int \prod\limits_{l=0}^{k_{i,j}-1}q_{\bm\lambda}(\bm z_{u^{i,j}_l}, \bm z_{u^{i,j}_{l+1}} | \bm x_{u^{i,j}_l}, \bm x_{u^{i,j}_{l+1}})\prod\limits_{l=1}^{k_{i,j}-1}\frac{d\bm z_{u^{i,j}_l}}{q_{\bm\lambda}(\bm z_{u^{i,j}_l} | \bm x_{u^{i,j}_l})}. \end{equation} The above pairwise marginal densities can be computed for all pairs of $(v_i, v_j)$ by doing a depth-first search or a breadth-first search starting from each $v_i \in V$ after we obtain the variational approximation $q_{\bm\lambda}^{G'}(\bm z | \bm x)$ from \Cref{alg:updates}, which has a total complexity of $O(|V|^2)$, the same as evaluating every pairwise marginal in \glspl{CVAE}. For the remainder of the paper, unless otherwise specified, we always apply the belief propagation refinement to \glspl{ACVAE}. As we show in \Cref{sec:expe}, this refinement with belief propagation dramatically improves the quality of the pairwise marginal approximation. \section*{Appendix} In the appendix, we provide more details on our baseline method \acrshort{CVAE} \citep{tang2019correlated} as well as the experiment data pre-processing and protocols. \section{More details on \glspl{CVAE}} \label{app:cvae} \glspl{CVAE} set the prior $p_0^{\textrm{corr}_g}(\bm z)$ to be the uniform average over all of these tractable densities: \begin{equation} p_0^{\textrm{corr}_g}(\bm z)=\frac{1}{|\mathcal A_G|}\sum\limits_{G'=(V,E')\in\mathcal A_G} p_0^{G'}(\bm z), \end{equation} where $p_0^{G'}(\bm z)=\prod\limits_{i=1}^np_0(\bm z_i)\prod\limits_{(v_i,v_j)\in E'}\frac{p_0(\bm z_i,\bm z_j)}{p_0(\bm z_i)p_0(\bm z_j)}$ is a prior on a maximal acyclic subgraph $G'=(V,E')$ with the same form as in \Cref{eqn:prior-acyclic}. For each $G' \in \mathcal{A}_G$, we can similarly define a structured variational approximation $q_{\bm\lambda}^{G'}(\bm z | \bm x)$ following the form of \Cref{eqn:prior-acyclic}: \begin{equation*} q_{\bm\lambda}^{G'}(\bm z | \bm x)=\prod\limits_{i=1}^nq_{\bm\lambda}(\bm z_i | \bm x_i)\prod\limits_{(v_i,v_j)\in E'}\frac{q_{\bm\lambda}(\bm z_i,\bm z_j|\bm x_i,\bm x_j)}{q_{\bm\lambda}(\bm z_i|\bm x_i)q_{\bm\lambda}(\bm z_j|\bm x_j)}, \end{equation*} where $q_{\bm\lambda}(\cdot | \cdot)$ and $q_{\bm\lambda}(\cdot,\cdot | \cdot,\cdot)$ are two conditional density functions that captures the singleton and pairwise variational approximation densities. These two functions need to satisfy the symmetry and consistency properties: \begin{equation*} \begin{cases} q_{\bm\lambda}(\bm z_i, \bm z_j | \bm x_i, \bm x_j)=q_{\bm\lambda}(\bm z_j, \bm z_i | \bm x_j, \bm x_i)\text{\ \ for all }\bm z_i,\bm z_j,\bm x_i, \bm x_j,\\ \int q_{\bm\lambda}(\bm z_i, \bm z_j | \bm x_i, \bm x_j) d\bm z_j=q_{\bm\lambda}(\bm z_i| \bm x_i)\text{\ \ \ \ \ for all }\bm z_i,\bm x_i, \bm x_j. \end{cases} \label{eqn:q-constraint} \end{equation*} The ELBO in \Cref{eqn:lb1} is an average over potentially exponential many ELBOs. To make computations tractable, \citet{tang2019correlated} simplifies this lower bound and represent it as \begin{align} &\mathcal L^{\textrm{CVAE}}(\bm\lambda, \bm\theta):=\sum\limits_{i=1}^n\Big(\mathbb E_{q_{\bm\lambda}}(\bm z_i | \bm x_i)\left[\log p_{\bm\theta}(\bm x_i | \bm z_i) \right]-\text{KL}(q_{\bm\lambda}(\bm z_i | \bm x_i)||p_0(\bm z_i))\Big)-\sum\limits_{(v_i,v_j)\in E}w^{\text{MAS}}_{G, (v_i, v_j)}\nonumber\\ &\ \ \ \ \cdot\Big(\text{KL}(q_{\bm\lambda}(\bm z_i, \bm z_j | \bm x_i, \bm x_j)||p_0(\bm z_i, \bm z_j))-\text{KL}(q_{\bm\lambda}(\bm z_i | \bm x_i)||p_0(\bm z_i)) - \text{KL}(q_{\bm\lambda}(\bm z_j | \bm x_j)||p_0(\bm z_j))\Big). \label{eqn:elbo-cvae-general} \end{align} Where $w^{\text{MAS}}_{G, e}:=\frac{|\{G'\in\mathcal A_G: e\in G'\}|}{|\mathcal A_G|}$ for each edge $e=(v_i,v_j)$ represents the fraction of $G$'s maximal acyclic subgraphs of $G$ that contain $e$. These weights can be computed easily from the Moore-Penrose inverse of the Laplacian matrix of $G$. \section{Experimental details} \subsection{Dataset pre-processing details} \paragraph{Epinions} We follow the same pre-processing scheme as \citet{tang2019correlated}: binarize the rating data and create a bag-of-words binary feature vector for each user. We only retain the items that have been rated for at least 100 times. We construct the graph $G=(V,E)$ and only keep an edge $(v_i, v_j)$ to be in $E$ if both $v_i\rightarrow v_j$ and $v_j\rightarrow v_i$ appear in the original directed graph. At last, we only retain users that have at least one edge in $E$ (i.e. having at least one bi-directional edge in the original dataset). \paragraph{Citations} This dataset includes the abstract and the citation information for high-energy physic theory papers on arXiv from 1992 to 2003. We work on all papers from 1998 in this dataset (in total $\approx 2.8\text{K}$ papers). We treat all citation edges as undirected edges and build the graph $G=(V,E)$. We only retain papers that cite or are cited by at least one of the other papers from the same year). We compute TF-IDF for the abstract of each paper as feature vector. \subsection{Experimental protocol} \label{app:exp_proto} We run 3 runs for each methods for the Epinions experiment and 5 runs for each methods for the Citations experiment, as the Epinions experiments work more stable empirically. For \acrshort{VAE}, \acrshort{CVAE} and \acrshort{ACVAE}, we apply a two-layer feed-forward neural inference network for the singleton variational distribution $q_{\bm\lambda}(\bm z_i | \bm x_i)$'s and a two-layer feed-forward neural generative network for the model distribution $p_{\bm\theta}(\bm x | \bm z)$'s. $q_{\bm\lambda}(\bm z_i | \bm x_i)$ is a diagonal normal distribution with the mean and standard deviation outputted from the inference network and $p_{\bm\theta}(\bm x | \bm z)$ is a multinomial distribution with the logits outputted from the generative networks. The latent dimensionality $d$ is 100 for the Epinions dataset and 10 for the Citations dataset. The hidden layer dimensionality $h_1$ is 300 for the Epinions dataset and 30 for the Citations dataset. For GraphSAGE, we choose to use $K=2$ aggregation, the mean aggregator, and $Q=20$ negative samples to optimize the loss function. The hidden layer size and latent dimensionality we apply to GraphSAGE are the same with that of the standard \acrshort{VAE}. For \acrshort{CVAE} and \acrshort{ACVAE}, we set the pairwise marginal prior density function to be $p_0(\cdot)=\mathcal N\left(\bm\mu=\bm 0_{2d},\Sigma=\begin{pmatrix}I_d & \tau\cdot I_d\\ \tau\cdot I_d & I_d\end{pmatrix}\right)$ with $\tau=0.99$. For {\sc cvae}$_\textrm{corr}$ and \acrshort{ACVAE}, we model the pairwise variational approximations $q(\bm z_i, \bm z_j | \bm x_i, \bm x_j)$ to be a multi-variate normal distribution that can be factorized across the $d$ dimensions as the product of $d$ independent bi-variate normal distributions. The correlation coefficients of these bi-variate normal distributions are computed from two-layer feed-forward neural networks that taking $\bm x_i$ and $\bm x_j$ as inputs. These two-layer neural networks have latent dimensionality $h_2$ to be 1000 for the Epinions experiment and 30 for the Citations experiment. For \acrshort{CVAE} and \acrshort{ACVAE}, we set the negative sampling parameter $\gamma$ to be 1000 for the Epinions experiment and 100 for the Citations experiment. This parameter is selected from $\{0.1,1,10,100,1000\}$ and select the values based on performances. For all methods, we look into the performances for every fixed number of iterations (the specific numbers depend on models) and update the current best test NCRR values if both the train objective and the train NCRR reach better values. We report the final current best test NCRR values as the results. For \acrshort{ACVAE}, we set the step size parameter (in \Cref{eqn:soft-update}) $\alpha^t=0.1$ to be a constant. We train the parameters using alternating updates as in \Cref{alg:updates}. We switch between updates on the parameters $\bm\lambda$, $\bm\theta$ for an epoch of the edges in $E$, and a single update on the weights $w^{\text{MAS}}_{G, \pi, e}$ according to \Cref{eqn:soft-update}. For the random initialization on the tree weights $w^{\text{MAS}}_{G, \pi, e}$, we just assign random weights to the graph $G=(V,E)$. Then we use Kruskal's algorithm to compute the maximal acyclic subgraph $\tilde G=(V,\tilde E)$ according to these random weights, and set $w^{\text{MAS}}_{G, \pi, e}=I[e\in \tilde E]$. It is straightforward to see that this is a valid initialization for the weights $w^{\text{MAS}}_{G, \pi, e}$'s since these weights relate to the distribution $\bm{\tilde\pi}$ that has all of its mass on the single subgraph $\tilde G$. For all methods, we apply stochastic gradient optimizations and use Adam \cite{kingma2015adam} to adjust the learning rates. We set the step size to be $10^{-3}$. For all methods, we use a batch size $B_1=64$ for sampling the vertices. For \acrshort{CVAE} and \acrshort{ACVAE}, we use a batch size $B_2=256$ for sampling the edges and non-edges. All experiments are done using Python. The training and evaluations are done with TensorFlow \citep{abadi2016tensorflow} and Numpy. The TF-IDF values and the t-SNE embeddings \citep{maaten2008visualizing} in the visualization (\Cref{fig:vis}) are computed using Scikit-learn \citep{pedregosa2011scikit}. For faster computations, we call C++ functions to do belief propagation and the Kruskal's algorithm using Cython \citep{behnel2011cython}. \section{Conclusion} In this paper, we introduce \acrshortpl{ACVAE}, which learn a joint variational distribution on the latent embeddings of input data via saddle-point optimization of a loss function that is a non-uniform average over some tractable correlated ELBOs. The learned joint variational distribution can be used to perform efficient evaluations using belief propagation. Experiment results show that \acrshortpl{ACVAE} can outperform existing methods for link prediction on two real datasets. Future work will include learning higher-order correlations between latent variables. \section{Experiment} \label{sec:expe} In this section, we evaluate \glspl{ACVAE} on the task of link prediction. We show that our method significantly outperforms various baselines. We perform careful corroboration to identify the contributing factor for the gain. Finally, we present a visualization of the learned correlated posterior variational approximation to illustrate the maximal acyclic subgraph $\hat G'$. \subsection{Experiment settings} \subsubsection{Task} For the task of link prediction, we are given a correlation graph $G=(V=\{v_1,\ldots,v_n\}, E)$ and a feature vector $\bm x_i\in\mathbb R^N$ for each $i\in\{1,\ldots,n\}$. Consistent with the setting of \citet{tang2019correlated}, we construct a heldout test set using $\max(1,\frac{\text{degree}(v_i)}{20})$ of the edges related to $v_i$, and use the remaining edges for training. \subsubsection{Datasets} We evaluate \glspl{ACVAE} on the Epinions\footnote{\href{http://www.trustlet.org/downloaded\_epinions.html}{http://www.trustlet.org/downloaded\_epinions.html}} \citep{massa2007trust}, a public product rating dataset that contains $\approx49\text{K}$ users and $\approx140\text{K}$ products, and the High-energy physics theory citation network dataset\footnote{\href{http://snap.stanford.edu/data/cit-HepTh.html}{http://snap.stanford.edu/data/cit-HepTh.html}} \citep{snapnets}, a citation graph with $\approx 28\text{K}$ papers and $\approx 353\text{K}$ citation edges. \subsubsection{Baselines} We compare \acrshort{ACVAE} with 4 baseline methods: \begin{itemize} \item \gls{VAE} \citep{kingma2013auto}: standard variational auto-encoders, with no information about the correlations. \item GraphSAGE \citep{hamilton2017inductive}: the state-of-the-art method for learning latent embeddings that takes the correlation structure into account with graph convolutional neural networks. \item {\sc cvae}$_\textrm{ind}$ and {\sc cvae}$_\textrm{corr}$ \citep{tang2019correlated}: Two variations of \glspl{CVAE} with factorized and structured variational approximations, respectively. \end{itemize} \subsubsection{Metrics} For all methods, we first learn latent embeddings $\bm z_1,\ldots,\bm z_n$, which are deterministic for GraphSAGE and stochastic for the \glspl{VAE}-related methods. Then we compute the pairwise distance $\text{dis}_{i,j}$ between each pair $(\bm z_i, \bm z_j)$ of the latent embeddings. The distance $\text{dis}_{i,j}$ is defined as \begin{equation*} \text{dis}_{i,j}= \begin{cases} \mathbb E_{r(\bm z_i, \bm z_j | \bm x_i, \bm x_j)}\left[\Vert\bm z_i-\bm z_j\Vert_2^2\right]&\text{ for \acrshort{ACVAE}}\\ \mathbb E_{q(\bm z_i, \bm z_j | \bm x_i, \bm x_j)}\left[\Vert\bm z_i-\bm z_j\Vert_2^2\right]&\text{ for \acrshort{VAE} and \acrshort{CVAE}}\\ \Vert\bm z_i-\bm z_j\Vert_2^2&\text{ for GraphSAGE.} \end{cases} \end{equation*} For each user $u_i$, we compute the \textit{Cumulative Reciprocal Rank} (CRR) as follows: \[ \text{CRR}_i=\sum\limits_{(v_i,v_j)\in E_{\text{test}}} \frac{1}{|\{k:(v_i,v_k)\not\in E_{\text{train}},\text{dis}_{i,k}\le\text{dis}_{i,j}\}|}. \] A larger CRR value indicates the heldout edges have a higher rank among all the candidates. We further normalize the CRR values to be in $[0,1]$, and report the normalized CRR (NCRR). More details on data pre-processing and the experimental protocols can be found in the appendix. \subsection{Results} We show the heldout NCRR values in \Cref{tab:ncrr}. \gls{ACVAE} outperforms all the baseline methods by a wide margin. \glspl{CVAE} outperform both \glspl{VAE} and GraphSAGE in \citet{tang2019correlated}. Therefore, we focus our attention to the comparison between \glspl{CVAE} and \glspl{ACVAE}. As motivated in \Cref{sec:cvae}, \glspl{ACVAE} improve over the limitations of \glspl{CVAE} by providing a holistic variational approximation as a result of the saddle-point optimization, which further enables applying belief propagation for more accurate marginal approximation. We look into each aspect individually. \paragraph{Saddle-point optimization v.s. empirical Bayes} From \Cref{sec:minimax}, we know that $\bm\pi$ will put all the probability mass on a single maximal acyclic graph in both the saddle-point optimization in \Cref{eqn:opt} or empirical Bayes. We compare these two approaches on Epinions. For empirical Bayes, we observe a test NCRR of only $0.0300\pm0.0093$, which is worse than \glspl{ACVAE} with saddle-point optimization in \Cref{tab:epinions}. Interestingly, in \Cref{fig:curve}, we can see that empirical Bayes actually reaches much higher ELBOs, yet it fails to generalize as well as saddle-point optimization which proves more robust. \paragraph{Belief propagation refinement} We investigate the importance of using belief propagation refinement on Epinions: without it, we only observe a test NCRR of $0.0133\pm0.0005$, a significant decline. This suggests that variational approximation can yield significantly different results when compared with exact inference (i.e., belief propagation) on an acyclic graph. \begin{table} \centering \caption{Link prediction normalized CRR} \subtable[Normalized CRR on Epinions]{ \begin{tabular}{ll} \toprule Name & Test NCRR \\ \midrule \acrshort{VAE} & $0.0052\pm0.0007$ \\ GraphSAGE & $0.0115\pm0.0025$ \\ {\sc cvae}$_\textrm{ind}$ & $0.0160\pm0.0004$ \\ {\sc cvae}$_\textrm{corr}$ & $0.0171\pm0.0009$ \\ \acrshort{ACVAE} & $\bm{0.0434\pm0.0014}$ \\ \bottomrule \label{tab:epinions} \end{tabular} } \hspace{0.2in} \subtable[Normalized CRR on Citations]{ \begin{tabular}{ll} \toprule Name & Test NCRR \\ \midrule \acrshort{VAE} &$0.0078\pm0.0023$ \\ GraphSAGE & $0.0143\pm0.0050$ \\ {\sc cvae}$_\textrm{ind}$ & $0.0335\pm0.0052$ \\ {\sc cvae}$_\textrm{corr}$ & $0.0663\pm0.0020$ \\ \acrshort{ACVAE} & $\bm{0.1052\pm0.0054}$ \\ \bottomrule \label{tab:citations} \end{tabular} } \label{tab:ncrr} \end{table} \begin{figure} \vspace{-.2in} \centering \subfigure[Training learning curves for the Epinions experiment. Belief propagation evaluations are applied. We compare the training objective for saddle-point optimization and empirical Bayes optimization. It can be seen that the objective for empirical Bayes optimization is much better compared to that for the saddle-point optimization.]{ \includegraphics[width=0.45\textwidth]{curve.pdf} \label{fig:curve}} \hspace{0.2in} \subfigure[Embeddings of an induced maximal acyclic subgraph $\hat G'$ that \glspl{ACVAE} learns on the citations experiment. The coordinates are t-SNE embeddings for the variational approximation mean of the latent variables. The edge widths represent the strength of the learned correlations. We can see some of the learned embeddings are not necessarily close to each other even when they have high correlations. Colors for better clarity only. ]{ \includegraphics[width=0.45\textwidth]{vis.pdf} \label{fig:vis} } \caption{Training learning curves on Epinions and latent embedding visualization on Citations.} \end{figure} \Cref{fig:vis} visualizes the largest connected component of the maximal acyclic subgraph $\hat G'=(V,\hat E')$ that \acrshort{ACVAE} learns for the variational distribution on the citations dataset. We can see that, not all the vertices with edges in $\hat E'$ are close to each other, which indicates that the learned $\hat G'$ provides some additional information that singleton marginals cannot provide. \section{Introduction} \Acrlongpl{VAE} (\acrshortpl{VAE}) \citep{kingma2013auto,rezende2014stochastic} are a family of deep generative models that learn latent embeddings for data. By applying variational inference on the latent variables, \acrshortpl{VAE} learn a stochastic mapping from high-dimensional data to low-dimensional representations, which can be used for many downstream tasks, including classification, regression, and clustering. \acrshortpl{VAE} assume the data points are $i.i.d.$ generated and treat the model and posterior approximations as factorized over data points. However, if we know \emph{a priori} that there is structured correlation between the data points, e.g., for graph-structured datasets \citep{shi2014correlated,bruna2013spectral,hamilton2017inductive,tang2019correlated}, correlated variational approximations can help. \citet{tang2019correlated} proposed \acrlongpl{CVAE} (\acrshortpl{CVAE}), which take this kind of correlation structure as auxiliary information to guide the variational approximations for the latent embeddings by taking a prior as a uniform mixture of tractable distributions on \emph{maximal acyclic subgraphs} of the given undirected correlation graph. However, there are several limitations that potentially prevent \acrshortpl{CVAE} from learning better correlated latent embeddings. First, it is possible that some of the maximal acyclic subgraphs of the given graph can, by themselves, well-capture the correlation between the data points while others may poorly capture the correlation. As a result, taking a uniform average may yield a sub-optimal result. Second, while the prior \acrshortpl{CVAE} is over multiple subgraphs, each subgraph has a unique joint variational distribution, and there is no single \emph{global} joint variational distribution over the latent variables. In addition, \acrshortpl{CVAE} require a pre-processing step that takes an amount of time cubic in the number of vertices, which limits its applicability to smaller datasets. To address these issues, we propose \acrlongpl{ACVAE} (\acrshortpl{ACVAE}), which chooses a non-uniform average over tractable distributions on the maximal acyclic subgraphs as a prior. This prior is adaptive, and will be adjusted during optimization. We apply a saddle-point optimization procedure that maximizes the objective with respect to the model and variational parameters and minimizes the objective with respect to the prior structure for more robust inference. The non-uniform average converges to a tractable prior on a single graph, which ensures that we obtain a holistic tractable joint variational distribution. With this variational distribution, we obtain more accurate marginal evaluation using exact inference algorithms (e.g., belief propagation). Moreover, \acrlongpl{ACVAE} do not require the cubic time pre-processing step embedded in \acrshortpl{CVAE}. We demonstrate the superior empirical performance of \acrlongpl{ACVAE} for link prediction on various real datasets. \section{Related Work} This work extends \acrshortpl{CVAE} with the idea of learning a non-uniform average loss over some tractable loss functions on maximal acyclic subgraphs of the given graph. This is similar to the idea of obtaining a tighter upper bound on the log-partition function for an undirected graphical model by minimizing over a convex combination of spanning trees of the given graph \citep{wainwright2005new}. To optimize the parameters, \citet{wainwright2005new} also apply alternating updates on the parameters and the distributions over the spanning tress, similar to the approach in \acrshort{ACVAE} learning. Alternating parameter updates are useful for many other cases. For example, Alternating Least Squares for matrix factorization \citep{takane1977nonmetric} and Alternating Direction Method of Multipliers (ADMM) for convex optimization \citep{chambolle2011first,tang2015duality,hong2017linear}. Some recent work also focuses on incorporating correlation structures over latent variables. For example, \citet{hoffman2015stochastic} proposed structured variational families that can improve over traditional mean-field variational inference. \citet{johnson2016composing} proposed Structured \acrshortpl{VAE} that apply more complex forms for the priors on the latent embeddings. Recently in the NLP community, \citet{yin2018structvae} proposed utilizing tree-structured latent variable models to deal with semantic parsing. However, most of these work focuses on correlations \emph{within} dimensions of latent variables whereas our work focus on correlations \emph{between} latent variables, similar to the setting of \acrshortpl{CVAE}. In addition, \citet{luo2018semi} incorporated pairwise correlations between latent variables into deep generative models for semi-crowdsourced clustering . In addition, another set of related work line in convolutional networks for graphs and their extensions \citep{bruna2013spectral,duvenaud2015convolutional,defferrard2016convolutional,niepert2016learning,hamilton2017inductive,velivckovic2018deep}, which also take graph structure of data into considerations.
{'timestamp': '2019-07-18T02:01:59', 'yymm': '1906', 'arxiv_id': '1906.06419', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06419'}
arxiv
\section{Introduction} Social networks have an important role in spreading {the political} views of their users{, who may be} public figures {or} common citizens \citep{Weller2014}. Twitter, in particular, is an online social network {used to} post short texts, called \textit{tweets}, through which {the users} express {their opinions}, thoughts and feelings. In addition, users can make or share public statements {they agree with} \citep{pak2010twitter}. {They may} also interact with each other on Twitter {through} the option ``follow'' and by retweeting {other tweets}. In this sense, Twitter presents valuable information {on} public opinion on various areas and can be employed for a variety of purposes, {e.g.}, to direct marketing ads \citep{cambria2013new} and to guide political campaigns \citep{larsson2012studying,Golbeck2010,Yardi2010}. This online social network has approximately 321 million active users \citep{verge}. Brazil is one of the 10 countries with the highest number of active accounts in Twitter according to information provided by the company. Therefore, {data mining algorithms play a key role in} the analysis of networks created {with} data collected from Twitter. {Context mining, in particular,} is a research topic that has attracted {the} attention of the scientific community \citep{Conover2011_predicting,Pennacchiotti2011_democrats,Makazhanov2014,Surian2016,Gaul2017,Ahmadi2018}. A number of tools has been proposed for {the} analysis {of} Twitter data, among {which} we highlight {the ones} based on natural language processing techniques \citep{ding2007utility,Sun2017} and supervised machine learning algorithms \citep{Pennacchiotti2011_democrats,Conover2011_predicting,Makazhanov2014}. These strategies aim at detecting {users' opinions and feelings according to the content of what they publish.} A major drawback {of} natural language processing techniques is the diversity of linguistic rules. Furthermore, supervised machine learning methods can {only be used} when there is enough labeled data {to train} the algorithm. Graph-based techniques, on the other hand, compile Twitter data into graphs {where} the vertices are the users and the arcs {are the} interactions between users. These techniques use graphs with unlabeled data to detect public opinions. Examples of graph-based techniques can be found in \citep{Conover2011_predicting,Pennacchiotti2011_democrats,Sluban2015,Surian2016}. According to a social network property known as homophily \citep{Tang2014}, users are more likely to retweet or mention tweets {from other} users {they share a common interest with}. {Community} detection in networks, thereby, can provide useful information {on} whether or not {tweets share} the same contexts. In light of the recent corruption investigations in Brazil and the presidential elections, {discussions} in social networks about the Brazilian political scenario {have seen a significant increase}. {In the study reported here}, we extracted data {from tweets} containing words related to politicians who would reportedly run for the 2018 Brazilian presidential elections and to corruption {investigations} in Brazil. The Twitter API \citep{twitterapi} was employed to extract data concerning {interactions between users}, such as retweets and mentions, to construct the Twitter networks proposed in this paper. The primary purpose of this {study was} to analyze the structure and topology of networks constructed {with data from Twitter in order to classify} users according to the subject of their tweets using community detection algorithms and to investigate the sentiment associated with the communities in the networks related to the Brazilian {presidential} elections. We also confirmed the observation {by \citet{Weng2013}} that a few popular tweets, referred to as viral tweets, spread across the communities like viruses and, therefore, are not expected to affect the community structure. {Non-viral} tweets, on the other hand, get trapped in the communities {where} they originated and, thereby, are expected to {stay} within the communities. The networks under investigation are scale-free {and therefore have} few {high-degree vertices} and a large number of {low-degree} vertices. In other words, a few popular users contribute to most of the retweets and mentions on these networks. Thereby, the {most retweeted tweets are the ones} posted by the most popular users. In addition, a case study {on the} networks related to the Brazilian {presidential} elections showed that {words} associated with positive sentiments are predominant in the communities. Amongst these words, the ones which contribute {most} to the positive sentiment in the communities are the {same words} that appear in viral tweets. The {remainder} of {the} paper is organized as follows: Section \nameref{sec:rev_community_detection} introduces basic concepts and algorithms for community detection in networks; Section \nameref{sec:related_works} presents a brief discussion about related works; Section \nameref{sec:database} shows the networks constructed from Twitter data; Section \nameref{sec:computational_experiments} presents the computational experiments carried out with community detection algorithms; Section \nameref{sec:network_analysis} presents a network analysis where the structure of the introduced networks is investigated; Section \nameref{sec:community_classification} investigates the communities related to the 2018 Brazilian {presidential} elections and the sentiments associated with them; and Section \nameref{sec:conclusion} summarizes the contributions of the paper and gives directions to {future} works. \section{Community Detection in Networks}\label{sec:rev_community_detection} This section presents {the} theoretical background and {primary} notations used throughout the paper. Moreover, it introduces some of the classical community detection algorithms employed in studies related to our investigation found in the literature{, and which} will also be the tools {used for} the network analysis in this paper. \subsection{Basic Concepts and Notations}\label{sec:notations} In this paper, a network is defined as a directed graph (digraph) $G=(V,A,\omega)$, where $V$ and $A$ are, respectively, its sets of vertices and arcs and $\omega:A \rightarrow \mathds{N}$ is a function that assigns a weight to each arc of the digraph. An arc $e$ is defined {as} an ordered tuple $(v,u)$, where {the points} $v,u \in V$ are called tail and head of $e$, respectively. Let $n=|V|$, $m=|A|$ and $\Omega= \sum_{e \in A}{\omega(e)}$ be, respectively, the number of vertices, number of arcs and the total weight of arcs of $G$. The in- and out-degrees of a vertex $v$ are given by, respectively, $d^{in}(v)=\sum_{(z,v)\in A} \omega(z,v)$ and $d^{out}({v})=\sum_{(v,z)\in A} \omega(v,z)$. Moreover, the degree of a vertex $v$ is defined by ${d(}v)=d^{in}(v)+d^{out}(v)$. A partition of $V$ into $k$ communities is given by $\mathcal{P}=\{P_1,P_2,\dots,P_k\}$, where $\bigcup_{i=1}^k P_i=V$ and $P_i \cap P_j=\emptyset$, $\forall i,j \in \{1,2,\dots,k \}, i\neq j$. The community of a vertex $v$ is referred to as $\mathcal{P}(v)$. Moreover, let $G[V']$ be the vertex-induced subgraph, which is the subgraph of $G$ such that $V(G[V']) =V'$ and $A(G[V'])$ is composed by all arcs in $A$ {whose} points are in $V'$. \subsection{Community Evaluation Metrics} One way of evaluating the quality of the community structure of a given partition is by calculating its closeness to the expected partition according to {metrics}, like the Normalized Mutual Information (NMI) proposed in \citep{Shannon1948}. However, as the expected partition is not available in most applications, {in order to evaluate the quality of partitions}, we employed the widely used evaluation measure known as modularity. Modularity is based on the intuitive notion that vertices belonging to the same community are more likely to connect with each other than with vertices from different communities. Equation \eqref{eq:modularity} defines the modularity measure for weighted undirected graphs \citep{Leicht2008} {applied to a partition $\mathcal{P}$ {of} digraph $G$}. \begin{equation} Q(\mathcal{P}) = \frac{1}{2 \Omega} \sum_{P \in \mathcal{P}} \sum_{{(i,j)\in A(G[P])}}\left( \omega(i,j) - \frac{d(i) d(j)}{4 \Omega} \right) \label{eq:modularity} \end{equation} {As can be seen in} Equation \eqref{eq:modularity}, the modularity of $\mathcal{P}$ consists {in} the difference between the total weight of the arcs between vertices of a same community {and} the expected sum of weights of edges inside communities in a random undirected graph whose vertices have the same degree sequence as the digraph under consideration. The values of the measure range from $-1$ to $1$ and the higher the value, the better the partition. \subsection{Community Detection Algorithms} Since the modularity measure {was proposed by} {\citet{Newman2004c}}, several authors {have studied ways} to detect {community structures} in a plethora of complex networks. In particular, community detection algorithms {that} aim at maximizing the modularity measure have been extensively studied \citep{Newman2004,Blondel2008,Santos2016a,Francisquini2017}. \citet{Blondel2008} presented the Louvain method, a multilevel greedy algorithm {for} modularity maximization that was successfully applied to a web graph with 118 million vertices and 1 billion edges. \citet{Newman2006} studied a {spectral} decomposition {using} the leading eigenvector of the modularity matrix and introduced a greedy algorithm to define the communities. Despite the good results {achieved} by modularity maximization-based methods, the measure has a resolution limit that {restricts} the size of the communities found by the algorithms. \citet{Yang2016} showed that the leading eigenvector algorithm {proposed by} \citet{Newman2006} found partitions far from the expected even in networks with small mixture coefficients\footnote{The mixture coefficient of a network is the percentage of edges or arcs crossing communities with respect to the total number of edges or arcs in the graph.}. \citet{Yang2016} also showed that the Louvain method was able to find the expected communities in networks with small mixture coefficients {and partitions sufficiently close to the ones expected for the networks} with high mixture coefficients. Among the algorithms that aim {to optimize} different measures, we highlight those proposed in \citep{Pons2005,Rosvall2007,Lancichinetti2011_oslom}. \citet{Pons2005} introduced the Walktrap algorithm to detect vertex partitions {based on the random walkers' probabilities of finding trails between vertices in the networks}. \citet{Rosvall2007} introduced the map equation measure to calculate the description length of a random walker in a digraph. The Infomap algorithm, also proposed by the authors, minimizes the map equation to find communiries in networks. Walktrap achieved results comparable {with the ones achieved by} Louvain, whereas Infomap {achieved} worse {results in} networks with higher mixture coefficients \citep{Yang2016}. \citet{Lancichinetti2011_oslom} suggested {finding} communities in networks by evaluating the communities {according to} their statistical significance. They proposed an algorithm named Order Statistics Local Optimization Method (OSLOM), {which obtained} better results than all the aforementioned algorithms in networks with the higher mixture coefficients, according to \citet{Lancichinetti2011_oslom}. Nevertheless, OSLOM requires more computational time than the other algorithms to find the communities. The community detection algorithm known as Label Propagation (LP) \citep{Raghavan2007} is neighborhood-based and does not optimize any measure. To form the communities, it starts from a partition whose vertices are isolated in their own communities -- singletons --- and iteratively assigns each vertex to the community {the} majority of its neighbors belong to. The computational complexity of LP is quasi-linear, being very fast in detecting communities. However, {LP} is highly dependent on the number of iterations since if it is too high, it tends to merge all communities into a single cluster. Next section presents a brief literature review of studies related to the classification of users in Twitter networks. \section{Related Works}\label{sec:related_works} This section {briefly} discusses classical approaches for mining public opinion in social networks through natural language processing and {s}upervised machine learning algorithms. Special attention is given to applications using information extracted from Twitter and to works that classify users based on community detection algorithms. Natural language processing techniques use a set of words that describe opinion and linguistic rules to infer {users' opinions} on Twitter. Although rule-based techniques are rather effective, linguistic rules usually change along the years and differ from language to language. In addition, users always follow linguistic rules in their posts. Thus, these techniques are very limited and {strongly} dependent {on} specialist knowledge \citep{wang2011topic}. For further details on these techniques, we refer the reader to the recent review in \citep{Sun2017}. Supervised machine learning approaches are commonly applied to different domains and {can therefore} overcome the challenges {presented by} rule-based methods. Among these approaches, we highlight the methods studied in \citep{Conover2011_predicting,Pennacchiotti2011_democrats,Makazhanov2014}. \citet{Pennacchiotti2011_democrats} trained a decision tree to learn Twitter users' information, such {as} political affiliation, ethnicity and whether {the users were} fans of a famous coffee shop {according to} the number of followers and friends, number of replies, average number of tweets and linguistic content of tweets. \citet{Makazhanov2014} also trained a decision tree coupled with a logistic regression to learn about political positions through the {interaction} between users. \citet{Conover2011_predicting} predicted the political alignment of Twitter users {by using} a Support Vector Machine (SVM) trained with the contents of users' tweets. However, these supervised methods require labeled data to be used as training data. Generally, real-time data are not inherently labeled. In such cases, a specialist can manually label a small sample for training machine learning algorithms, as performed in \citep{Conover2011_predicting}. In dealing with big data, manual data labeling is not viable, since if a very small sample is used for training, the model becomes unreliable \citep{Raudys1991}. Community detection in networks {does} not need any prior knowledge about the data classes and mostly {does} not rely on rule-based techniques. These algorithms detect communities whose users interact more {among} each other, in terms of friendship, retweets or mentions, than with the rest of the users. {Community} detection in networks {can thereby} provide useful sharing information {on} tweets among {users} \citep{Conover2011_predicting,Sluban2015}. In addition to the SVM classifier, \citet{Conover2011_predicting} employed a community detection algorithm based on the leading eigenvector method \citep{Newman2006} and on the label propagation algorithm \citep{Raghavan2007}. \citet{Sluban2015} detected the communities of a Twitter network using the Louvain method \citep{Blondel2008} and then identified the topics of the tweets in each community using a content-based classification algorithm. \citet{Surian2016} investigated discussions about HPV vaccines {on} Twitter using a community detection algorithm to infer about the topics of the tweets. Despite not explicitly employing a community detection algorithm, \citet{Pennacchiotti2011_democrats} refined the results found by a supervised classification method by updating the classes of the users according to the classes {their} friends {belonged} to. \citet{Weng2013} studied the spreading of hashtags on Twitter networks and {observed} that a few viral hashtags {disseminate through} the communities like viruses, while {most} get trapped within the communities where they originated. According to \citet{Weng2013}, {the virality of a tweet can be measured {as the} percentage of retweets it receives from users of {communities different} than the community of the user who posted it.} Let $\mathcal{P}$ be a partition of vertices into communities. Equation \eqref{eq:virality} defines the virality of a tweet $tw$ posted by a user $v$ from a community $\mathcal{P}(v)$. \begin{equation} vir(tw) = \frac{\sum_{j \in \mathcal{J}, \mathcal{P}(j)\neq \mathcal{P}(v)} {\omega}({v,j})} {\sum_{j \in \mathcal{J}} {\omega}({v,j})} \label{eq:virality} \end{equation} \noindent where $\mathcal{J}=\{j \in V \mbox{ such that } (v,j) \in A \mbox{ and } j \mbox{ retweeted } tw \}$ is the set of users who retweeted tweet $tw$. As \citet{Weng2013} affirmed that viral tweets spread equally to the communities, we can expect that {they} do not affect the community structure of the networks. Non-viral tweets, on the other hand, spread mostly {in} the {communities} where they {originated} and, thus, are expected to define the community structure of the networks. Next section discusses the {methodology} employed to extract information from Twitter to construct the networks under evaluation in this paper. \section{Extracted Networks}\label{sec:database} In this paper, we constructed directed networks {from} data collected {on} Twitter using the streaming API {\citep{twitterapi}}{, which} returns {samples of} recent tweets {matching the application queries.} The vertices of the digraphs represent the Twitter users from the sample of tweets. {Arc} $e=(v,u)$ {in} digraph $G$ expresses that user $v$ was mentioned, {replied to} or {posted} a tweet $tw$ that was retweeted by user $u$. The weight {of} arc $e$, ${\omega(e)}$, is the number of {times} $v$ was mentioned, {replied to} or {retweeted} by user $u$. Figure \ref{fig_ex_arc_tweet} shows a triplet whose arcs were added due to tweets. In this figure, user $u$ retweeted a tweet {from} user $v$, creating arc ($v,u$). In addition, user $z$ mentioned user $v$ in another tweet, represented by arc $(v,z)$. Note that the arcs of the networks do not {distinguish retweets from mentions}. \begin{figure}[!htb] \begin{center} \small \begin{tikzpicture}[node distance = 0.6cm, auto] \node [node] (v3) {$z$}; \node [node, right=3.5cm of v3] (v1) {$v$}; \node [node, right=3.5cm of v1] (v2) {$u$}; \path[line] (v1) --node{$v$ was retweeted by $u$ } (v2); \path[line, above=2cm] (v1) --node{$v$ was mentioned by $z$ } (v3); \end{tikzpicture} \caption{Example of a network with 3 users and whose arcs were created due to retweets and mentions.} \label{fig_ex_arc_tweet} \end{center} \end{figure} {Table \ref{tab:network_queries} presents the queries employed to construct the networks. Table \ref{tab:network_network} presents the number of vertices ($n$) and arcs ($m$); total weight of the arcs ($\Omega$){; and} the average (avg), standard deviation (std), minimum (min) and maximum (max) in- and out-degrees {of the} proposed networks.} Note that the sum of the in-degrees and the sum of the out-degrees of all vertices are equal to the total weight of the arcs, $\Omega$, since each arc $e=(v,u)$ of $G$ counts $\omega{{(e)}}$ to the out-degree of $v$ and to the in-degree of $u$. Consequently, the average in- and out-degrees are the same. The networks introduced in this paper have the maximum out-degree at least $13.55$ times larger than the maximum in-degree. {The \textit{Politicians} network} was constructed by querying Twitter API tweets {matching} the names of politicians who {demonstrated} interest in running {for the} 2018 Brazilian {presidential} elections. As this network was constructed before the politicians {had effectively} presented {their} candidacy, we selected the names based on an article published {by the} BBC \citep{bbc_article_election}. {The \textit{Bolsonaro} and \textit{Lula} networks} captured {interactions in} tweets that {referred} to politicians Jair Bolsonaro and Luiz Inácio Lula da Silva, respectively; {\textit{LavaJato} network was} formed by tweets presenting reactions {to} Operation Car {Wash, in Brazil, which} investigates executives {who have} reportedly accepted bribes from construction firms in exchange for inflating contracts prices. {\textit{1st\_Round} and \textit{2nd\_Round} networks} were constructed using, respectively, tweets expressing reactions to the first and second rounds of the 2018 Brazilian {presidential} elections\footnote{The Brazilian {presidential} elections {are} composed {of} two rounds. In case the most voted candidate in the first round does not get the absolute majority of the votes, the second round of the election occurs. In the second round, the two most {voted candidates} in the first round are the only {ones} to run.}. These last two networks only model interactions using retweets. \begin{table}[htb] \centering \caption{Information on the queries submitted to Twitter streaming API.} \small \label{tab:network_queries} \setlength{\tabcolsep}{1pt} \begin{tabular}{|c|c|c|} \hline \multirow{1}{*}{Network} & \multirow{1}{*}{Query} & \multirow{1}{*}{Date} \\ \hline \multirow{3}{*}{\textit{Politicians}} & lula,bolsonaro,alckmin,temer,cirogomes, marinasilva, & \multirow{2}{*}{May 15, 2018 to} \\ & alvarodias, fernandohaddad, manueladavila,guilhermeafif, & \multirow{2}{*}{May 16, 2018} \\ & fernandocollor, guilhermeboulos,joaoamoedo & \\ \hline \multirow{2}{*}{ \textit{Lula}} & lulapreso,lula preso,lulalivre,lula livre, & May 7, 2018 to\\ & & May 9, 2018 \\ \hline \multirow{2}{*}{\textit{Bolsonaro}} & bolsonaro, bolsonaro2018, jair bolsonaro, bolsonaro presidente, & May, 7 2018 to\\ & \#bolsonaro2018, \#bolsonaropresidente, \#bolsonaro & May 14, 2018 \\ \hline \multirow{2}{*}{\textit{LavaJato}} & \multirow{2}{*}{lavajato,lava-jato,``lava jato''} & May, 7 2018 to \\ & & May 14, 2018\\ \hline \multirow{4}{*}{\textit{1st\_Round}} & jairbolsonaro,bolsonaro,fernandohaddad,haddad, cirogomes, & \multirow{4}{*}{7 October, 2018} \\ & ciro,geraldoalckmin,alckmin, marinasilva, marina & \\ & alvarodias,henriquemeirelles, meirelles, joaoamoedo,amoedo&\\ & guilhermeboulos, boulos, josemariaeymael,cabodaciolo &\\ \hline \multirow{4}{*}{\textit{2nd\_Round}} & jairbolsonaro,bolsonaro,fernandohaddad,haddad, cirogomes, & \multirow{4}{*}{28 October, 2018}\\ & ciro,geraldoalckmin,alckmin,marinasilva,marina, & \\ & alvarodias,henriquemeirelles, meirelles, joaoamoedo,amoedo &\\ & guilhermeboulos, boulos, josemariaeymael,cabodaciolo &\\ \hline \end{tabular} \end{table} \begin{table}[htb] \centering \caption{Information on the networks extracted from Twitter.} \small \label{tab:network_network} \setlength{\tabcolsep}{2pt} \begin{tabular}{|c|c|c|c|c|c|c|c|c|c|c|c|} \hline \multirow{2}{*}{Network} & \multirow{2}{*}{$n$} & \multirow{2}{*}{$m$} & \multirow{2}{*}{$\Omega$} & \multicolumn{4}{|c|}{in-degree} & \multicolumn{4}{|c|}{out-degree} \\ \cline{5-12} & & & & avg & std & min & max & avg & std & min & max \\ \hline \multirow{1}{*}{\textit{Politicians}} & \multirow{1}{*}{16137} & \multirow{1}{*}{31933} & \multirow{1}{*}{40858} & \multirow{1}{*}{2.53} & \multirow{1}{*}{6.06} & \multirow{1}{*}{0} & \multirow{1}{*}{359} & \multirow{1}{*}{ 2.53} & \multirow{1}{*}{32.39 } & \multirow{1}{*}{0} & \multirow{1}{*}{2875} \\ \hline \multirow{1}{*}{ \textit{Lula}} & \multirow{1}{*}{13319} & \multirow{1}{*}{33519} & \multirow{1}{*}{40456} & \multirow{1}{*}{3.04} & \multirow{1}{*}{7.8} & \multirow{1}{*}{0} & \multirow{1}{*}{236} & \multirow{1}{*}{3.04} & \multirow{1}{*}{35.8} & \multirow{1}{*}{0} & \multirow{1}{*}{1798} \\ \hline \multirow{1}{*}{\textit{Bolsonaro}} & \multirow{1}{*}{873} & \multirow{1}{*}{1264} & \multirow{1}{*}{1676} & \multirow{1}{*}{1.92} & \multirow{1}{*}{2.75} & \multirow{1}{*}{0} & \multirow{1}{*}{32} & \multirow{1}{*}{1.92} & \multirow{1}{*}{9.62} & \multirow{1}{*}{0} & \multirow{1}{*}{178} \\ \hline \multirow{1}{*}{\textit{LavaJato}} & \multirow{1}{*}{14081} & \multirow{1}{*}{35642} & \multirow{1}{*}{42937} & \multirow{1}{*}{3.05} & \multirow{1}{*}{7.8} & \multirow{1}{*}{0} & \multirow{1}{*}{237} & \multirow{1}{*}{3.05} & \multirow{1}{*}{35.16} & \multirow{1}{*}{0} & \multirow{1}{*}{1798} \\ \hline \multirow{1}{*}{\textit{1st\_Round}} & \multirow{1}{*}{135865} & \multirow{1}{*}{242679} & \multirow{1}{*}{249042} & \multirow{1}{*}{1.83} & \multirow{1}{*}{2.49 } & \multirow{1}{*}{ 0} & \multirow{1}{*}{103} & \multirow{1}{*}{1.83} & \multirow{1}{*}{42.76} & \multirow{1}{*}{ 0 } & \multirow{1}{*}{6032} \\ \hline \multirow{1}{*}{\textit{2nd\_Round}} & \multirow{1}{*}{100755} & \multirow{1}{*}{171813} & \multirow{1}{*}{176955} & \multirow{1}{*}{1.76} & \multirow{1}{*}{2.38} & \multirow{1}{*}{ 0} & \multirow{1}{*}{79} & \multirow{1}{*}{ 1.76 } & \multirow{1}{*}{33.17} & \multirow{1}{*}{ 0 } & \multirow{1}{*}{3863} \\ \hline \end{tabular} \end{table} The following section presents computational experiments with community detection algorithms {in these networks.} \section{Computational Experiments with Community Detection Algorithms}\label{sec:computational_experiments} In {the experiments presented in this section}, we considered four different community detection algorithms available in the igraph package \citep{igraph}: Louvain Method \citep{Blondel2008}, Label Propagation (LP) \citep{Raghavan2007}, Infomap \citep{Rosvall2007} and Walktrap \citep{Pons2005}. Even {though the} Infomap {method} has a version to detect communities in digraphs, the version to undirected graphs found communities with higher modularity values and was therefore selected for the experiments. All the experiments were carried out on a computer with {an} Intel Core Xeon E5-1620 processor with 3.7-GHz and 32GB of main memory. Table \ref{tab:modularity} shows the modularity of the partitions obtained by the algorithms {for} each of the networks used. In this table, the columns marked as ``Modularity'' refer to the {modularity value} of the partitions obtained by the community detection {algorithms according to Equation \eqref{eq:modularity}.} The columns marked as ``Time'' report the time (in seconds) required to detect the communities. Due {to} computer memory limitations, Walktrap could not find the communities for networks \textit{1st\_Round} and \textit{2nd\_Round}. \begin{table}[htb] \centering \small \caption{Modularity values {of communities} achieved by reference community detection algorithms.} \label{tab:modularity} \setlength{\tabcolsep}{2pt} \begin{tabular}{|c|c|c|c|c|c|c|c|c|} \hline \multicolumn{1}{|c|}{\multirow{2}{*}{Network}} & \multicolumn{2}{|c|}{Louvain} & \multicolumn{2}{|c|}{LP} & \multicolumn{2}{|c|}{Infomap} & \multicolumn{2}{|c|}{Walktrap} \\ \cline{2-9} & Modularity & Time & Modularity & Time & Modularity & Time & Modularity & Time \\ \hline \textit{Politicians} & 0.7211 & 0.16 & 0.6521 & 0.2 & 0.6162 & 10.09 & 0.6527 & 8.98 \\ \hline \textit{Lula} & 0.5464 & 0.15 & 0.4107 & 0.14 & 0.4676 & 8.77 & 0.4465 & 7.92 \\ \hline \textit{Bolsonaro} & 0.7993 & 0.01 & 0.746 & 0.01 & 0.7497 & 0.15 & 0.7435 & 0.02 \\ \hline \textit{LavaJato} & 0.5504 & 0.17 & 0.4247 & 0.15 & 0.4673 & 9.58 & 0.4594 & 8.89 \\ \hline \textit{1st\_Round} & 0.6771 & 1.48 & 0.6488 & 8.48 & 0.5401 & 2.98 & - & - \\ \hline \textit{2nd\_Round} & 0.7228 & 1.54 & 0.6664 & 2.52 & 0.5742 & 1.95 & - & - \\ \hline \end{tabular} \end{table} The Louvain method is the only algorithm included in Table \ref{tab:modularity} {that} aims at maximizing the modularity. Thereby, as expected, it achieved the highest modularity values for all the networks. The remaining algorithms, however, still obtained partitions with high modularity values. As previously explained, the modularity measure was selected to evaluate the quality of the partitions because there are no ground-truth communities available for these constructed networks. Therefore, we selected the Louvain method to detect communities in networks in the {remainder} of this paper {as it was} the algorithm that obtained communities with the highest modularity values in the lowest computational times. The partitions achieved by the Louvain method {for} the {\textit{1st\_Round} and \textit{2nd\_Round} networks} were chosen to be analyzed at length in this paper. To illustrate these partitions, Figures \ref{fig:stream_Elections_1st} and \ref{fig:stream_Elections_2nd} exhibit the {\textit{1st\_Round} and \textit{2nd\_Round} networks} along with the communities found. In these figures, vertices belonging to the same community have the same color. \begin{figure}[!htb] \begin{center} \subfigure[fig:indegree][{\textit{1st\_Round} network}.]{\label{fig:stream_Elections_1st}\includegraphics[width=0.44\textwidth]{stream_0710/graph_all_orig_louvain_.png}} \subfigure[fig:indegree][{\textit{2nd\_Round} network}.]{\label{fig:stream_Elections_2nd}\includegraphics[width=0.44\textwidth]{stream_2810/graph_5_orig_louvain_.png}} \caption{Communities found by the Louvain method.} \label{fig:graphs} \end{center} \end{figure} Next section presents {the} analysis performed to describe the topology and the community structure of the constructed networks. \section{Network Analysis}\label{sec:network_analysis} \citet{Tedjamulia2005} suggested {dividing} the users {of Twitter networks} into categories according to their popularity {and} activity. In this paper, {we have} divided the users into 8 sets (categories) {according} to their popularity -- number of mentions and retweets received {by the user} -- and activity -- number of mentions and retweets {made} by {the} user. The categories related to the popularity are called $PC1$, $PC2$, $PC3$ and $PCR$, whereas those regarding activity are $AC1$, $AC2$, $AC3$ and $ACR$. $PC1$ and $AC1$ contain the $0.1\%$ most popular and the $0.1\%$ most active users, respectively; $PC2$ and $AC2$ comprise the $1\%$ most popular users {not} in $PC1$ and the $1\%$ most active users {$AC1$}, respectively; $PC3$ and $AC3$ have the $10\%$ most popular users that are neither in $PC1$ {nor in} $PC2$ and the $10\%$ most active users that are neither in $AC1$ {nor in} $AC2$; and $PCR$ and $ACR$ {comprise} as the $90\%$ least popular and the $90\%$ least {active users,} respectively. According to these sets of users, the $1\%$ most popular and active users are those from $PC1\cup PC2$ and $AC1\cup AC2${, respectively}. The $10\%$ most popular and active users are those that belong to $PC1\cup PC2\cup PC3$ and $AC1\cup AC2 \cup AC3${, respectively}. Now, consider the division of tweets into sets (categories) according to their popularity regarding only the number of retweets they received: $TC1, TC2, TC3$ and $TCR$ are the categories of tweets {and are respectively ranked as the} $0.1\%$ most popular {tweets}, $1\%$ most popular tweets {not} in $TC1$, $10\%$ most popular tweets {not in} $TC1$ nor in $TC2$ and $90\%$ least popular tweets. The following sections show the analysis of the constructed networks with respect to the popularity and activity of their {users, tweets and communities. Moreover, they also show the evolution of the topologies of the networks along time.} The classification of users into communities and the spread of viral tweets is also discussed. In particular, the results of the largest network \textit{1st\_Round} are further investigated. \subsection{Users' Popularity and Activity} This section {presents} the analysis of the proposed networks with respect to {the distribution of their degrees in order to} describe the popularity and activity of the users {and} their influence on the constructed networks. {The section investigates the {\textit{1st\_Round}} network more thoroughly} whereas the other networks are loosely discussed. The popularity of a user is measured by the total number of mentions and retweets that they receive. A user's activity is defined by the number of mentions and retweets they make. According to the definition of arcs presented in Section \nameref{sec:database}, the in- and out-degrees of a vertex represent, respectively, the activity and the popularity of the user that the vertex refers to. Large social networks are usually scale-free. In particular, on Twitter-based networks, the most visible users are the nodes with the highest degrees. To analyze the topology of the constructed networks, Figures \ref{fig:indegree} and \ref{fig:outdegree} exhibit histograms with the out- and in-degree frequencies of {{\textit{1st\_Round}}}. \begin{figure}[!htb] \begin{center} \subfigure[fig:outdegree][Out-degree distribution.]{\label{fig:outdegree}\includegraphics[width=0.44\textwidth]{stream_0710/graph_all_Out-degree.pdf}} \subfigure[fig:indegree][In-degree distribution.]{\label{fig:indegree}\includegraphics[width=0.44\textwidth]{stream_0710/graph_all_In-degree.pdf}} \caption{Histograms of the out{-} and in-degree distributions of \textit{1st\_Round}.} \label{fig:degree_distr} \end{center} \end{figure} {As can be noted in} Figure \ref{fig:degree_distr}, the distribution of the node degrees follows {a} power law. The power law degree distribution of the vertices corroborates with the observation that a few users are more active or visible in social networks. \citet{Bruns2013} stated that {a} minority of users is very active or popular in a Twitter network. In the \textit{1st\_Round} network, users from $ACR, AC3, AC2$ and $AC1$ {were} responsible for, respectively, $61.08\%, 28.54\%, 8.28\%$ and $2.11\%$ of the total number of tweets. Users from $PCR, PC3, PC2$ and $PC1$ {received}, respectively, $1.88\%, 15.75\%, 29.62\%$ and $52.75\%$ of the total number of retweets. As a consequence, on the one hand the 90\% least active users ($ACR$) {were} responsible for posting most of the mentions and retweets. On the other, the top $1\%$ most popular users ($PC1 \cup PC2$) {received} most of the mentions and retweets. Also, $89.77\%$ of users from $PCR$ {were} among the $90\%$ least active users, i.e., {they belonged} to $ACR$. {A total of} $7.01\%$ of users {who} ranked between the $1\%$ {and the} $10\%$ most popular users (in $PC3$) are {also between} the $1\%$ {and} $10\%$ most active ones (in $AC3$). Only $1.18\%$ of the top $1\%$ most popular users (in $PC1 \cup PC2$) belong to the top $1\%$ most active users (in $AC1 \cup AC2$). {None of the 0.1\% most popular users, i.e. in $PC1$, is among the top 0.1\% most active users, i.e. in $AC1$.} Since users from $PC1 \cup PC2$ are responsible for $82.37\%$ of the tweets, {it is possible to conclude} that the most popular users are not necessarily the most active {ones}. This conclusion makes sense since the top $0.1\%$ most popular users are news organizations or public figures, such as, for example, politicians and journalists, who get more retweets than effectively post tweets on Twitter. The most popular users, therein, must effectively post popular tweets that receive most of the retweets and mentions. Table \ref{tab:pop_tweets_in_users} exhibits the percentage of the tweets posted by users from each popularity category. {As can be seen in the} table, the higher the popularity {of the} tweets, the higher the popularity of the users who posted them. \begin{table}[htb] \centering \caption{Percentage {of} tweets posted by users from each popularity category for network \textit{1st\_Round}.} \small \label{tab:pop_tweets_in_users} \setlength{\tabcolsep}{2pt} \begin{tabular}{cc|c|c|c|c|} \cline{3-6} & & \multicolumn{4}{|c|}{Users} \\ \cline{3-6} & & \multicolumn{1}{|c|}{$PCR$} & $PC3$ & $PC2$ & $PC1$ \\ \hline \multicolumn{1}{|c}{\multirow{4}{*}{Tweets}} & \multicolumn{1}{|c|}{$TCR$} & 0.26\% & 94.88\% & 4.34\% & 0.52\% \\\cline{2-6} \multicolumn{1}{|c}{} & \multicolumn{1}{|c|}{$TC3$} & 0\% & 27.96\% & 67.68\% & 4.37\%\\ \cline{2-6} \multicolumn{1}{|c}{} & \multicolumn{1}{|c|}{$TC2$} &0\% & 0\% & 44.16\% & 55.84\% \\ \cline{2-6} \multicolumn{1}{|c}{} & \multicolumn{1}{|c|}{$TC1$} & 0\% & 0\% & 0\% & 100\% \\ \hline \end{tabular} \end{table} Table \ref{tab:network_validation_pop_act} shows an analysis of the activity and popularity of users {in} the networks introduced in this paper. In this table, column ``Network'' identifies the network under analysis; column ``Contribution to tweets posted'' presents the percentage of mentions and retweets sent by the users from activity categories; column ``Contribution to {retweets}'' shows the percentage of mentions and retweets received by the users from popularity categories; column ``Popular users ranked as active'' presents the percentage of users ranked into popularity categories who are also in activity categories; and column ``Popular tweets posted by users'' presents the percentage of the 90\% least and 10\% most popular tweets posted by the 90\% and 10\% most popular users, respectively. \begin{table}[!h] \centering \scriptsize \caption{Analysis of popularity and activity of users {in} the proposed networks.} \label{tab:network_validation_pop_act} \setlength{\tabcolsep}{0.75pt} \begin{tabular}{|c||c|c|c|c||c|c|c|c||c|c|c||c|c|} \hline \multirow{5}{*}{Network} & \multicolumn{4}{|c||}{\multirow{1}{*}{Contribution to}} & \multicolumn{4}{|c||}{\multirow{1}{*}{Contribution to}} & \multicolumn{3}{|c||}{\multirow{1}{*}{Popular users}} & \multicolumn{2}{|c|}{\multirow{1}{*}{Popular tweets}} \\ % & \multicolumn{4}{|c||}{tweets posted} & \multicolumn{4}{|c||}{retweets or mentions} & \multicolumn{3}{|c||}{ranked as actives} & \multicolumn{2}{|c|}{posted by users} \\ \cline{2-14} % &\multicolumn{1}{|c|}{\multirow{3}{*}{$ACR$}} & \multicolumn{1}{|c|}{\multirow{3}{*}{$AC3$}} & \multicolumn{1}{|c|}{\multirow{3}{*}{$AC2$}}& \multicolumn{1}{|c||}{\multirow{3}{*}{$AC1$}} &\multicolumn{1}{|c|}{\multirow{3}{*}{$PCR$}} & \multicolumn{1}{|c|}{\multirow{3}{*}{$PC3$}} & \multicolumn{1}{|c|}{\multirow{3}{*}{$PC2$}}& \multicolumn{1}{|c||}{\multirow{3}{*}{$PC1$}} & \multicolumn{1}{|c|}{$ACR$} & \multicolumn{1}{|c|}{$AC3$} & \multicolumn{1}{|c||}{$AC1\cup AC2$} & \multicolumn{1}{|c|}{$PCR$} & \multicolumn{1}{|c|}{$PC1\cup PC2\cup$ } \\ & & & & & & & & & in & in & in & in & $PC3$ in $TC1 \cup $\\ % & & & & & & & & & $PCR$ & $PC3$ & $PC1 \cup PC2$ & $TCR$ & $TC2 \cup TC3$ \\ \hline \textit{Politicians} & 53.24\% & 30.66\% & 11.03\% & 5.07\% & 5.11\% & 29.15\% & 36.88\% & 28.87\% & 91.04\% & 15.08\% & 5.56\% & 44.59\% & 100\% \\ \hline \textit{Lula} & 44.73\% & 35.61\% & 14.05\% & 5.62\% & 2.91\% & 25.86\% & 39.14\% & 32.09\% & 91.11\% & 15.03\% & 5.97\% & 90.34\% & 9.63\% \\ \hline \textit{Bolsonaro} & 58.65\% & 29.89\% & 6.8\% & 4.65\% & 22.37\% & 34.37\% & 18.62\% & 24.64\% & 89.94\% & 5.13\% & 10\% & 85.62\% & 16.67\% \\ \hline \textit{LavaJato} & 44.63\% & 35.76\% & 13.99\% & 5.61\% & 3.2\% & 26.86\% & 38.54\% & 31.39\% & 91.11\% & 15.23\% & 7.04\% & 91.29\% & 11.58\% \\ \hline {\textit{1st\_Round}} & 61.08\% & 28.54\% & 8.28\% & 2.11\% & 1.88\% & 15.75\% & 29.62\% & 52.75\% & 89.77\% & 7.01\% & 1.18\% & 27.09\% & 100\% \\ \hline {\textit{2nd\_Round}} & 61.53\% & 28.03\% & 8.31\% & 2.14\% & 0.87\% & 17.61\% & 35.43\% & 46.09\% & 89.5\% & 4.73\% & 1.39\% & 14.49\% & 100\% \\ \hline \end{tabular} \label{tab:my_label} \end{table} The values in Table \ref{tab:network_validation_pop_act} corroborate with the findings on network \textit{1st\_Round}: the 90\% least active users ($PCR$) are responsible for posting most of the mentions and retweets; the top $1\%$ most popular users receive most of the mentions and retweets; the top $1\%$ most popular users are mostly not ranked in the top $1\%$ most {active}; and less than $11\%$ of the $1\%$ to $10\%$ most {popular users} ($PC3$) are also ranked as the $1\%$ to $10\%$ most {active users} ($AC3$). However, for all the networks but \textit{Politicians}, \textit{1st\_Round} and \textit{2nd\_Round}, the percentage of the top $10\%$ most popular users ($PC1 \cup PC2 \cup PC3$) who posted the top $10\%$ most popular tweets ($TC1\cup TC2 \cup TC3$) {ranged} from $9.28\%$ to $16.67\%$. According to this result, the tweets that {received} most of the retweets were not necessarily posted by the most popular users{. The} users' popularity might {therefore be} due to: (i) retweets received from a plethora of tweets; or (ii) mentions received from other users. In the next section, {like} \citet{Sluban2015}, {we shall} analyze the influence of the most popular users on the communities. \subsection{Influence of the Most Popular Users and Tweets} The popularity of a community is defined by the sum of the popularity of its users, that is, the total out-degree of the vertices that belong to the community. Figure \ref{fig:stream_part_comm_number} presents the percentage of users from each popularity category {in} the communities of network \textit{1st\_Round}{. Each community is described on} the x-axis {according to} their size. Figure \ref{fig:stream_part_comm_pop} shows the contribution of the users from each popularity category{, in percentage,} to the total popularity of the communities found by Louvain in network \textit{1st\_Round}. {Again, t}he x-axis {indicates} the size of the communities, which is the number of vertices in a community. \begin{center} \begin{figure}[!htb] \includegraphics[width=1\textwidth]{stream_0710/graph_all_orig_louvain_barplot_comm_number.pdf}\caption{{Percentage of users in the communities found by Louvain method {in} network \textit{1st\_Round}.}}\label{fig:stream_part_comm_number} \end{figure} \end{center} \begin{center} \begin{figure}[!htb] \includegraphics[width=1\textwidth]{stream_0710/graph_all_orig_louvain_barplot_comm_pop.pdf}\caption{{Contribution of each popularity category, in percentage, to the popularity of the communities found by Louvain method in network \textit{1st\_Round}.}}\label{fig:stream_part_comm_pop} \end{figure} \end{center} Although in smaller number, the top $0.1\%$ most popular users ($PC1$) are responsible {for} the majority of the community's popularity for most of the communities with more than 28 vertices. Users from $PC2$ {have also significantly contributed} to the {popularity of the communities.} As expected, although the $90\%$ least popular users ($PCR$) are the majority of users in the communities, they do not contribute to the popularity of the communities. The social influence on a community is the percentage of the retweets or mentions its users receive {made by} users {from} other communities \citep{Sluban2015}. Figures \ref{fig:stream_part_comm_influence} and \ref{fig:stream_part_comm_influence_tweets} summarize the influence exerted by, respectively, users and tweets from each popularity category {in} the communities. \begin{center} \begin{figure}[!htb] \begin{minipage}[t]{0.49\textwidth} \includegraphics[width=1\textwidth]{stream_0710/graph_all_orig_louvain_boxplot_comm_user_influence.pdf} \caption{Influence exerted by users {of} the communities {in} network \textit{1st\_Round}.} \label{fig:stream_part_comm_influence} \end{minipage} \quad \begin{minipage}[t]{0.49\textwidth} \includegraphics[width=1\textwidth]{stream_0710/graph_all_orig_louvain_boxplot_comm_tweet_influence.pdf}\caption{Influence exerted by tweets {of} the communities {in} network \textit{1st\_Round}.}\label{fig:stream_part_comm_influence_tweets} \end{minipage} \end{figure} \end{center} The $90\%$ least popular users have an average influence very close to $0$, {meaning that most of the retweets and mentions they receive are made by users within} their community. Users from $PC2$ and $PC1$ have higher social influence on their communities than $PC3$. A similar conclusion can be drawn on the influence of the most retweeted tweets on communities. The social influence concerning tweets from $TC3$, $TC2$ and $TC1$ are substantially higher than of users from $TCR$, which suggests that the $10\%$ most retweeted tweets are indeed good candidates to be viral tweets. We classify a tweet as viral if its virality is greater than the threshold $0.25$, that is, at least $25\%$ of the retweet it receives is from communities other than the one it {originated from}. Figure \ref{fig:comm_viral_Elections_1st} exhibits the percentage of viral tweets in the communities of network \textit{1st\_Round} regarding each tweet popularity category. According to this figure, the higher the popularity of the tweets, the higher {their} chance {of} being viral. In particular, all of the $0.1\%$ most popular tweets ($TC1$) are viral. \begin{figure}[!htb] \begin{center} \includegraphics[width=0.49\textwidth]{stream_0710/graph_all_orig_louvain_boxplot_comm_viral.pdf} \caption{Percentage of viral tweets in the communities of network \textit{1st\_Round}.} \label{fig:comm_viral_Elections_1st} \end{center} \end{figure} Table \ref{tab:validation_community} presents a brief analysis of the communities found by the Louvain method {in the} networks introduced in this paper. In this table, columns ``Number of users in communities (\%)'' and ``Popularity of users in communities (\%)'' exhibit the percentage of users from each popularity category and their popularity, respectively, {in} the communities. Column ``Viral tweets'' shows the percentage of the $10\%$ most popular tweets {that} are viral. {The columns} marked as ``avg'' and ``std'' exhibit, respectively, the average and standard deviations of the aforementioned values. \begin{table}[htb] \centering \scriptsize \caption{Analysis of the communities found by Louvain for the constructed networks.} \label{tab:validation_community} \setlength{\tabcolsep}{1pt} \begin{tabular}{|c||c|c|c|c|c|c|c|c||c|c|c|c|c|c|c|c||c|c||c|c|} \hline \multicolumn{1}{|c||}{\multirow{3}{*}{Network}} & \multicolumn{8}{|c||}{Number of users in communities (\%)} & \multicolumn{8}{|c||}{Popularity of users in communities (\%)} & \multicolumn{2}{|c||}{Viral} & \multicolumn{2}{|c|}{Virality of}\\ \cline{2-17} & \multicolumn{2}{|c|}{$PCR$} & \multicolumn{2}{|c|}{$PC3$} & \multicolumn{2}{|c|}{$PC2$} & \multicolumn{2}{|c||}{$PC1$} & \multicolumn{2}{|c|}{$PCR$} & \multicolumn{2}{|c|}{$PC3$} & \multicolumn{2}{|c|}{$PC2$} & \multicolumn{2}{|c||}{$PC1$} & \multicolumn{2}{|c||}{ tweets (\%)} & \multicolumn{2}{|c|}{ tweets (\%)} \\ \cline{2-21} & avg & std & avg & std & avg & std & avg & std & avg & std & avg & std & avg & std & avg & std & avg & std & avg & std \\ \hline \textit{Politicians} & 88.85 & 15.46 & 10.75 & 15.39 & 0.38 & 1.09 & 0.02 & 0.07 &42.4 & 46.81 & 65.29 & 35.43 & 56.93 & 27.27 & 55.85 & 27.32 & 32.78 & 31.41 & 10.14 & 10.78 \\ \hline \textit{Lula} & 78.62 & 18.1 & 20.95 & 18.27 & 0.41 & 0.72 & 0.03 & 0.07 &11.6 & 22.96 & 65.69 & 34.08 & 53.07 & 24.22 & 54.05 & 29.54 & 100 & 0 & 91.11 & 11.36 \\ \hline \textit{Bolsonaro} & 87.58 & 9.16 & 11.67 & 9.7 & 0.64 & 1.12 & 0.11 & 0.37 & 31.45 & 19.94 & 49.03 & 25.99 & 62.2 & 26.66 & 75.37 & 16.26 & 97.44 & 9.25 & 87.35 & 19.01 \\ \hline \textit{LavaJato} & 80.2 & 14.16 & 19.45 & 14.31 & 0.33 & 0.68 & 0.02 & 0.07 & 17.77 & 29.22 & 67.76 & 32.26 & 50.2 & 25.04 & 51.54 & 31.1 & 100 & 0 & 92.55 & 9.36 \\ \hline {\textit{1st\_Round}} & 71.47 & 17.31 & 28.1 & 17.63 & 0.4 & 0.76 & 0.03 & 0.05 & 0 & 0 & 70.43 & 37.59 & 36.07 & 22.88 & 58.56 & 13.1 & 55.54 & 40.09 & 4.6 & 6.33 \\ \hline {\textit{2nd\_Round}} & 74.72 & 15.6 & 24.91 & 15.93 & 0.34 & 0.66 & 0.03 & 0.05 & 0 & 0 & 72.7 & 37.87 & 41.14 & 25.69 & 56.4 & 21.42 & 47.24 & 41.86 & 7.99 & 9.98 \\ \hline \end{tabular} \end{table} On the one hand, the results of ``Number of users in communities (\%)'' and ``Popularity of users in communities (\%)'' presented in Table \ref{tab:validation_community} confirm the preceding analysis of network \textit{1st\_Round}: the most popular users are responsible for most of the popularity of the communities. On the other hand, all or almost all the $10\%$ most popular tweets are viral on the remaining networks. {Except for the} \textit{Politicians}, \textit{1st\_Round} and \textit{2nd\_Round} {networks, tweets had} viralities higher than $83.75\%$. The average virality of tweets from \textit{Politicians}, \textit{1st\_Round} and \textit{2nd\_Round} networks, on the other hand, {were} lower than $10.14\%$. Next section {presents} an analysis {of} the growing patterns {in} network \textit{1st\_Round}. \subsection{Temporal Analysis of \textit{1st\_Round} Network}\label{subsec:temporalanalysis} To understand how the popularity and activity of users from network \textit{1st\_Round} evolves along time, we took snapshots of the {network} at every 5000 tweets. Each snapshot represents the network constructed from the tweets posted up to that time. Figure \ref{fig:temporal_outdegree} presents the average out-degree, that is, the number of retweets received from users from each popularity set with regard to the snapshots. Figure \ref{fig:temporal_indegree} presents the average in-degree, that is, the number of mentions and retweets made by users from each activity set with regard to the snapshots. \begin{center} \begin{figure}[!htb] \begin{minipage}[t]{0.49\textwidth} \includegraphics[width=1\textwidth]{plots/temporal_outdegree.eps} \caption{Average out-degree of users {in} popularity categories along time windows.} \label{fig:temporal_outdegree} \end{minipage} \quad \begin{minipage}[t]{0.49\textwidth} \includegraphics[width=1\textwidth]{plots/temporal_indegree.eps}\caption{Average in-degree of users {in} activity categories along time windows.}\label{fig:temporal_indegree} \end{minipage} \end{figure} \end{center} The top $0.1\%$ most popular users ($PC1$) received an increasing number of retweets along time, as shown by their augmenting average out-degree. This observation corroborates with the remark that new vertices are more likely to connect with the existing vertices with the highest degrees in scale-free networks. Figure \ref{fig:politiciansevolution} presents the evolution of network \textit{1st\_Round} along time. In each snapshot, the following are considered: the total number of communities in the network obtained by the Louvain method, the average community size, the total number of arcs and nodes, the number of new tweets and the total number of different tweets in the network. As shown in Table \ref{tab:network_network}, the network \textit{1st\_Round} has 135865 nodes and 242679 arcs. It is possible to notice in Figure \ref{fig:politiciansevolution} that the number of new tweets that appear in the network at each snapshot is {nearly} constant. However, at snapshot 48, the number of new tweets drops significantly and {then immediately starts to raise again.} \begin{figure}[!htb] \begin{center} \includegraphics[height=0.5\columnwidth]{plots/temporal.eps} \caption{Evolution of network \textit{Politicians} over time.} \label{fig:politiciansevolution} \end{center} \end{figure} On average, 15\% of the new arcs that appear in the network in a given snapshot represent retweets and mentions of new tweets. The other 85\% of the new arcs represent new retweets and mentions of tweets {already} in the network in previous snapshots. The number of arcs created from a tweet decreases rapidly over time. In Figure \ref{fig:temporal_outdegree} it is possible to note {that the} popularity of users from ${PC1}$ {ceases} to increase just in snapshot 48, where the number of new tweets is smaller. \begin{figure}[!htb] \begin{center} \includegraphics[height=0.5\columnwidth]{plots/interval.eps} \caption{Duration of each snapshot in seconds.} \label{fig:snapshotduration} \end{center} \end{figure} Figure \ref{fig:snapshotduration} shows the duration (in seconds) of each snapshot. The average duration of each snapshot was 108 seconds, which means that 5000 tweets were collected at every 108 seconds. The average duration of snapshots before and after snapshot 48 was, respectively, 110 and 104 seconds. {S}napshot 48 was collected {upon} the {disclosure} of the results of the first round {of the} elections {at} 19:00:00 (Brasília Time (BRT)), while snapshot {49} was collected from 19:00:38 to 19:02:23 (Brasília Time (BRT)). On the one hand, the average duration of the snapshots obtained after the release of the first {round of} results decreased. That is, the 5000 tweets collected in each snapshot were obtained in a shorter time window, which meant that Twitter users were more active. On the other hand, the number of new tweets {appearing} in snapshot 49 is smaller than in previous snapshots. This possibly means that, during the {disclosure} {of the} election results, users {created} fewer new tweets and interacted more with {previously posted tweets}. However, the rate of new tweets soars after snapshot 48, whose content was probably about the released results. \section{Context and Sentiment {of the} Communities {in Relation} to the Elections} \label{sec:community_classification} The output of a community detection algorithm provides a straightforward classification of users into communities. Tweets can be classified according to the communities of the users who posted them. In this section the context of the communities and {their} sentiments {in relation} to the words {in} the tweets {of} networks \textit{1st\_Round} and \textit{2nd\_Round} are studied. Prior to the sentiment analysis, we first selected the words which were used at least 10 {times in the communities with a minimum of 1000 vertices}. Then, we translated all the words {into} English. Finally, we employed the R library \textit{sentimentr} \citep{sentimentr} to analyse the sentiment {related} {to} the selected words in each community. Each word is associated with a score in the range [-1,1], where -1 and 1 indicate the most negative and positive sentiments, respectively. Figures \ref{fig:stream_wordCloud_Elections1} and \ref{fig:stream_wordCloud_Elections2} illustrate word clouds with the most frequent words in the tweets from networks \textit{1st\_Round} and \textit{2nd\_Round}. The word cloud {in} Figure \ref{fig:stream_wordCloud_Elections1} shows that the names of {the} {three most} voted candidates in the first round of the elections were {also amongst} the most used words. This word cloud also shows the words ``segundo'' and ``turno'', which mean ``second'' and ``round'' in English, respectively, {suggesting} interest in the second round during the first round of the elections. The word cloud {in} Figure \ref{fig:stream_wordCloud_Elections2} shows the name of the two candidates who ran {in} the second round of the elections. \begin{figure}[!htb] \begin{center} \subfigure[fig][Word Cloud for network \textit{1st\_Round}.]{\label{fig:stream_wordCloud_Elections1}\includegraphics[width=0.49\textwidth]{stream_0710/all_wordcloud.png}} \subfigure[fig][Word Cloud for network \textit{2nd\_Round}.]{\label{fig:stream_wordCloud_Elections2}\includegraphics[width=0.49\textwidth]{stream_2810/all_wordcloud.png}} \caption{Word clouds with the most frequent words.} \label{fig:word_clouds} \end{center} \end{figure} Figures \ref{fig:stream_scatterPlot_Elections1} and \ref{fig:stream_scatterPlot_Elections2} show the sentiment of the most common words in the tweets from networks \textit{1st\_Round} and \textit{2nd\_Round}. {The} x-axis {in the figures presents} the size of the communities, i.e., their number of vertices. The y-axis shows the sentiment of the words. The center of the circumferences indicates the sentiment of the words whereas their diameter indicates the frequency {of} the data collected: higher diameters {indicate words used more often}. These figures show that the sentiment and frequencies of the words in the data collected regarding the first and second rounds of the elections are similar. The higher the size of the community, the higher the frequency of the words. Moreover, although the number of words associated with negative and positive sentiments is similar, the words associated with positive sentiments appear more often. \begin{figure}[!htb] \begin{center} \subfigure[fig][Network \textit{1st\_Round}.]{\label{fig:stream_scatterPlot_Elections1}\includegraphics[width=0.49\textwidth]{stream_0710/Elections_1st_scatter_plot_comm_size_vs_sentiment_louvain_P.png}} \subfigure[fig][Network \textit{2nd\_Round}.]{\label{fig:stream_scatterPlot_Elections2}\includegraphics[width=0.49\textwidth]{stream_2810/Elections_2st_scatter_plot_comm_size_vs_sentiment_louvain_P.png}} \caption{Sentiments associated with the most common words on the communities.} \label{fig:scatterPlot_sentiment} \end{center} \end{figure} Based on the observation that the words associated with positive sentiments are more frequent, the sentiment of the words that appear more times in the tweets should {weigh more} in a general sentiment score. Thereby, we calculate the average sentiment score of each community as the sum of the {sentiments} associated with each word multiplied by its frequency in the community. Figures \ref{fig:stream_sentiment_Elections1} and \ref{fig:stream_sentiment_Elections2} present the average sentiment score of the communities with at least 1000 vertices. In these {figures}, the vertices belonging to the community found using the Louvain method are collapsed into supernodes and the edges between them represent the existence of arcs between its vertices. The larger the size of a supernode, the higher the number of vertices in the community. Similarly, the thickness of the edges {is} proportional to the amount of arcs between the communities. Additionally, for the 7 largest communities, these figures also show the three negative and positive words associated with {the highest} and lowest scores, respectively. The word in Portuguese is presented {next to} {a} green or red square {whose color intensity is} proportional to the sentiment score and the number of times the word {was} used in the community. \begin{figure}[!htb] \begin{center} \includegraphics[width=0.90\textwidth]{stream_0710/1turno-min.png} \caption{Average sentiment score and words associated with the highest positive and negative scores in communities considering network \textit{1st\_Round}.} \label{fig:stream_sentiment_Elections1} \end{center} \end{figure} \begin{figure}[!htb] \begin{center} \includegraphics[width=0.99\textwidth]{stream_2810/2turno-min.png} \caption{Average sentiment score and words associated with the highest positive and negative scores in communities considering network \textit{2nd\_Round}.} \label{fig:stream_sentiment_Elections2} \end{center} \end{figure} The scores presented in Figures \ref{fig:stream_sentiment_Elections1} and \ref{fig:stream_sentiment_Elections2} show that, on average, the sentiment associated with the words in the communities was positive. However, this result is due to the higher frequency of positive words. These words are also amongst the most frequent words exhibited in the word clouds of Figures \ref{fig:stream_wordCloud_Elections1} and \ref{fig:stream_wordCloud_Elections2}. Moreover, the words associated with the highest scores are the same in all the communities in both Figures \ref{fig:stream_sentiment_Elections1} and \ref{fig:stream_sentiment_Elections2}. These words occur in tweets classified as $TC1$, i.e, {the} $0.1\%$ most popular tweets, which according to Figure \ref{fig:comm_viral_Elections_1st}, are viral tweets. This observation corroborates with \citet{Wang2013}, who state that viral tweets spread across the communities. \section{Final Remarks and Future Works}\label{sec:conclusion} This paper {presents a thorough analysis of} the structure and topology of networks constructed from political discussions on Twitter and, in particular, {discusses} networks composed by tweets expressing reactions to the 2018 Brazilian presidential elections. These networks are scale-free and {a} minority of their users are responsible for receiving {most} ``retweets'' and ``mentions'', while effectively posting few tweets. The evolution of the networks {along} time showed that new users are more likely to interact with the most popular users. We {verified} that the study {by} \citet{Weng2013} on the spreading patterns of hashtags {was} valid for the spreading of retweets on a political network regarding the 2018 Brazilian presidential elections: {most tweets were retweeted by users from within} the community of the user who originally posted the tweet but the minority of tweets is {retweeted} from several different communities and spread like viruses. The most popular users, although in smaller number, dictate the popularity of the communities and the higher their popularity, the greater their influence on other communities. These users are also responsible for posting viral tweets. Moreover, we studied the sentiment related to the most frequent words in the tweets with content about the 2018 Brazilian presidential elections and discovered that, overall, words associated with positive sentiments are predominant. The words that contribute most to the positive sentiment of the communities are the same and appear in viral tweets. As a future application of this work, we intend to further investigate and classify tweets from larger databases, in particular, reactions to the 2018 Truckers' Strike and to the 2018 World Cup. To deal with the large scale networks, we plan to design distributed algorithms. In addition, the study of the evolution of the networks with respect to spreading patterns of the tweets might help us to understand how communities are formed and the proliferation of tweets along time. Finally, the observation that viral tweets do not affect the community structure of the networks and that non-viral tweets {get} trapped within the communities could be explored through community detection algorithms in order to provide better communities. \section*{Acknowledgments} The authors would like to acknowledge the financial support provided by São Paulo Research Foundation (FAPESP): Grant Numbers 2016/22688-2; 2017/24185-0 and 2015/21660-4; Conselho Nacional de Desenvolvimento Científico e Tecnológico (CNPq): Grant Number 306036/2018-5; and Coordenação de Aperfeiçoamento de Pessoal de Nível Superior - Brasil (CAPES) - Finance Code 001. The authors are grateful to Professor Ana Carolina Lorena (Instituto Tecnológico de Aeronáutica) for providing a thoughtful review of the first draft of this paper. The last author would also like to thank Leonardo V. Rosset for giving her a hand.
{'timestamp': '2019-06-17T02:18:12', 'yymm': '1906', 'arxiv_id': '1906.06315', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06315'}
arxiv
\section{Introduction} An independence system consists of a ground set $E=\{1,\ldots,n\}$ and a family $\ensuremath{\mathcal I}$ of subsets of $E$. The pair $(E, \ensuremath{\mathcal I})$ is a called an independence system if $\emptyset \in \ensuremath{\mathcal I}$ and for all $B \subseteq A \in \ensuremath{\mathcal I}$ we have $B \in \ensuremath{\mathcal I}$ as well. Elements of $\ensuremath{\mathcal I}$ are called independent. For any $A \subseteq E$, a set $B \subseteq A $ is called a basis of $A$ if $B \in \ensuremath{\mathcal I}$ and $B \cup \{j\} \not \in \ensuremath{\mathcal I}$ for all $j \in A \setminus B$. For $A\subseteq E$ denote by $ \ensuremath{\mathcal B}_\ensuremath{\mathcal I}(A)$ (or $\ensuremath{\mathcal B}(A)$ when no ambiguity) the set of bases of $A$ (with respect to $\ensuremath{\mathcal I}$). The bases with respect to $E$ are denoted by $\ensuremath{\mathcal B}_\ensuremath{\mathcal I}$ or just $\ensuremath{\mathcal B}$. Minimally dependent sets are called circuits. If we associate weights $v_i\in {\mathbb R}_+$ for each $i\in E$, the problem of finding a maximum weight basis of $(E, \ensuremath{\mathcal I})$ can be expressed as $\max_{A \in \ensuremath{\mathcal B}}\sum_{i \in A}v_i$. For convenience we will write $\sum_{i \in S}v_i$ as $v(S)$ for all $S \subseteq E$. The problem is NP-hard by reduction to Hamiltonian path in a directed graph \citep{korte-hausmann-1978}. Call an independence systems $(E,\ensuremath{\mathcal I})$ with $\{i\}\in\ensuremath{\mathcal I}$ for all $i\in E$ \emph{normal} (for graphs or matroids, the term \emph{loopless} is more prevalent). A non-normal independence system can be turned into a normal one by deleting the elements $e\in E$ with $\{e\}\notin\ensuremath{\mathcal I}$ without changing the solution to the problem of finding a maximum weight basis. % \citet{milgrom-2017} proposed a heuristic for determining a maximum weight basis of an independence system $\ensuremath{\mathcal I}$ given that for sets from $\ensuremath{{\mathcal O}}\subseteq \ensuremath{\mathcal I}$ we care in particular about the qualitiy of approximation as we assume, that $\ensuremath{{\mathcal O}}$ contains (frequently) the optimal basis. It is based on finding an `inner matroid', one contained in the independence system. We compare the worst-case performance of this heuristic with the well known greedy algorithm for the same problem. We show that the worst-case performance of this new heuristic without additional assumptions on $\ensuremath{{\mathcal O}}$ being different from $\ensuremath{\mathcal I}$ is no better than that of the classical greedy algorithm. Nevertheless, as we show by example, there are aspects of Milgrom's proposal that bear further investigation. We defer a discussion of these matters till the end. In the next section we describe the greedy algorithm and state its worst case performance. \section{Greedy Algorithm} We describe the greedy algorithm for finding a basis of $E$ with possibly large weight. \begin{algorithm}[H] \caption{Greedy Algorithm \label{alg:GI} } \SetKwInput{KwIn}{Given} \SetKwInput{KwOut}{Goal} \SetAlgoNoLine\LinesNumbered \KwIn{An independence system $(E, \ensuremath{\mathcal I})$ represented by an independence oracle. Weights $v_i\in {\mathbb R}_+$ for all $i\in E$. % } \KwOut{An independent set $I_g \in \ensuremath{\mathcal I}$\ of ``large'' value.} Order the elements of $E$ by non-increasing value $v_1 \geq v_2 \geq \ldots \geq v_n\geq 0$ \label{lGI-1}\; Set $I \ensuremath{\leftarrow} \emptyset$\; \For{$i\ensuremath{\leftarrow} 1$ \KwTo $n$}{ % \lIf{ $I\cup \{i\}$ independent (oracle call)}{ $I \ensuremath{\leftarrow} I\cup \{i\}$\label{lGI-5}} } Let $I_g \ensuremath{\leftarrow} I$ and return $I_g$. \end{algorithm} \begin{rem} If some coefficients in the objective function are equal, the order of the $v_i$'s is not unique and therefore the algorithm's outcome is not necessarily unique. To avoid this assume an exogenously given tie breaking rule, so that the outcome of the greedy algorithm is unique. \end{rem} A worst case bound on the quality of the greedy solution in terms of the rank quotient of an independence system can be found in \citet{jenkyns-1976, korte-hausmann-1978}. \begin{deff} Let $(E,\ensuremath{\mathcal I})$ be an independence system. The \emph{rank} of $F \subseteq E$ is defined by % \begin{align*} r(F) \mathrel{\raise.095ex\hbox{:}\mkern-4.2mu=} \max \{|B| \, : \, B \text{ basis of } F\}. \end{align*} The rank-function maps $2^E$ into the nonnegative integers. Similarly, for $F\subseteq E$ we define \[ l(F) \mathrel{\raise.095ex\hbox{:}\mkern-4.2mu=} \min \{|B| \colon B \text{ basis of } F\}\] to be the \emph{lower rank} of $F$. The \emph{rank quotient} of $\ensuremath{\mathcal I}$ is denoted by \[ q(\ensuremath{\mathcal I}) \mathrel{\raise.095ex\hbox{:}\mkern-4.2mu=} \min_{F\subseteq E, r(F) > 0}\, \frac{l (F)}{r(F)}. \] \end{deff} Following an axiomatization of matroids by \citet{hausmann-korte-jenkyns-1980}, we define a matroid to be an independences system $(E,\ensuremath{\mathcal I})$ with $q(\ensuremath{\mathcal I}) = 1$. For matroids there are several equivalent characterizations known, some of which we will use later: \begin{description} \item[Basis exchange:] For every pair of bases $B^1,B^2\in\ensuremath{\mathcal B}$ and $i\in B^2\setminus B^1$ there exists a $j\in B^1\setminus B^2$ such that $(B^1\cup \{i\})\setminus \{j\}$ is again a basis. \item[Augmentation property:] For every pair of independent sets $I,J\in\ensuremath{\mathcal I}$ with $|I|<|J|$ there exists $j\in J\setminus I$ such that $I\cup\{j\}$ is again independent. \item[Rank axioms:] see~\eqref{R1}-\eqref{R3} on page~\pageref{R1}. \end{description} For proofs on these and more see \citet{oxley-b1992}. If $(E, \ensuremath{\mathcal I})$ is a normal independence system, then, \[q(\ensuremath{\mathcal I})\in\left\{\frac{i}{j}\mid 1\leq i,j\leq r(\ensuremath{\mathcal I})\right\}.\] Hence for normal independence systems, $q(\ensuremath{\mathcal I})\geq 1/r(\ensuremath{\mathcal I}).$ However, a better bound is known: \begin{thm}[\citealp{hausmann-korte-jenkyns-1980}]\label{thm:hkj} Let $(E,\ensuremath{\mathcal I})$ be an independence system. If, for any $A\in\ensuremath{\mathcal I}$ and $e\in E$ the set $A\cup\{e\}$ contains at most $p$ circuits, then $q(\ensuremath{\mathcal I})\geq 1/p$. If an independence system $\ensuremath{\mathcal I}$ is the intersection of $p$ matroids, then $q(\ensuremath{\mathcal I})\geq 1/p$. \end{thm} \begin{thm}[\citealp{jenkyns-1976,korte-hausmann-1978}] \label{satz:5.18} For an independence system $\ensuremath{\mathcal I}$ on $E$ with objective function $v\gneqq \ensuremath{\mathbf 0}\xspace$, let $I_g$ be the solution returned by Algorithm~\eqref{alg:GI} and $I_o$ be a maximum weight basis. Then, \[ q(\ensuremath{\mathcal I}) \leq \frac{v(I_g)}{v(I_o)} \leq 1. \] Also, for every independence system there are weights $v \in \{0,1\}^E$, such that the first inequality holds with equality. \end{thm} The only attempt to improve upon this bound we are aware of involves incorporating a partial enumeration stage into the greedy algorithm see~\citet{hausmann-korte-jenkyns-1980}. \section{Inner Matroid} \citet{milgrom-2017} proposes an alternative to direct application of the greedy algorithm. It has two parts. The first is the introduction of \emph{a-priori} information on where the optimal basis may lie. Formally, let $\ensuremath{{\mathcal O}}\subseteq \ensuremath{\mathcal I}$ be a collection of independent sets one of which is conjectured to be an optimal weight basis. $\ensuremath{{\mathcal O}}$ need not satisfy the hereditary property (so $J\subset I\in \ensuremath{{\mathcal O}}$ does not imply $J\in \ensuremath{{\mathcal O}}$) and may exclude a basis that is in fact optimal (see Example~\ref{ex:stab}). Call $\ensuremath{{\mathcal O}}$ the \emph{acceptable set}. The second part finds a matroid `inside' the independence system (but not necessarily containing all of $\ensuremath{{\mathcal O}}$) and applies the greedy algorithm to find an optimal weight basis of that matroid. We describe this approach here. Given an independence system $(E, \ensuremath{\mathcal I}),$ an acceptable set $\ensuremath{{\mathcal O}}$, and a weight vector $v\in{\mathbb R}_+^E$ let \[V^*(\ensuremath{\mathcal I},v)=\max_{S\in\ensuremath{\mathcal I}}v(S) \text{ and } V^*(\ensuremath{{\mathcal O}}, v) =\max_{S\in\ensuremath{{\mathcal O}}}v(S)\] and \[V^*_g(\ensuremath{\mathcal I},v)=\text{value of the greedy solution}.\] Independence system $(E,\ensuremath{\mathcal M})$ is a matroid by previous definition involving rank quotient and Theorem~\eqref{satz:5.18} if and only if \[V^*(\ensuremath{\mathcal M},v)=V_g^*(\ensuremath{\mathcal M},v)\quad \forall v\in{\mathbb R}_+^E.\] We say that the independence system $(E,\ensuremath{\mathcal J})$ is contained in $(E,\ensuremath{\mathcal I})$, an inner independence system, if $\ensuremath{\mathcal J}\subseteq \ensuremath{\mathcal I}$. If $(E, \ensuremath{\mathcal J})$ is a matroid it is called an inner matroid. The \emph{approximation quality of $\ensuremath{\mathcal J}$ for $\ensuremath{\mathcal I}$ with respect to the acceptable set $\ensuremath{{\mathcal O}} \subseteq \ensuremath{\mathcal I}$} is given by \[\rho(\ensuremath{\mathcal I},\ensuremath{{\mathcal O}},\ensuremath{\mathcal J})\mathrel{\raise.095ex\hbox{:}\mkern-4.2mu=} \min_{S \in \ensuremath{{\mathcal O}}\setminus\{\emptyset\}}\min_{S'\in \ensuremath{\mathcal B}_\ensuremath{\mathcal J}(S)} \frac{|S'|}{|S|};\] so this picks the element from $\ensuremath{{\mathcal O}}$ that is least well approximated by a basis of $\ensuremath{\mathcal J}$. If $l_\ensuremath{\mathcal J}$ denotes the lower rank function of $(E,\ensuremath{\mathcal J})$ then \[\rho(\ensuremath{\mathcal I},\ensuremath{{\mathcal O}},\ensuremath{\mathcal J})= \min_{S \in \ensuremath{{\mathcal O}}\setminus\{\emptyset\}} \frac{l_\ensuremath{\mathcal J}(S)}{|S|}. \] If $\ensuremath{\mathcal M}$ is an inner matroid, then $r_\ensuremath{\mathcal M}=l_\ensuremath{\mathcal M}$ and \[\rho(\ensuremath{\mathcal I},\ensuremath{{\mathcal O}},\ensuremath{\mathcal M}) = \min_{S \in \ensuremath{{\mathcal O}}\setminus\{\emptyset\}} \frac{r_{\ensuremath{\mathcal M}}(S)}{|S|} =\min_{S \in \ensuremath{{\mathcal O}}\setminus\{\emptyset\}}\max_{S'\in\ensuremath{\mathcal M}:S'\subseteq S}\frac{|S'|}{|S|},\] which is the form \citet{milgrom-2017} originally chose. It is natural to ask when $\rho(\ensuremath{\mathcal I},\ensuremath{{\mathcal O}},\ensuremath{\mathcal M})=1$. \begin{thm}\label{rho1} If $(E, \ensuremath{\mathcal I})$ is a normal independence system with acceptable set $\ensuremath{{\mathcal O}}\subseteq\ensuremath{\mathcal I}$, then, there exists a matroid $\ensuremath{\mathcal M}$ with $\rho(\ensuremath{\mathcal I},\ensuremath{{\mathcal O}},\ensuremath{\mathcal M})=1$ if and only if \ensuremath{\mathcal I}\ has an inner matroid containing $\ensuremath{{\mathcal O}^\dagger}\mathrel{\raise.095ex\hbox{:}\mkern-4.2mu=} \bigcup_{F\subseteq B\in\ensuremath{{\mathcal O}}}\{F\}$. \end{thm} \begin{proof} If $(\ensuremath{\mathcal I},\ensuremath{{\mathcal O}},\ensuremath{\mathcal M})=1$ then $\ensuremath{{\mathcal O}}\subseteq \ensuremath{\mathcal M}$. For $I\subseteq J\in \ensuremath{{\mathcal O}}$ follows $J\in \ensuremath{\mathcal M}$ and by hereditary property of matroid $I\in\ensuremath{\mathcal M}.$ \end{proof} We give three examples to suggest that nothing stronger is possible. \begin{deff} Let $U^k_n$ denote the \emph{uniform matroid} of all subsets of an $n$-element set of cardinality at most $k$, where clearly $0\leq k\leq n$. If we want to specify the groundset $E$ of $n$ elements explicityly, we can also write $U^k_E.$ \end{deff} \begin{example} In all cases the ground set is $E = \{1,2,3,4\}$. \begin{itemize} \item Let $\ensuremath{\mathcal I} = \{\{1\},\{2\},\{3\},\{4\}, \{1,2\},\{3,4\}\}$. $(E, \ensuremath{\mathcal I})$ is not a matroid as the basis exchange axiom is violated. If $\ensuremath{{\mathcal O}}=\{\{1\},\{2\},\{3\},\{4\}\}$, then, $\rho(\ensuremath{\mathcal I},\ensuremath{{\mathcal O}},U^1_4)=1$. This demonstrates, that the condition ``$\ensuremath{{\mathcal O}}$ is matroid'' is too strong. However, in this case \ensuremath{{\mathcal O}^\dagger}\ \emph{is} a matroid. \item Again, let $\ensuremath{\mathcal I} = \{\{1\},\{2\},\{3\},\{4\}, \{1,2\},\{3,4\}\}$. Hence $(E, \ensuremath{\mathcal I})$ is not a matroid (again). If $\ensuremath{{\mathcal O}}=\{\{1,2\},\{3,4\}\}$, then, $\rho(\ensuremath{\mathcal I},\ensuremath{{\mathcal O}},U^1_4)=1/2$. In this case \ensuremath{{\mathcal O}^\dagger}\ is not a matroid. \item Let $\ensuremath{\mathcal I} = \{\{1\},\{2\},\{3\},\{4\},\{1,2\}, \{2,3\}, \{3,4\}, \{1,3\}, \{1,4\}, \{2, 4\}, \{1,2,3\}\}.$ $(E, \ensuremath{\mathcal I})$ is not a matroid, since $\{1,2,3\}$ and $\{3,4\}$ are bases for $E$ of different sizes. If $\ensuremath{{\mathcal O}}=\{\{2,3\},\{3,4\}\}$ the smallest inner matroid of $\ensuremath{\mathcal I}$ containing $\ensuremath{{\mathcal O}}$ is $\ensuremath{\mathcal M}=U^2_{\{2,3\}}$; and $\rho(\ensuremath{\mathcal I},\ensuremath{{\mathcal O}},\ensuremath{\mathcal M})=1.$ However $\ensuremath{{\mathcal O}^\dagger}$ is not a matroid, since it lacks the basis $\{2,4\}$ that would be required by basis exchange. So requiring ``$\ensuremath{{\mathcal O}^\dagger}$ is a matroid'' is too strong. \end{itemize} \end{example} \begin{rem} Usually, the intersection of all matroids containing $\ensuremath{{\mathcal O}^\dagger}$ is not a matroid, therefore it is unsuitable for a notion of hull.% % % % \end{rem} \begin{rem} Clearly \[\rho(\ensuremath{\mathcal I},\ensuremath{{\mathcal O}},\ensuremath{\mathcal J})\geq\rho(\ensuremath{\mathcal I},\ensuremath{{\mathcal O}^\dagger},\ensuremath{\mathcal J}),\] since the minimum on the right hand side is determined over a larger set. \end{rem} However, $\rho(\ensuremath{\mathcal I},\ensuremath{{\mathcal O}},\ensuremath{\mathcal J})>\rho(\ensuremath{\mathcal I},\ensuremath{{\mathcal O}^\dagger},\ensuremath{\mathcal J})$ is possible, as the following example demonstrates: \begin{example} Consider $E=\{1,2,3,4,5,6\}$ and the independence system $\ensuremath{\mathcal I}=2^{\{1,2,3,4\}}\cup 2^{\{3,4,5,6\}}.$ Clearly $\{1\}, \{5,6\} \in \ensuremath{\mathcal I}$. The augmentation property would require, that $\{1,5\}$ or $\{1,6\}$ has to be independent, which is not the case. Therefore \ensuremath{\mathcal I}\ is not a matroid. Let $\ensuremath{{\mathcal O}} = \{\{1,2,3,4\}, \{3,4,5,6\}\}$ be our benchmark set and let $\ensuremath{\mathcal M}=2^{\{1,2,3,4\}}$. Now, to determine $\rho(\ensuremath{\mathcal I},\ensuremath{{\mathcal O}},\ensuremath{\mathcal M}) = \min_{S \in \ensuremath{{\mathcal O}}\setminus\{\emptyset\}} \frac{r_{\ensuremath{\mathcal M}}(S)}{|S|}$ we have to consider only the two elements of $\ensuremath{{\mathcal O}}$: \begin{description} \item[$O=\{1,2,3,4\}$] is easy, since $r_\ensuremath{\mathcal M}(O)=4$; \item[$O=\{3,4,5,6\}$] is as easy, since $r_\ensuremath{\mathcal M}(O)=2$. \end{description} Together, we obtain $\rho(\ensuremath{\mathcal I},\ensuremath{{\mathcal O}},\ensuremath{\mathcal M})=\frac24=\frac12.$ Now, $\ensuremath{{\mathcal O}^\dagger}$ contains $O=\{4,5,6\}$ with $r_\ensuremath{\mathcal M}(O)=1$. Even worse $O=\{6\}\in\ensuremath{{\mathcal O}^\dagger}$ with $r_\ensuremath{\mathcal M}(O)=0$ which demonstrates $\rho(\ensuremath{\mathcal I},\ensuremath{{\mathcal O}^\dagger},\ensuremath{\mathcal M})= 0<\frac12=\rho(\ensuremath{\mathcal I},\ensuremath{{\mathcal O}},\ensuremath{\mathcal M})$. \end{example} \begin{corollary} The example demonstrates, that % $\rho(\ensuremath{\mathcal I},\ensuremath{{\mathcal O}^\dagger},\ensuremath{\mathcal M})>0$ is only possible if for all $e\in\bigcup_{O\in\ensuremath{{\mathcal O}}}O$ holds $\{e\}\in \ensuremath{\mathcal M}$ \end{corollary} \begin{example}[twin-peaks]\label{ex:twin-peaks} Consider two disjoint sets $E_1$ and $E_2$ and integers $k_1,k_2$ such that $k_1<|E_1|<k_2<|E_2|.$ Let $\ensuremath{\mathcal M}_1=U^{k_1}_{E_1}$ and $\ensuremath{\mathcal M}_2=U^{k_2}_{E_2}$. % % % % % Define $(E, \ensuremath{\mathcal I})$ to be the independence system on $E\mathrel{\raise.095ex\hbox{:}\mkern-4.2mu=} E_1\dot\cup E_2$ where a set $A \subseteq E$ is independent if and only if $A$ is an independent set in $\ensuremath{\mathcal M}_1$ \emph{or} $\ensuremath{\mathcal M}_2$, thus $\ensuremath{\mathcal I}=\ensuremath{\mathcal M}_1\cup\ensuremath{\mathcal M}_2$. Call this a `twin-peaks' indendence system. % % % % Choose an $F\subseteq E$ which consists of one element from $E_1$ and $k_2$ elements from $E_2$. Now $l(F)=1$ and $r(F)=k_2$. Since larger ratios between sets in this independence system are impossible, $q(\ensuremath{\mathcal I})=\frac1{k_2}$. To determine the best matroid approximating $\ensuremath{{\mathcal O}}=\ensuremath{\mathcal I}$ contained in \ensuremath{\mathcal I}, we must examine all matroids $\ensuremath{\mathcal M}'$ contained in $\ensuremath{\mathcal I}.$ \begin{enumerate} \item Suppose first that there exists $i\in E_1, j\in E_2$ such that $\{i\}, \{j\}\in {\ensuremath{{\mathcal M}'}}$. We show that the rank of ${\ensuremath{{\mathcal M}'}}$ is 1, i.e. the largest bases of ${\ensuremath{{\mathcal M}'}}$ are of size one. If not, there exists a set $F \in {\ensuremath{{\mathcal M}'}}$ of cardinality two. By construction of $\ensuremath{\mathcal I}$ the set $F$ must be a subset of $E_1$ or $E_2$, wlog let $F\subseteq E_1$; since $F$ and $\{j\}$ are independent sets in ${\ensuremath{{\mathcal M}'}}$ there has to be an element in $F$ with which we could augment $\{j\}$ to be an independent set $F'$ in ${\ensuremath{{\mathcal M}'}}$. But $F'$ contains elements from $E_1$ and $E_2$ and therefore is not independent in $\ensuremath{\mathcal I}$ and therefore not in ${\ensuremath{{\mathcal M}'}}.$ The largest matroid of this kind contained in \ensuremath{\mathcal I}\ is the one, where all singletons are independent. Hence every independent set from \ensuremath{\mathcal I}\ is approximated by an arbitrary contained singleton and we obtain the worst case bound of \[\frac{1}{\max(k_1,k_2)}=\frac{1}{k_2}.\] \item On the other hand, if $\rank {\ensuremath{{\mathcal M}'}}>1$ then we can conclude that either all independent sets of {\ensuremath{{\mathcal M}'}}\ are contained in $E_1$ or they are contained in $E_2$ and the inclusion-wise largest matroids contained in $E_1$ and $E_2$ are $\ensuremath{\mathcal M}_1$ and $\ensuremath{\mathcal M}_2.$ For ${\ensuremath{{\mathcal M}'}}=\ensuremath{\mathcal M}_1$ approximating sets $F\in\ensuremath{\mathcal M}_2\setminus\{\emptyset\}$ is only possible with the empty set which yields a quotient of $0/|F|$ and the same for ${\ensuremath{{\mathcal M}'}}=\ensuremath{\mathcal M}_2$ approximating sets aproximating nonempty sets $F\in\ensuremath{\mathcal M}_1\setminus\{\emptyset\}$ is only possible with the empty set which yields a quotient of $0/|F|.$ \end{enumerate} In summary we obtain the best approximation in the first case and can conclude \[\rho(\ensuremath{\mathcal I},\ensuremath{\mathcal I},{\ensuremath{{\mathcal M}'}})=\frac{1}{k_2}=q(\ensuremath{\mathcal I}).\] \textbf{However,} $\rho$ can be much better if we exploit additional knowledge. As an illustration, suppose that $\ensuremath{{\mathcal O}}= \binom{E_2}{k_2}$, i.e., all subsets of size at most $k_2$ of $E_2$. This might be justified by a situation, where we know that the optimal solutions, that occur in our environment, have to live in $E_2$, maybe since $k_1\ll k_2$. Unsurprisingly, the matroid $\ensuremath{\mathcal M}_2$ gives us the best conceivable guarantee of $1$: \[\rho\left(\ensuremath{\mathcal M},\binom{E_2}{k_2},\ensuremath{\mathcal M}_2\right )=1>\frac{1}{k_2}=q(\ensuremath{\mathcal I}).\] \end{example} \citet{milgrom-2017} proposes that the maximum weight basis of an inner matroid $\ensuremath{\mathcal M}$ be used as a solution to the problem of finding a maximum weight basis in $(E, \ensuremath{\mathcal I})$. % The objective function value of this solution will be $V^*(\ensuremath{\mathcal J},v)$. \citet{milgrom-2017} gives a bound on the quality of this solution in term of $\rho(\ensuremath{\mathcal I},\ensuremath{{\mathcal O}},\ensuremath{\mathcal J})$. \begin{deff} For a given independence system $(E,\ensuremath{\mathcal I})$ and $e\in E$ define the new independence system $\ensuremath{\mathcal I}\setminus\{e\}$ on $E\setminus \{e\}$ by $\ensuremath{\mathcal I}\setminus\{e\}\mathrel{\raise.095ex\hbox{:}\mkern-4.2mu=} \{I\in\ensuremath{\mathcal I}\colon e\notin I\}.$ \end{deff} \begin{rem} It is easy to see, that $(E\setminus\{e\},\ensuremath{\mathcal I}\setminus\{e\})$ is an independence systems again. Furthermore, if $(E,\ensuremath{\mathcal I})$ is a matroid, so is $(E\setminus\{e\},\ensuremath{\mathcal I}\setminus\{e\})$. \end{rem} \begin{lem} Given an independence system $(E,\ensuremath{\mathcal I})$ and a set $\ensuremath{{\mathcal O}}$ the set \[W\mathrel{\raise.095ex\hbox{:}\mkern-4.2mu=} \{ w\in {\mathbb R}^E_+\colon \ensuremath{\mathbf 1}\xspace^\top w=1\} \cap\{w\in{\mathbb R}^E_+\colon \emptyset\neq\ensuremath{{\mathcal O}}\cap \operatorname{arg\,max}_{I\in \ensuremath{\mathcal I}} w(I)\}\] is compact. \end{lem} \begin{proof} Clearly the set $\{ w\in {\mathbb R}^E_+\colon \ensuremath{\mathbf 1}\xspace^\top w=1\}$ compact. Also, \begin{align*} \{w\in{\mathbb R}^E_+\colon \emptyset\neq\ensuremath{{\mathcal O}}\cap \operatorname{arg\,max}_{I\in \ensuremath{\mathcal I}} w(I)\} &=\bigcup_{O\in\ensuremath{{\mathcal O}}} \{w\in{\mathbb R}_+^E\colon O\in \operatorname{arg\,max}_{I\in \ensuremath{\mathcal I}} w(I)\}, \end{align*} where each set on the right is a closed cone. As $\ensuremath{{\mathcal O}}$ is finite the right hand side is closed. Therefore $W$ is compact. \end{proof} \begin{thm}[\citealp{milgrom-2017}]\label{miltheorem} % Let $(E,\ensuremath{\mathcal M})$ be an inner matroid and $W$ be the above defined set of non-negative and non-trivial weight vectors $v$ such that at least one member of $\ensuremath{{\mathcal O}}$ is a maximum weight basis of $(E, \ensuremath{\mathcal M})$. % Then, \[\rho(\ensuremath{\mathcal I},\ensuremath{{\mathcal O}},\ensuremath{\mathcal M}) =\min_{v\in W} \frac{V^*(\ensuremath{\mathcal M},v)}{V^*(\ensuremath{{\mathcal O}},v)}.\] \end{thm} As a convenience for the reader we provide here an independent, fuller proof of the result than \citet{milgrom-2017}. \begin{proof}% If the theorem is false, there must exist an independence system $(E, \ensuremath{\mathcal I})$, a set $\ensuremath{{\mathcal O}}$ and an inner matroid $(E, \ensuremath{\mathcal M})$ such that \begin{equation} \rho(\ensuremath{\mathcal I},\ensuremath{{\mathcal O}},\ensuremath{\mathcal M}) > \min_{v\in W} \frac{V^*(\ensuremath{\mathcal M},v)}{V^*(\ensuremath{{\mathcal O}},v)}.\label{eq:viol} \end{equation} Among all such counterexamples choose one where $|E|$ is minimal. Among all such counterexamples choose one, where the support of $v$ is smallest. Denote the size of the support by $\ell$. Let \[v^*\in \operatorname{arg\,min}_{v \in W:\supp(v)\leq\ell} \frac{V^*(\ensuremath{\mathcal M},v)}{V^*(\ensuremath{{\mathcal O}},v)}. \] such that it is a vector with as few distinct values as possible. % Choose $X_\ensuremath{{\mathcal O}}\in\operatorname{arg\,max}_{S\in\ensuremath{{\mathcal O}}}v^*(S),$ and $ X_{\ensuremath{\mathcal M}}\in\operatorname{arg\,max}_{S\in\ensuremath{\mathcal M}}v^*(S)$ such that $|X_\ensuremath{{\mathcal O}}\cap X_\ensuremath{\mathcal M}|$ is maximal. By the minimum support assumption, $v^*_j = 0$ for all $j \not \in X_{\ensuremath{\mathcal M}} \cup X_{\ensuremath{{\mathcal O}}}$. \begin{claim} $v^*_j>0$ for all $j\in E\setminus X_\ensuremath{{\mathcal O}}.$ \end{claim} \begin{proofcl} Suppose there exists $j\in E\setminus X_\ensuremath{{\mathcal O}}$ with $v^*_j=0.$ Let ${\ensuremath{{\mathcal I}'}}=\ensuremath{\mathcal I}\setminus\{j\}$, $E'=E\setminus\{j\}$, ${\ensuremath{{\mathcal M}'}}=\ensuremath{\mathcal M}\setminus\{j\}$ and ${\ensuremath{{\mathcal O}'}}=\ensuremath{{\mathcal O}}\setminus\{j\}\mathrel{\raise.095ex\hbox{:}\mkern-4.2mu=} \{O\in\ensuremath{{\mathcal O}}\colon j\notin O \}.$ Because $j\notin X_\ensuremath{{\mathcal O}}\in {\ensuremath{{\mathcal O}'}}$ we have ${\ensuremath{{\mathcal O}'}}\neq\emptyset$. For our counterexample we had: \[\min_{S\in\ensuremath{{\mathcal O}}\setminus\{\emptyset\}}\frac{r_\ensuremath{\mathcal M}(S)}{|S|}=\rho(\ensuremath{\mathcal I},\ensuremath{{\mathcal O}},\ensuremath{\mathcal M})> \frac{V^*(\ensuremath{\mathcal M},v^*)}{V^*(\ensuremath{{\mathcal O}},v^*)}.\] Now \[\min_{S\in{\ensuremath{{\mathcal O}'}}\setminus\{\emptyset\}}\frac{r_{\ensuremath{{\mathcal M}'}}(S)}{|S|}\geq \min_{S\in\ensuremath{{\mathcal O}}\setminus\{\emptyset\}}\frac{r_\ensuremath{\mathcal M}(S)}{|S|},\] since the minimum on the left is taken over a smaller set and $r_{\ensuremath{{\mathcal M}'}}(S)=r_\ensuremath{\mathcal M}(S)$ for all $S\in{\ensuremath{{\mathcal O}'}}$. On the other hand, $V^*(\ensuremath{\mathcal M},v^*)\geq V^*({\ensuremath{{\mathcal M}'}},v^*)$ and $V^*(\ensuremath{{\mathcal O}},v^*)=V^*({\ensuremath{{\mathcal O}'}},v^*)>0$ yield \[ \frac{V^*(\ensuremath{\mathcal M},v^*)}{V^*(\ensuremath{{\mathcal O}},v^*)}\geq \frac{V^*(\ensuremath{\mathcal M}',v^*)}{V^*(\ensuremath{{\mathcal O}}',v^*)}.\] Together \[\min_{S\in{\ensuremath{{\mathcal O}'}}\setminus\{\emptyset\}}\frac{r_{\ensuremath{{\mathcal M}'}}(S)}{|S|}=\rho({\ensuremath{{\mathcal I}'}},{\ensuremath{{\mathcal O}'}},{\ensuremath{{\mathcal M}'}})> \frac{V^*({\ensuremath{{\mathcal M}'}},v^*)}{V^*({\ensuremath{{\mathcal O}'}},v^*)}.\] Therefore we obtain a counterexample with $|E'|<|E|$ in contradiction to our assumption of minimality of the counterexample. \end{proofcl} \begin{claim} $v^*_k=0\,\, \forall k\in X_\ensuremath{\mathcal M}\setminus X_\ensuremath{{\mathcal O}}$. \end{claim} \begin{proofcl} Suppose a $k\in X_\ensuremath{\mathcal M}\setminus X_\ensuremath{{\mathcal O}}$ with $v^*_k>0$ exists. Consider the valuations $v^\alpha=v^*-\alpha e^k$ for $0\leq\alpha< v^*_k$ and their projection \[\hat v^\alpha = \frac{1}{\sum_{i\in E} v^\alpha_i} v^\alpha\] onto the unit simplex. Now \[ \frac{\hat v^\alpha (S)}{\hat v^\alpha(T)}=\frac{v^\alpha (S)}{v^\alpha(T)}\quad \forall S,T:v(T)>0.\] Since the weights on elements in $X_\ensuremath{{\mathcal O}}$ have not changed, while the coefficient for index $k$ decreases, $X_\ensuremath{{\mathcal O}}$ is optimal for all $\alpha$. Therefore $\hat v^\alpha \in W.$ There exists $\epsilon>0$ such that $X_\ensuremath{\mathcal M}$ remains optimal for $\ensuremath{\mathcal M}$ with respect to $v^\alpha$ for $0\leq \alpha\leq\epsilon$. If not, there is another solution $X'$ that is optimal in $\ensuremath{\mathcal M}$ with respect to $v^0$. By the basis exchange property of matroids there is some $j\in X_\ensuremath{{\mathcal O}}\setminus X_\ensuremath{\mathcal M}$ such that $X' = X_{\ensuremath{\mathcal M}} \setminus \{k\} \cup \{j\}$. This contradicts our assumption, that $X_\ensuremath{\mathcal M}$ and $X_\ensuremath{{\mathcal O}}$ were chosen to have a maximal intersection. Now, observe $v^\alpha(X_\ensuremath{\mathcal M})$ and $\hat v^\alpha(X_\ensuremath{\mathcal M})/\hat v^\alpha(X_\ensuremath{{\mathcal O}})$ are decreasing for $\alpha$ increasing from $0$ to $\epsilon$. But this contradicts minimality of $v^*$. \end{proofcl} Together with the previous claim we obtain: \begin{claim} $X_\ensuremath{\mathcal M}\setminus X_\ensuremath{{\mathcal O}}=\emptyset$, therefore $X_\ensuremath{\mathcal M}\subseteq X_\ensuremath{{\mathcal O}}$ and $X_\ensuremath{{\mathcal O}}=E$. \end{claim} \begin{claim} For every $i\in X_\ensuremath{\mathcal M}$ there exists an $j\in X_\ensuremath{{\mathcal O}}\setminus X_\ensuremath{\mathcal M}$ such that $v^*_i=v^*_j$ and vice-versa. \end{claim} \begin{proofcl} Consider a valuation where $v^*_i$ is slightly decreased. If $X_\ensuremath{{\mathcal O}}$ and $X_\ensuremath{\mathcal M}$ do not change, then a smaller quotient for that valuation would result, which contradicts the assumption. As $X_\ensuremath{{\mathcal O}}=E$ that cannot change either; so $X_\ensuremath{\mathcal M}$ has to change for arbitrary small changes to $v^*_i$, and it can change only, by dropping $i$ and picking up some new element $j\in X_\ensuremath{{\mathcal O}}\setminus X_\ensuremath{\mathcal M}.$ But this requires $v^*_i=v^*_j$. Similarly, consider a valuation, where $v^*_j$ is slightly increased. If $X_\ensuremath{{\mathcal O}}$ and $X_\ensuremath{\mathcal M}$ do not change, then a smaller quotient for that valuation would result, which contradicts assumption. Again, $X_\ensuremath{{\mathcal O}}=E$ ensures that $X_\ensuremath{{\mathcal O}}$ remains optimal after these slight increases. However, it could be, that $j$ immediately enters $X_\ensuremath{\mathcal M}$ but this requires, that just as immediately some $i\in X_\ensuremath{\mathcal M}$ exits $X_\ensuremath{\mathcal M}$. But this requires $v^*_i=v^*_j$. \end{proofcl} Let $\bar v=\max_{i\in E} v^*_i$ and set \[\hat v_j^{\alpha}\mathrel{\raise.095ex\hbox{:}\mkern-4.2mu=} \begin{cases} \bar v + \alpha&\text{ if } v^*_j=\bar v,\\ v^*_j&\text{ otherwise.} \end{cases}\] If $v^*$ were a multiple of the all ones vector, we would be done. Otherwise, for $\dbarv\mathrel{\raise.095ex\hbox{:}\mkern-4.2mu=} \max_{i:v^*_i\neq \bar v} v^*_i$ holds $\dbarv\neq-\infty$. Now, when $|\alpha|\leq \bar v-\dbarv$, $X_\ensuremath{{\mathcal O}}$ and $X_\ensuremath{\mathcal M}$ remain optimal for $V^*(\ensuremath{{\mathcal O}},\hat v_j^\alpha)$ and $V^*(\ensuremath{\mathcal M},\hat v_j^\alpha)$ respectively, since $X_\ensuremath{{\mathcal O}}=E$ and $v\geq 0$ implies, that $X_\ensuremath{{\mathcal O}}$ is best possible. Regarding the optimality of $X_\ensuremath{\mathcal M}$, notice, that the greedy algorithm can find the optimal solution, but for $|\alpha|\leq \bar v-\dbarv$ the ordering of the elements did not change, hence $X_\ensuremath{\mathcal M}$ remains optimal. Let \[f(\alpha) \mathrel{\raise.095ex\hbox{:}\mkern-4.2mu=}\frac{V^*(\ensuremath{\mathcal M},\hat v_j^\alpha)}{V^*(\ensuremath{{\mathcal O}},\hat v_j^\alpha)}.\] By our analysis we deduce \[f(\alpha) \mathrel{\raise.095ex\hbox{:}\mkern-4.2mu=}\frac{V^*(\ensuremath{\mathcal M},\hat v_j^*)+\alpha|\{i\in X_\ensuremath{\mathcal M}\colon \bar v=v^*_i\}|}{V^*(\ensuremath{{\mathcal O}},\hat v_j^\alpha)+\alpha|\{i\in X_\ensuremath{{\mathcal O}}\colon \bar v=v^*_i\}|} .\] If $f'(0) < 0$, then $f(\epsilon)<f(0)= \frac{V^*(\ensuremath{\mathcal M},v^*)}{V^*(\ensuremath{{\mathcal O}},v^*)}$ (for small $\epsilon$) contrary to the assumption, that $v^*$ was chosen best possible among those with minimal $|E|$ and support of size $\ell$. For small $\epsilon$ neither $E$ nor $\supp(v^\epsilon)$ have changed. If $f'(0) > 0$, then $f(-\epsilon)<f(0)= \frac{V^*(\ensuremath{\mathcal M},v^*)}{V^*(\ensuremath{{\mathcal O}},v^*)}$ (for small $\epsilon$) contrary to the assumption, that $v^*$ was chosen best possible among those with minimal $|E|$ and support of size $\ell$. For small $\epsilon$ neither $E$ nor $\supp(v^{-\epsilon})$ have changed. Finally, if $f'(0) = 0$, it is straightforward to show that $f$ is a constant function on $\alpha\in[\dbarv -\bar v,\bar v -\dbarv]$, hence $f(\dbarv -\bar v)=f(0)$ but the number of distinct values of $\hat v^{\dbarv -\bar v}$ has decreased by $1$ contrary to the assumption that $v^*$ was chosen to have the minimum number of distinct values. Since in all three cases we got a contradiction, we conclude that $v^*$ is just a multiple of the all-ones vector. \end{proof} \begin{rem} Uniqueness of $X_\ensuremath{{\mathcal O}}$ and $X_\ensuremath{\mathcal M}$ is important for the proof. Consider a twin-peaks independence system consisting of $\{1\}$ and of $\{2,3\}$. The bases are $\{1\}$ and $\{2,3\}$. Let $2,1,1$ be the coefficients of the objective function. Optimal are both $X_1=\{1\}$ and $X_2=\{2,3\}.$ If we choose $X_2$ for the optimal solution and $\alpha$ increases from $0$ upwards then the objective function is $\alpha |X_1|$ which does not relate to $X_2$. If we choose $X_1$ for the optimal solution and $\alpha$ decreases from $0$ downwards, then, the objective function is constantly $|X_2|$ which does not relate to $X_1$. \end{rem} Theorem~\ref{miltheorem} about approximating an independence system by a matroid motivates the search for a matroid that yields a best approximation. To this end, \citet{milgrom-2017} defines the following \emph{substitutability index}: \begin{equation}\label{rho} \rho^M(\ensuremath{\mathcal I},\ensuremath{{\mathcal O}})\mathrel{\raise.095ex\hbox{:}\mkern-4.2mu=}\max_{\ensuremath{\mathcal M} \subseteq \ensuremath{\mathcal I}: \ensuremath{\mathcal M} \text{ is a matroid}}\rho(\ensuremath{\mathcal I},\ensuremath{{\mathcal O}},\ensuremath{\mathcal M}). \end{equation} \citet{milgrom-2017} gives no algorithm for determining the inner matroid $\ensuremath{\mathcal M}'$. We describe an integer program % % for finding it. Let $r$ be the rank function of the independence system $(E, \ensuremath{\mathcal I})$. We use the fact that matroids are completely characterized by their rank functions. A function $r: 2^E\mapsto {\mathbb Z}_+$ is the rank function of matroid $(E,\ensuremath{\mathcal I})$, with $\ensuremath{\mathcal I}=\{F\subseteq E\colon r(F)=|F|\}$ if and only if for all $X,Y\subseteq E$: \begin{align} \tag{R1}\label{R1} & r(X)\leq |X|\\% \text{ (subcardinality)}.\\ \tag{R2}\label{R2} & \text{If } X\subseteq Y, \text{ then } r(X)\leq r(Y)\\% \text{ (monotonicity)}\\ \tag{R3}\label{R3} & r(X\cup Y)+r(X\cap Y)\leq r(X)+r(Y)% \end{align} % % % % We formulate the problem of finding the inner matroid as the problem of finding a suitable rank function, $r'(S) = r(S) - \delta_S$, with $\delta_S$, integral, must be chosen to ensure that $r'$ is a matroid rank function. Hence, \[ \begin{alignedat}{2} \rho^M(\ensuremath{\mathcal I}, \ensuremath{{\mathcal O}}) = \max_{\delta} \min_{S \in \ensuremath{{\mathcal O}}} (1- \frac{\delta_{S}}{r(S)})&\\ \textrm{s.t.\ }\quad 0 \leq \delta_{S} &\leq r(S)&& \forall S \subseteq E\\ [r(S)-\delta_{S}] &\leq [r(T)-\delta_{T}]&&\forall S \subset T\subseteq E\\ [r(S \cup j \cup k) - \delta_{S \cup j \cup k}] - [r(S \cup j ) - \delta_{S \cup j}]&\leq [r(S \cup k ) - \delta_{S \cup k}] - [r(S) - \delta_{S}]\quad&&\forall j, k \not \in S \subseteq E\\ \delta_S &\text{ integral }&& \forall S \subseteq E\\ \end{alignedat} \] Obviously, this is not an efficient mean to find in general an optimal inner matroid, since it is an integer-program which by itself is usually hard to solve and this instances involve exponential numbers of variables and of constrainst which does not make it any easier if we aim for efficiency in $|E|$. Additionally, the usually given independence oracle is of no use either. However, if one faces an important application on a single independence system with possibly different objective functions but always, for reasons of fundamental value, the same desireable set $\ensuremath{{\mathcal O}}$, then finding a good inner matroid could be written off as a simple mean of preprocessing. \section{Comparison to Greedy} In this section we compare the outcome of the algorithm in \citet{milgrom-2017} with greedy in the zero knowledge case of $\ensuremath{{\mathcal O}} = \ensuremath{\mathcal I}$. Example~\ref{ex:twin-peaks} investigated a case, in which under zero knowledge the usual rank-quotient bound could not be improved. But that does not exclude the possibility that there exists an independence system $(E, \ensuremath{\mathcal I})$ where $\rho^M(\ensuremath{\mathcal I}, \ensuremath{\mathcal I}) > q(\ensuremath{\mathcal I})$. \begin{thm} \label{bound} For every independence system $(E,\ensuremath{\mathcal I})$, % \[ \rho^M(\ensuremath{\mathcal I}, \ensuremath{\mathcal I})\leq q(\ensuremath{\mathcal I}).\] \end{thm} \begin{proof} Suppose not. Then, there is an independence system $(E,\ensuremath{\mathcal I})$ with $ \rho^M(\ensuremath{\mathcal I}, \ensuremath{\mathcal I})>q(\ensuremath{\mathcal I}).$ Among all such counterexamples, choose one that minimizes $|E|$ and among these, one that minimizes $|\ensuremath{\mathcal I}|$. Then, \[ \rho^M(\ensuremath{\mathcal I}, \ensuremath{\mathcal I}) =\max_{\ensuremath{\mathcal M} \subseteq \ensuremath{\mathcal I}: \ensuremath{\mathcal M} \text{ is a matroid}}\min_{S \in \ensuremath{\mathcal I}\setminus\{\emptyset\}} \frac{r_{\ensuremath{\mathcal M}}(S)}{r(S)} > \min_{F\subseteq E, r(F) > 0}\, \frac{l(F)}{r(F)}=q(\ensuremath{\mathcal I}).\] Suppose the maximum on the left hand side of the inequality is attained by ${\ensuremath{{\mathcal M}'}}$ and the minimum on the right hand side by $F_0$, where $F_0$ is chosen to minimize $|F_0|$. Therefore, \begin{equation} \label{*} \rho^M(\ensuremath{\mathcal I}, \ensuremath{\mathcal I}) =\min_{S \in \ensuremath{\mathcal I}\setminus\{\emptyset\}} \frac{r_{{\ensuremath{{\mathcal M}'}}}(S)}{r(S)} > \frac{l(F_0)}{r(F_0)}=q(\ensuremath{\mathcal I}). \end{equation} Now, the lower and upper rank of $F_0$ differ (otherwise $\ensuremath{\mathcal I}$ were a matroid and $q(\ensuremath{\mathcal I})=1$), so let $U,L\subseteq F_0$ be bases of $F_0$ (in $\ensuremath{\mathcal I}$) with $|L|=l(F_0)$ and $|U|=r(F_0)$. $U$ and $L$ satisfy the following: \begin{enumerate} \item $U\cup L=F_0$ because $F_0$ was chosen to be of smallest cardinality. \item $U\cap L=\emptyset$, otherwise $F'\mathrel{\raise.095ex\hbox{:}\mkern-4.2mu=}(U\cup L)\setminus (U\cap L)$ satisfies $l(F')/r(F')<l(F_0)/r(F_0)$ contradicting the choice of $F_0$. \item $F_0=E$, otherwise the restriction of $\ensuremath{\mathcal I}$ to $F_0$ yields a smaller counter example.% \end{enumerate} Thus, our minimal counterexample has $E = U\dot\cup L$. Furthermore, $U$ and $L$ are bases of $E$ with $|L| < |U|$. This last inequality follows from \eqref{*}. Therefore, every matroid $\ensuremath{\mathcal M}$ contained in $\ensuremath{\mathcal I}$ has to have a rank of at most $|U| $, i.e., $m\mathrel{\raise.095ex\hbox{:}\mkern-4.2mu=} r_\ensuremath{\mathcal M}(E)\leq |U|$. As $U \in \ensuremath{\mathcal I}$ from \eqref{*} we see that: \[\frac{r_{\ensuremath{{\mathcal M}'}}(U)}{r(U)} \geq \min_{S \in \ensuremath{\mathcal I}\setminus\{\emptyset\}} \frac{r_{{\ensuremath{{\mathcal M}'}}}(S)}{r(S)}>\frac{l(F_0)}{r(F_0)} \Rightarrow \frac{r_{\ensuremath{{\mathcal M}'}}(U)}{|U|}>\frac{|L|}{|U|}\] \[\Rightarrow r_{\ensuremath{{\mathcal M}'}}(U)>|L|=l(F_0).\] Hence, for ${\ensuremath{{\mathcal M}'}}$ we have $|L| < m$. Let $Z$ be a basis of $L$ in ${\ensuremath{{\mathcal M}'}}$. By the augmentation property of matroid ${\ensuremath{{\mathcal M}'}}$ we can augment $Z$ into a basis $Z'$ of $E$ in ${\ensuremath{{\mathcal M}'}}$. If $Z\neq \emptyset$, then $L,Z'\in\ensuremath{\mathcal I}$ would form a smaller counterexample on the groundset $L\cup Z'$ contrary to assumption. Therefore, all elements of $L$ are dependent in ${\ensuremath{{\mathcal M}'}}.$ Hence, for the matroid $\ensuremath{\mathcal M}$ we have that the minimum in \eqref{rho} is attained for $L$, therefore, $\frac{r_\ensuremath{\mathcal M}(L)}{r(L)}=\frac{0}{|L|}=0$. This contradicts the assumption that $\rho^M(\ensuremath{\mathcal I},\ensuremath{\mathcal I}) > q(\ensuremath{\mathcal I})>0$. Therefore, no minimal example $\ensuremath{\mathcal I}$ with $\rho^M(\ensuremath{\mathcal I},\ensuremath{\mathcal I})>q(\ensuremath{\mathcal I})$ exists. % % % \end{proof} The zero knowledge assumption is weaker than necessary. If $v\geq \ensuremath{\mathbf 0}\xspace$, we know that a maximum weight basis must be, unsurprisingly, a basis of $E$. % Thus, a more reasonable knowledge assumption is $\ensuremath{{\mathcal O}}=\ensuremath{\mathcal B}_\ensuremath{\mathcal I}$. Theorem \ref{bound} continues to hold under the \emph{reasonable knowledge assumption.} This is because in the proof, $L$ and $U$ were each a basis of $E$. Suppose $v\geq \ensuremath{\mathbf 0}\xspace$ and $\ensuremath{{\mathcal O}} \subset \ensuremath{\mathcal B}_\ensuremath{\mathcal I}$. In this case, prior information rules out some basis from being optimal. To ensure an apples with apples comparison between the greedy algorithm and the algorithm in \citet{milgrom-2017} we must allow the greedy algorithm to make use of the information contained in $\ensuremath{{\mathcal O}}$ as well. This may require modifying the greedy algorithm so much that it become an entirely different algorithm altogether. A straightforward way to do this is to apply the greedy algorithm to an independence system $(E,\ensuremath{{\mathcal O}^\dagger})$ of sets contained in elements of $\ensuremath{{\mathcal O}}$. The example we describe below shows that the greedy algorithm will be dominated by Milgrom's heuristic. Under one interpretation of $\ensuremath{{\mathcal O}}$ this is not surprising. Suppose, that $\ensuremath{\mathcal I} \setminus \ensuremath{{\mathcal O}}$ is the collection of sets that can never be optimal. Then, $\ensuremath{{\mathcal O}^\dagger}$ would include sets that should definitely not be selected. \begin{example}\label{ex:stab} Consider the stable set problem (problem to find a set of nonadjacent vertices) on a path of $9$ vertices: \begin{center} \begin{tikzpicture}[scale=1.2,style=thin]% \path[clip](-1,0.5) rectangle (9,1.5); \tikzstyle{every node}=[font={\small}]; \foreach \x/\y/\i in { 0.5/1/1, 1.5/1/2, 2.5/1/3, 3.5/1/4, 4.5/1/5, 5.5/1/6, 6.5/1/7, 7.5/1/8, 8.5/1/9% }{% \node[circle, draw, fill=white,% inner sep=2pt, minimum width=14pt] at (\x,\y)(\i){\i}; } \begin{scope}[black]% \foreach \i/\j in { 1/2, 2/3, 3/4, 4/5, 5/6, 6/7, 7/8, 8/9% }{ \draw (\i)--(\j); } \end{scope}% \end{tikzpicture} \end{center} The underlying independence system has $E=\{1,2,3,4,5,6,7,8,9\}$ and the stable sets form the set-system $\ensuremath{\mathcal I}$. The maximum cardinality basis of $\ensuremath{\mathcal I}$ is the set $\{1,3,5,7,9\}$ of cardinality $5$. An example of a small basis of $E$ would be $\{2,5,8\}$ of size $3$. For the Korte-Hausmann bound, consider the set $\{1,2,3\}$ that demonstrates $q\leq \frac12$. Suppose $\ensuremath{{\mathcal O}}$ is the collection of stable sets $S$ of size at most $4$ with $|S\cap \{3,6,9\}|\leq 1$. Notice, $\{1,3,5,7\} \in \ensuremath{{\mathcal O}}$. Consider the set $\{1,2,3\}$. Assuming only subsets of elements of $\ensuremath{{\mathcal O}}$, are independent, this set has a rank quotient of $1/2$, i.e., $q(\ensuremath{{\mathcal O}^\dagger}) = 1/2$. Hence, the greedy algorithm applied to the independence system consisting of the elements of $\ensuremath{{\mathcal O}^\dagger}$ will have a worst case bound of at most $1/2$. The following matroid $\ensuremath{\mathcal M}=U^1_{\{1,2\}}\oplus U^1_{\{4,5\}}\oplus U^1_{\{7,8\}}$ is contained in $\ensuremath{\mathcal I}$ since every independent set in $\ensuremath{\mathcal M}$ is a stable set from $\ensuremath{\mathcal I}$. It is straightforward to verify that $\rho^M(\ensuremath{\mathcal I},\ensuremath{{\mathcal O}}) = 3/4 > 1/2$. Interestingly, the largest set of $\ensuremath{\mathcal I}$ is not independent in the matroid $\ensuremath{\mathcal M}$. \end{example} This example highlights the essential difference between Milgrom's heuristic and the greedy algorithm. The first is looking for a basis that has large overlap with each of the sets in $\ensuremath{{\mathcal O}}$. The greedy algorithm seeks a basis with a large overlap with \emph{every} set that is contained in $\ensuremath{{\mathcal O}^\dagger}$. \section{Discussion} Our reading of \cite{milgrom-2017} suggests that he proposed the existence of a `good' inner matroid as an explanation for the success of the greedy algorithm in some settings. He writes: \begin{quote} ``In practice, procedures based on greedy algorithms often perform very well.'' \end{quote} Our analysis shows that existence of a good inner matroid by itself is not good enough to explain the practical observation. It is possible for there to be no good inner matroid approximation, yet the greedy algorithm performs well. Further, there are examples where the inner matroid approximation will dominate that of the greedy algorithm. In our view the power of the inner matroid approximation comes from the prior knowledge encoded in $\ensuremath{{\mathcal O}}$. The idea of incorporating prior information about the optimal solution into an optimization problem is not new. There are three approaches we are aware of: probabilistic, uncertainty sets and stability. The first encodes the prior information in terms of a probability distribution over the possible objective value coefficients.\footnote{This is sometimes relaxed to a class of distributions sharing common moments.} The second, assumes that the objective coefficients are drawn from some set given a-priori. Stability assumes that the optimal solution of the instance under examination does not change under perturbations to the objective function (see \cite{bilulinial}). Milgrom, instead, proposes that the prior information be encoded in a description of the set of possible optima. Interestingly, it is unclear how to adapt the greedy algorithm (or indeed other heuristics) to incorporate prior information about the location of the optimal solution. We think this a useful and fruitful line of inquiry. % \bibliographystyle{sdv-plainnat} \newcommand{\urlprefix}{}% \nopagebreak
{'timestamp': '2019-06-17T02:14:50', 'yymm': '1906', 'arxiv_id': '1906.06217', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06217'}
arxiv
\section{Introduction} \label{sec:intro} Communities of a graph are sets of nodes that are densely connected and close to one another in the graph~\cite{Fortunato2010}. Communities are important for understanding complex systems modeled as graphs~\cite{graph-clustering-survey,Fortunato2010}. In our modern age of big data, it has become increasingly important to study and understand complex systems that arise from large data of diversely interconnected entities such as biological networks \cite{alon2003biological}, social networks \cite{girvan2002community}, citation networks \cite{giles2006future}, among many others. Community detection in graphs has been one of the most fundamental tools for analyzing and understanding the components of complex networks and has been used for many real-world applications. It has been used extensively in applications to distributed systems~\cite{hendrickson1995improved, simon1991partitioning, van1995improved}, compression~\cite{rossi2015pmc-sisc, buehrer2008scalable}, image segmentation~\cite{shi2000normalized, felzenszwalb2004efficient}, document and word clustering \cite{dhillon2001co}, among others. Communities are sets of vertices $C_1,\ldots,C_k$ such that each set $C_k$ has with more connections inside the set than outside~\cite{Fortunato2010}. While there are many different methods for finding communities~\cite{graph-clustering-survey,Fortunato2010}, it is generally agreed that a community $C_k \subseteq V$ is ``good" if the induced subgraph is dense (\emph{e.g.}, many edges between the vertices in $C_k$) and there are relatively few edges from $C_k$ to other vertices $\bar{C_k} = V \setminus C_k$~\cite{graph-clustering-survey}. Let $E(C_k)$ denote the set of edges between vertices in $C_k$ (internal edges) and $E(C_k,\bar{C}_k)$ be the set of all edges between $C_k$ and $\bar{C}_k$ (external edges). Another desired property of a community $C_k$ is that vertices in $C_k$ are all close to one another, \emph{i.e.}, the distance between any two vertices $v,w \in C_k$ denoted as $\mathtt{dist}(v,w)$ is as small as possible (small proximity, distance). Community detection aims to cut a graph into two or more sparsely interconnected dense subgraphs~\cite{Fortunato2010}. Semantically, these subgraphs may represent a tightly-knit group of friends, a household or organization, web pages of the same general topic, or a group of researchers that frequently publish together. In this work, we address the following problem: \begin{Definition}[Hierarchical Community Detection]\label{def:hier-comm-detection} Given an (un)directed graph $G=(V,E)$, the problem of hierarchical community detection is to find \begin{compactenum}[$\bullet$ \leftmargin=0.0em] \item[(i)] a hierarchy of communities denoted as $\mathbb{H} = \{\mathbfcal{C}^1,\ldots,\mathbfcal{C}^L\}$ where $\mathbfcal{C}^{t}=\{C^{t}_1,\ldots,C^{t}_k\}$ are the communities at level $t$ in the hierarchy \begin{align} V_{t} = \bigcup_k C^{t}_k \;\;\text{ and }\;\; |\mathbfcal{C}^1| < \cdots < |\mathbfcal{C}^t| < \cdots < |\mathbfcal{C}^L| \end{align} \item[(ii)] a hierarchy of community (super) graphs $G_1, \ldots, G_t, \ldots, G_L$ where $G_t=(V_t,E_t)$ succinctly captures the relationships between the communities (nodes in $G_t$) at a lower $t-1$ level in the hierarchy. The hierarchy of community (super) graphs indicate how the functional units (communities) of the graph interact at each level and how they combine to form larger communities. \end{compactenum} \end{Definition} \begin{figure*}[h!] \vspace{-1mm} \centering \subfigure[$\mathbfcal{C}^{1}$ (40 communities)]{ \includegraphics[width=0.32\linewidth]{fig1.png}\label{fig:LP-vs-hLP-netscience-traditional-LP}} \hfill \subfigure[$\mathbfcal{C}^{2}$ (6 communities)]{ \includegraphics[width=0.32\linewidth]{fig2.png}\label{fig:LP-vs-hLP-netscience-L2}} \hfill \subfigure[$\mathbfcal{C}^{3}$ (2 communities)]{ \includegraphics[width=0.32\linewidth]{fig3.png}\label{fig:LP-vs-hLP-netscience-L3}} \vspace{-3.5mm} \caption{Network science co-authorship network. \textsc{h}LP summarizes the higher-order organization of the network at multiple granularities as shown in \ref{fig:LP-vs-hLP-netscience-traditional-LP}-\ref{fig:LP-vs-hLP-netscience-L3}. Node color encodes community assignment. See text for discussion. } \label{fig:LP-vs-hLP-netscience} \vspace{-1mm} \end{figure*} While there have been a lot of work on community detection~\cite{graph-clustering-survey,Fortunato2010}, most research (i) does not address the hierarchical community detection problem (Definition~\ref{def:hier-comm-detection}) \emph{or} are (ii) inefficient for large networks with a worst-case time (and space) complexity that is \emph{not} linear in the number of edges. In this work, we describe an approach called \textsc{hLP} that addresses both these limitations. In particular, \textsc{h}LP solves the hierarchical community detection problem by detecting a hierarchy of communities (going from the lowest to highest granularity) along with a hierarchy of community (super) graphs that reveal the higher-order organization and components at each level and how these components interact with one another to form larger components at a higher-level in the hierarchy. Most importantly, \textsc{h}LP is fast and efficient for large networks with a worst-case time complexity that is linear in the number of edges whereas the space complexity of \textsc{h}LP is linear in the number of nodes. { \algblockdefx[parallel]{parfor}{endpar}[1][]{$\textbf{parallel for}$ #1 $\textbf{do}$}{$\textbf{end parallel}$} \algrenewcommand{\alglinenumber}[1]{\fontsize{7.0}{8.0}\selectfont#1\;\;} \begin{figure}[b!] \vspace{-1mm} \begin{center} \begin{algorithm}[H] \caption{\, Hierarchical Community Detection ({\textsc{h}LP}) } \label{alg:hier-LP} \begin{spacing}{1.15} \small \begin{algorithmic}[1] \smallskip \Require a graph $G=(V,E)$ \Ensure hierarchical communities $\mathbb{H} = \{\mathbfcal{C}^1,\ldots,\mathbfcal{C}^L\}$ \smallskip \State Set $G_{0} \leftarrow G$ to be the initial graph and $t \leftarrow 1$ \Repeat \State $\mathbfcal{C}^{t}\leftarrow$ \textsc{LabelProp}($G_{t-1}$) \State $G_{t}=(V_{t},E_{t}) \leftarrow \,$ \textsc{CreateSuperGraph}($G_{t-1}$, $\mathbfcal{C}^{t}$) via Eq.~\ref{eq:super-edges-for-t} \State $t \leftarrow t + 1$ \smallskip \Until{$|V_{t}|<2$} \label{algline:check-convergence} \Comment{Stop when no nodes to combine} \end{algorithmic} \end{spacing} \end{algorithm} \end{center} \vspace{-4mm} \end{figure} } { \algblockdefx[parallel]{parfor}{endpar}[1][]{$\textbf{parallel for}$ #1 $\textbf{do}$}{$\textbf{end parallel}$} \algrenewcommand{\alglinenumber}[1]{\fontsize{7}{8}\selectfont#1\;\;} \begin{figure}[b!] \vspace{-4mm} \begin{center} \begin{algorithm}[H] \caption{\, Create Super Graph} \label{alg:create-supergraph} \begin{spacing}{1.15} \small \begin{algorithmic}[1] \smallskip \Require a graph $G_{t-1} = (V_{t-1}, E_{t-1})$, communities $\mathbfcal{C}^{t}$ from $G_{t-1}$ \Ensure community (super) graph $G_t=(V_t,E_t)$ for layer $t$ \smallskip \State $V_{t} \leftarrow \mathbfcal{C}^{t-1}$ where $\mathbfcal{C}^{t-1} = \{C_1, \ldots, C_k\}$ \Comment{Super node set} \State $E_{t} \leftarrow \emptyset$ \Comment{Super edge set} \State Let $\vc$ be the community assignment vector where $c_i=k$ if $v_i \in C_k$ \parfor[$i \in V_{t-1}$] \For{$j \in \Gamma_{i}$} \Comment{Neighbor of vertex $i$} \If{$c_i \not= c_j$ \textbf{and} $(c_i,c_j) \not\in E_{t}$} \State $E_{t} \leftarrow E_{t} \cup (c_i,c_j)$ \EndIf \EndFor \endpar \end{algorithmic} \end{spacing} \vspace{-0.mm} \end{algorithm} \end{center} \vspace{-4mm} \end{figure} } \section{Approach} \label{sec:approach} This section describes our fast linear-time approach for revealing hierarchical communities in large graphs. Given $G$, the algorithm outputs a hierarchy of communities $\mathbb{H} = \{\mathbfcal{C}^{1}, \ldots, \mathbfcal{C}^{L}\}$ where $L$ is the number of layers (\emph{i.e.}, levels in the community hierarchy $\mathbb{H}$). A summary of the approach is shown in Algorithm~\ref{alg:hier-LP}. There are two general steps: Label Propagation (Section~\ref{sec:label-prop}) and Super Graph Construction (Section~\ref{sec:super-graph-construction}). \subsection{Label Propagation}\label{sec:label-prop} Note $\Gamma(v_i) = \{j \in V \,|\, (i,j) \in E\}$ is the set of neighbors of node $i$. The first step performs label propagation. In particular, the approach begins with each node belonging to its own community. For each node $v_i \in V$ (or edge), we assign it to the community $C_k \in \mathbfcal{C}$ that has the maximum number of neighbors $\Gamma(v_i)$ in it. More formally, \begin{equation}\label{eq:comm-detection-single-node-obj} \argmax_{C_k \in \,\mathbfcal{C}} \sum_{v_j \in\, \Gamma(v_i)} \mathbb{I} \big[\, v_j \in C_k \,\big] \end{equation}\noindent where for any predicate $p$ the indicator function $\mathbb{I}[ p ] = 1$ iff $p$ holds and $0$ otherwise. Hence, $\mathbb{I} \big[\, v_j \in C_k \,\big]=1$ iff $v_j \in C_k$, and 0 otherwise. In other words, every node $v_i \in V$ is assigned the label that appears the most frequent in the 1-hop neighborhood of the node Eq.~\ref{eq:comm-detection-single-node-obj} can be easily replaced/modified to take into account other important aspects. The algorithm converges when an iteration results in no further changes (\emph{i.e.}, no new assignments are made) or if the max number of iterations is reached which can be interactively tuned by the user. Upon each iteration, we compute a random permutation and use this ordering to assign nodes (or edges) to communities. To further speedup the approach, we leverage the number of previous iterations that the community assignment of a node (or edge) remained unchanged (\emph{i.e.}, the community of $v_i$ remained stable over the last $t$ iterations). In particular, let $\delta$ denote a hyperparameter that controls the number of previous iterations that the community assignment of a node or edge must remain unchanged before it is declared as final. Thus, each iteration of the approach can be defined over the set $S$ of graph elements (nodes/edges) that are still active, \emph{i.e.}, $T_i < \delta$ where $T_i$ denotes the number of subsequent iterations that $v_i$ has remained unchanged (\emph{w.r.t.} community assignment). Fast and efficient localized updates are performed when new nodes/edges arrive. \subsection{Super Graph Construction}\label{sec:super-graph-construction} Given a graph $G_{t-1}$ and $\mathbfcal{C}^{t} = \{C_1^{t}, \ldots, C_k^{t}\}$, Algorithm~\ref{alg:create-supergraph} computes the community (super) graph $G_{t}=(V_{t},E_{t})$ for layer $t$ in the community hierarchy where $V_{t} \leftarrow \mathbfcal{C}^{t}$ and thus the number of nodes in $G_{t}$ is $n_{t} = |\mathbfcal{C}^{t}|$, \emph{i.e.}, the number of communities detected in the previous graph $G_{t-1}$ (or level in the community hierarchy). Similarly, an edge $(i,j) \in E_{t}$ iff there is an edge between $C_i^{t}$ and $C_j^{t}$ in $G_{t-1}$, \emph{i.e.}, a link exists between a node $r \in V_{t-1}$ assigned to community $C_i^{t}$ and another node $s \in V_{t-1}$ assigned to community $C_j^{t}$. More formally, \begin{equation}\label{eq:super-edges-for-t} E_{t} = \big\lbrace (i,j) \,:\, r \in C_i^{t}, \,s \in C_j^{t} \wedge\; (r,s) \in E_{t-1} \,\wedge\; i\not=j \big\rbrace \end{equation}\noindent \begin{property} Let $E_t(C_i, C_j)$ be the set of edges between $C_i$ and $C_j$ (cut set), then the number of edges $|E_{t+1}|$ in the next level $t+1$ is: \begin{align} |E_{t+1}| = \sum_{C_i \in \mathbfcal{C}^{t}} \;\;\sum_{C_j \in \mathbfcal{C}^{t}} |E_t(C_i, C_j)| \;\;\text{ s.t. }\; i<j \end{align}\noindent Note $|E_t(C_i, C_j)|$ does not include multi-edges. \end{property} Algorithm~\ref{alg:create-supergraph} returns $G_t=(V_t,E_t)$ for layer $t$ in the hierarchy. The approach terminates when $|V_{t}|<2$ as shown in Algorithm~\ref{alg:hier-LP}. Hence, \textsc{h}LP terminates when there are no nodes remaining to combine. \begin{property}\label{prop:node-and-edge-size-shrink} Let $|E(G_t)|$ and $|V(G_t)|$ be the number of edges and nodes in $G_t$ and $G_{0} \leftarrow G$, then \begin{align} |E(G_0)| \geq \cdots \geq |E(G_L)| \;\;\text{ and }\;\; |V(G_0)| \geq \cdots \geq |V(G_L)| \end{align} \end{property}\noindent Property~\ref{prop:node-and-edge-size-shrink} has a number of important and useful implications that are leveraged in Section~\ref{sec:analysis}. \section{Analysis} \label{sec:analysis} This section shows the worst-case time and space complexity of the proposed approach. Let $L$ denote the number of layers (hierarchies) and let $T$ denote the maximum number of iterations at any given layer. Both $L$ and $T$ are small. Further, let $N = |V|$ denote the number of nodes and let $M = |E|$ denote the number of edges in $G$. \subsection{Time Complexity}\label{sec:time-complexity} \begin{lem}\label{lem:time-complexity} The worst-case time complexity of \emph{hierarchical label propagation} is \begin{equation} \mathcal{O}(LTM) = \mathcal{O}(M) \end{equation}\noindent where $L$ and $T$ are small constants. Therefore, the time complexity is linear in the number of edges $M$ in the graph. \end{lem} \smallskip\noindent\textbf{Supergraph construction}: The worst-case time complexity of Algorithm~\ref{alg:create-supergraph} is $\mathcal{O}(|E_{t-1}|)$. This is bounded above by the number of edges denoted as $|E|$ in the input graph $G$. \subsection{Space Complexity}\label{sec:space-complexity} \begin{lem}\label{lem:space-complexity} The space complexity of hierarchical label propagation is \begin{equation} \mathcal{O}(NL) \end{equation}\noindent where $L$ is a small constant. Therefore, the space complexity is linear in the number of nodes in $G$. \end{lem} Lemma~\ref{lem:space-complexity} assumes the node community assignments at each layer are stored and given as output to the user. However, this information can be significantly compressed by storing only the community assignments at the first layer, and then storing only how these communities are merged at each subsequent layer. \smallskip\noindent\textbf{Supergraph construction}: The worst-case space complexity of Algorithm~\ref{alg:create-supergraph} is $\mathcal{O}(|E_{t-1}|)$. Similar to time complexity, this is bounded above by the number of edges denoted as $|E|$ in the input graph $G$. \begin{figure*}[h!] \vspace{-1mm} \centering \subfigure[road-luxembourg ($\mathbfcal{C}^{2}$)] { \includegraphics[width=0.32\linewidth]{fig4.png} \label{fig:supergraph-road-luxembourg-layer1}} \hfill \subfigure[$\mathbfcal{C}^{3}$] { \includegraphics[width=0.32\linewidth]{fig5.png} \label{fig:supergraph-road-luxembourg-layer2}} \hfill \begin{minipage}[b]{0.32\textwidth} \centering \vspace{-4mm} \subfigure[$\mathbfcal{C}^{4}$] { \includegraphics[width=0.85\linewidth]{fig6.png} } \vspace{-2mm} \subfigure[$\mathbfcal{C}^{5}$] { \includegraphics[width=0.55\linewidth]{fig7.png} } \end{minipage} \vspace{-3.5mm} \caption{ In this case study, the network data is a road network of luxembourg consisting of 114,600 nodes and 239,332 edges making it impossible to visualize the entire network. There are 9,452 communities in $\mathbfcal{C}^{2}$ and therefore impossible to visualize by assigning each community a unique color. (a) Super graph derived after first layer consisting of 9,452 supernodes (communities) with 25,386 superedges (between community edges). (b) consists of 2,023 communities with only 6,588 between community edges whereas (c)-(d) consists of 372 and 48 communities with 1,580 and 214 between community edges, respectively. Nodes are weighted by degree. See text for discussion. } \vspace{-1.0mm} \label{fig:supergraph-road-luxembourg-new} \end{figure*} \section{Experiments} \label{sec:exp} The experiments in this section are designed to investigate the quality of the communities revealed by \textsc{h}LP and the utility of the hierarchical communities for a visualization application. For comparison, we use a wide variety of graphs from different application domains including social networks (soc), biological/protein networks (bio), infrastructure networks (inf), web graphs (web), road networks (road), and collaboration networks (ca). Due to space constraints, network statistics were removed but can be accessed online at \url{http://networkrepository.com} along with the data~\cite{nr}. \subsection{Comparison} \subsubsection{Baseline methods.} For fair comparison, we use baselines that are fast with \emph{linear-time} complexity (with the exception of Louvain): {\smallskip \begin{compactenum}[$\bullet$ \leftmargin=0em] \item \textbf{Densest Subgraph} (\textbf{DS})~\cite{khuller2009finding}: This method finds an approximation of the densest subgraph in $G$ using degeneracy ordering, and removes this subgraph. This is repeated until all nodes have been assigned. \item \textbf{KCore Communities} (\textbf{KCore})~\cite{rossi2015pmc-sisc,shin2016corescope}: Many have observed that the largest k-core subgraphs of a real-world network are highly dense subgraphs that often contain the max clique~\cite{rossi2015pmc-sisc}. The KCore baseline simply uses the maximum k-core subgraph as $S$ and $\bar{S} = V \setminus S$. \item \textbf{Label Propagation} (\textbf{LP})~\cite{raghavan2007near}: Label propagation takes a labeling of the graph, then for each node, the label is updated according to the label that occurs the most among its neighbors. This is repeated until convergence. \item \textbf{Louvain} (\textbf{Louv})~\cite{blondel2008fast}: Louvain performs a greedy optimization of modularity by forming small, locally optimal communities then grouping each community into one node. This two-phase process is repeated until modularity cannot be maximized locally. \item \textbf{Spectral Clustering} (\textbf{Spec})~\cite{chung1997spectralbook}: This baseline uses spectral clustering on the normalized Laplacian of the adjacency matrix to greedily build the sweeping cluster that minimizes conductance. \end{compactenum} \smallskip} \noindent \begin{table}[h!] \centering \setlength{\tabcolsep}{3.5pt} \renewcommand{\arraystretch}{1.1} \caption{ Quantitative evaluation of the methods (modularity). The best result from each graph is bold. Note \textsc{h}LP is the proposed method. } \vspace{-3mm} \label{table:quant-mod} \small \begin{tabularx}{1.0\linewidth}{lHrr rr rH HrHHHHH} \toprule && \multicolumn{1}{l}{\rotatebox{0}{\textbf{DS}}} & \multicolumn{1}{l}{\rotatebox{0}{\textbf{KCore}}} & \multicolumn{1}{l}{\rotatebox{0}{\textbf{LP}}} & \multicolumn{1}{l}{\rotatebox{0}{\textbf{Louv}}} & \multicolumn{1}{l}{\rotatebox{0}{\textbf{Spec}}} &&& \multicolumn{1}{l}{\rotatebox{0}{\textbf{\textsc{h}LP}}} & \\ \midrule \textsf{soc-yahoo-msg} && 0.0003 & 0.0004 & 0.0479 & 0.0394 & 0.0005 &&& \textbf{0.0569} \\ \textsf{bio-gene} && 0.0195 & 0.0217 & 0.0315 & 0.0408 & -0.0208 &&& \textbf{0.0846} \\ \textsf{ca-cora} && 0.0089 & 0.0304 & 0.0444 & 0.0608 & 0.0164 &&& \textbf{0.1026} \\ \textsf{soc-terror} && 0.0888 & 0.0892 & 0.0967 & 0.0967 & 0.0999 &&& \textbf{0.1243} \\ \textsf{inf-US-powerGrid} && 0.0027 & 0.0027 & 0.0061 & 0.0212 & 0.1127 &&& \textbf{0.1242} & \\ \textsf{web-google} && 0.0272 & 0.0275 & 0.0429 & 0.0471 & 0.1010 &&& \textbf{0.1122} & \\ \textsf{ca-CSphd} && 0.0224 & 0.0224 & 0.0234 & 0.0198 & 0.0131 &&& \textbf{0.1201} & \\ \textsf{ca-netscience} && 0.0164 & 0.0168 & 0.1063 & 0.0561 & 0.1229 &&& \textbf{0.1233} & \\ \textsf{road-luxem.} && 0.0629 & 0.0629 & 0.0077 & 0.0046 & -0.1170 &&& \textbf{0.1141} & \\ \textsf{bio-DD21} && 0.0865 & 0.0866 & 0.0106 & 0.0202 & 0.1241 &&& \textbf{0.1247} & \\ \bottomrule \end{tabularx} \end{table} \subsubsection{Quantitative evaluation.} We quantitatively evaluate the communities using modularity~\cite{newman2001structure}. Modularity is defined as: \begin{equation} \label{eq:modularity} \mathbb{E(\vc)} = \frac{1}{2m} \sum_{ij} \Bigg[ A_{ij} - \frac{d_i d_j}{2m} \Bigg] \delta(c_i, c_j) \end{equation}\noindent where $M$ is the number of edges, $\mA$ is the adjacency matrix with $A_{ij}=1$ if $(i,j) \in E$ and 0 otherwise; $d_i$ and $d_j$ is the degree of node $i$ and $j$; $c_i$ and $c_j$ are the community assignments of node $i$ and node $j$; and $\delta$ is an indicator function such that $\delta(c_i, c_j)=1$ if $c_i=c_j$ and $0$ otherwise. We report the best result from any layer/level in the community hierarchy. Results are provided in Table~\ref{table:quant-mod}. Notably, \textsc{h}LP outperforms all the other baseline methods across all graphs as shown in Table~\ref{table:quant-mod}. \textsc{h}LP reveals better high quality communities across a wide variety graphs from different application domains (social, biological, infrastructure, among others) as shown in Table~\ref{table:quant-mod}. Overall, \textsc{h}LP typically achieves at least an order of magnitude improvement over the other baseline methods. Now we investigate the communities found by \textsc{h}LP by overlaying the community assignments on top of the network structure (node-link diagram). The communities given by \textsc{h}LP at different levels in the hierarchy are shown in Figure~\ref{fig:LP-vs-hLP-netscience} for the network science co-authorship network. Communities in \ref{fig:LP-vs-hLP-netscience-traditional-LP} represent small groups of researchers that frequently publish together whereas communities in \ref{fig:LP-vs-hLP-netscience-L2} represent different research areas and so on. \subsubsection{Runtime Performance} \label{sec:exp-runtime-perf} Figure~\ref{fig:supergraph-road-luxembourg-new} visualizes the important components (functional modules) of a large road network from luxembourg at multiple scales (layers). Note that using a serial python implementation of the proposed method takes only 10.2 seconds to derive the initial 9,452 communities visualized in Figure~\ref{fig:supergraph-road-luxembourg-layer1}. However, the next layer is orders of magnitude faster taking less than a second (0.611 sec.) and the runtime steadily decreases as a function of the supergraph size (number of supernodes, superedges) and the number of iterations to converge in the preceding layers. Furthermore, the number of iterations until convergence also steadily decreases as the number of layers increases. \subsection{Visualizing Large Networks} One important application of \textsc{h}LP is visualization of large networks. In Figure~\ref{fig:supergraph-road-luxembourg-new}, we use \textsc{h}LP to compute a hierarchy of communities for a large real-world network consisting of 114,600 nodes and 239,332 edges. While it is impractical and often impossible to visualize such a large network, we can use \textsc{h}LP to summarize the graph structure at multiple levels as shown in Figure~\ref{fig:supergraph-road-luxembourg-new}. Instead of visualizing the graph at the level of intersections (nodes in the original road network), we can instead visualize the graph at a higher-level where nodes represent something more meaningful, \emph{e.g.}, instead of intersections, nodes at layer 2 shown in Figure~\ref{fig:supergraph-road-luxembourg-layer2} might represent neighborhoods and edges represent routes from one neighborhood to another. Thus, \textsc{h}LP uncovers the \emph{hierarchical higher-order organization} of complex networks. \bibliographystyle{ACM-Reference-Format}
{'timestamp': '2019-06-18T02:03:16', 'yymm': '1906', 'arxiv_id': '1906.06432', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06432'}
arxiv
\section*{Acknowledgments} \vspace{-1.5ex} \noindent The authors wish to thank Luca Cosmo, Luca Balsanelli and Jing Ren for useful discussions and the technical help. AR and ER are supported by the ERC Starting Grant no. 802554 (SPECGEO). Parts of this work were supported by the KAUST OSR Award No. CRG-2017-3426, a gift from the NVIDIA Corporation and the ERC Starting Grant No. 758800 (EXPROTEA). } {\small \bibliographystyle{ieee} \section{Background} \vspace{-0.5ex} In this paper we model shapes as 2-dimensional Riemannian manifolds $\mathcal{X}$ (possibly with boundary $\partial\mathcal{X}$) equipped with the area element $\mathrm{d}x$. We denote by $\mathrm{int}(\mathcal{X})$ the interior of $\mathcal{X}$, namely the set of points $\mathcal{X}\setminus\partial\mathcal{X}$. \vspace{1ex}\noindent\textbf{Laplacian.} The positive semi-definite Laplace-Beltrami operator $\Delta_\mathcal{X}$ (or manifold Laplacian) generalizes the basic differential operator from Euclidean analysis to Riemannian manifolds. It admits a spectral decomposition \begin{align} \Delta_\mathcal{X} \phi_i(x) &= \mu_i \phi_i(x) &x\in\mathrm{int}(\mathcal{X}) \label{eq:eig} \\ \phi_i(x) &=0 &x\in\partial\mathcal{X}\,,\label{eq:d} \end{align} with homogeneous Dirichlet boundary conditions \eqref{eq:d}, where $\{ 0<\mu_1 \leq \mu_2 \leq \dots \}$ are the eigenvalues (each with finite multiplicity) and $\phi_i$ are the associated eigenfunctions. For the remainder of the paper, we always assume eigenvalues to be increasingly ordered. The {\em spectrum} of $\Delta_\mathcal{X}$ is the set of all eigenvalues, forming a discrete subset of $\mathbb{R}_+$. It encodes geometric and topological properties of $\mathcal{X}$; for instance, it has been used as a basic global shape descriptor for 3D shape retrieval \cite{reuter2006laplace}. A direct consequence of Eq.~\eqref{eq:eig} is that each eigenvalue $\mu_i$ is associated to an eigenfunction $\phi_i$ by the equality\footnote{In this equality we use the intrinsic gradient operator $\nabla_\mathcal{X}$ acting on scalar functions $f:\mathcal{X}\to\mathbb{R}$, which defines the direction (tangent to the surface) of the steepest change of $f$ around each point $x\in\mathcal{X}$.} \begin{align}\label{eq:de} \mu_i = \int_\mathcal{X} \| \nabla_\mathcal{X} \phi_i (x) \|^2_2 \,\mathrm{d}x \end{align} after normalization so that $\int_\mathcal{X} \phi_i^2(x) \mathrm{d}x =1$. Equation~\eqref{eq:de} makes the {\em global} nature of the eigenvalues clear, since they are computed as integrals over the entire surface. \vspace{1ex}\noindent\textbf{Hamiltonian operator.} Given a scalar {\em potential} function $v:\mathcal{X}\to\mathbb{R}_+$, one can define a Hamiltonian $H_\mathcal{X} = \Delta_\mathcal{X} + v$, operating on scalar functions $f$ as follows: \begin{align} H_\mathcal{X} f = \Delta_\mathcal{X} f + v f\,, \end{align} where the product $vf$ is taken point-wise. Trivially, for the null potential where $v(x)=0 ~~\forall x\in\mathcal{X}$, the Hamiltonian $H_\mathcal{X}$ simplifies to $\Delta_\mathcal{X}$. The operator $H_\mathcal{X}$ also admits a spectral decomposition: \begin{align} H_\mathcal{X} \psi_i(x) = \lambda_i \psi_i(x)\,, \end{align} with boundary conditions when necessary. Hamiltonian eigenfunctions have been used in shape analysis applications in \cite{choukroun2018hamiltonian,melzi2018localized,rodola2019functional}. \vspace{1ex} \setlength{\columnsep}{7pt} \setlength{\intextsep}{1pt} \begin{wrapfigure}[4]{r}{0.23\linewidth} \vspace{-0.6cm} \begin{center} \begin{overpic} [trim=0cm 0cm 0cm 0cm,clip,width=1.0\linewidth]{./figures/notation.pdf} \put(29,96){\footnotesize $h$} \put(34,45){\footnotesize $i$} \put(100,28){\footnotesize $k$} \put(93,77){\footnotesize $j$} \put(48,80){\footnotesize $\alpha_{ij}$} \put(72,45){\footnotesize $\beta_{ij}$} \end{overpic} \end{center} \end{wrapfigure} \noindent\textbf{Discretization.} In the discrete setting, $\mathcal{X}$ is approximated by a triangle mesh with $n$ vertices $v_i\in V_\mathrm{int} \cup V_\mathrm{bdr}$, and where each edge $e_{ij}\in E_\mathrm{int} \cup E_\mathrm{bdr}$ belongs to at most two triangle faces $F_{ijk}$ and $F_{jih}$ (see inset for notation). We use the subscripts $\mathrm{int}$ and $\mathrm{bdr}$ on vertices and edges to denote interior and boundary, respectively. The Laplacian is defined in terms of two $n\times n$ matrices $\mathbf{W}$ and $\mathbf{A}$, where $\mathbf{A}$ is a diagonal matrix of local area elements $a_i$ and $\mathbf{W}$ is a symmetric matrix of edge-wise weights (also known as cotangent formula, see \eg \cite{meyer2003discrete}): \begin{eqnarray} \label{eq:cotan} w_{ij} \hspace{-0.3cm} &=& \hspace{-0.4cm} \left\{ \begin{array}{lc} {\scriptstyle -(\cot \alpha _{ij} + \cot \beta _{ij})/2} & {\scriptstyle e_{ij} \in E_\mathrm{int};} \\ {\scriptstyle 0} & {\scriptstyle (i\neq j) \wedge (i \in V_\mathrm{bdr} \vee j \in V_\mathrm{bdr})}; \\ {\scriptstyle \sum_{k\neq i} (\cot \alpha _{ik} + \cot \beta _{ik})/2} & {\scriptstyle (i = j) \wedge v_i\in V_\mathrm{int};} \\ {\scriptstyle 1} & {\scriptstyle (i = j) \wedge v_i\in V_\mathrm{bdr};} \end{array} \right.\\ a_i \hspace{-0.3cm} &=& \hspace{-0.4cm} \left\{ \begin{array}{lc} \frac{1}{3}\sum_{jk:ijk\in F} A_{ijk} & v_i \in V_\mathrm{int}; \\ 0 & v_i \in V_\mathrm{bdr}; \end{array} \right. \end{eqnarray} where $A_{ijk}$ is the area of triangle $F_{ijk}$. In the formulas above, the special treatment of boundary edges and vertices imposes the Dirichlet boundary conditions of Eq.~\eqref{eq:d}. A generalized eigenproblem $\mathbf{W}\bm{\Phi} = \mathbf{A}\bm{\Phi}\mathrm{diag}(\bm{\mu})$ is solved for computing the Laplacian eigenvalues and eigenvectors. In the case of the Hamiltonian, it takes the form \begin{align}\label{eq:eigs} (\mathbf{W}+\mathbf{A}\mathrm{diag}(\v))\bm{\Psi} = \mathbf{A}\bm{\Psi}\mathrm{diag}(\bm{\lambda})\,. \end{align} Above, $\mathbf{v}$ is a $n$-dimensional vector containing the values of the potential $v$ at each vertex, $\bm{\Phi}$ and $\bm{\Psi}$ are matrices containing the first $k$ eigenvectors as their columns, and $\bm{\lambda},\bm{\mu}$ are the corresponding $k$-dimensional vectors of eigenvalues. For brevity, we will write $\bm{\lambda}(\bm{\Delta}_\mathcal{X}+\mathrm{diag}(\v))$ to denote the eigenvalues appearing in Eq.~\eqref{eq:eigs}. \section{Conclusions} \vspace{-0.5ex} In this paper we presented a new approach for partial shape similarity, based on aligning short sequences of eigenvalues computed on the given shapes. Our approach is correspondence-free, is invariant to non-rigid transformations, it can be solved efficiently, and only makes use of descriptors for post-processing refinement. Our formulation is also general enough to be applied to other relevant tasks in vision and graphics. We demonstrated this on a challenging shape-from-spectrum recovery problem, where it compares favorably with respect to a very recent method. % \begin{figure}[bt] \centering \begin{overpic} [trim=0cm 0cm 0cm 0cm,clip,width=0.85\linewidth]{./figures/fail.png} \put(0,16.5){\footnotesize 0.51} \put(51,16.5){\footnotesize 0.13} \end{overpic} \begin{overpic} [trim=0cm 0cm 0cm -2.0cm,clip,width=0.85\linewidth]{./figures/fail_2D.pdf} \end{overpic} \caption{\label{fig:fail}Failure cases. {\em Top}: On the left example, the eigenvalues did not align well at the local optimum; as a result, the partial shape was localized only roughly. On the right, the found region is wrongly classified as correct since it has similar eigenvalues to the partial input within the limited bandwidth. In both cases we report the IoU. {\em Bottom}: Shape-from-spectrum recovery of shapes with non-trivial topology can be difficult to achieve, due to the narrow bandwidth and first-order discretization of the operators.} \end{figure} \vspace{1ex}\noindent\textbf{Limitations and future work.} We did observe some failure cases during our tests (see Figure~\ref{fig:fail}). In the partial similarity setting, this typically happens whenever the chosen bandwidth (\ie, the number $k$ of input eigenvalues) is too small for discriminating regions that only differ at medium-high frequencies; \eg, a human arm might be confused with a leg. This can be remedied to some extent by increasing the value of $k$. For large values ($k>100$), however, a more accurate discretization of the operator $\Delta$ should be used in place of the cotangent formulas of Eq.~\eqref{eq:cotan}, to avoid artifacts related to mesh tessellation. Using second- or third-order FEM discretization \cite{ciarlet2002finite} might be a promising solution. Furthermore, while we only showed 2D examples of shape-from-spectrum recovery, the exact same algorithm can be used invariantly for reconstructing the geometry of 3D (volumetric) shapes. However, this would require solving for a potential defined in $\mathbb{R}^3$, for which efficient data structures (such as octrees) could be necessary. We leave this exciting possibility to future work. Finally, a theoretical question that we left open concerns the empirical observation that eigenfunction alignment is induced in many practical situations. We believe that this requires a deeper understanding, with potentially profound consequences in many applied domains. \section{Introduction} \vspace{-0.5ex} Assessing similarity between non-rigid shapes is an active research topic in computer vision, pattern recognition and graphics \cite{biasotti2016recent}. At the heart of such methods lies the definition of shape {\em descriptors}, characterizing the shape either locally or globally (\eg, via the Bag-of-Words \cite{toldo2009bag} paradigm or via deep learning \cite{monti2017geometric}). Deformation-invariant shape descriptors often require careful tuning and hand-crafting, or sufficient training examples to enable learned-based methods. While similarity by itself is usually expressed by a numerical score, the problem as a whole is also strictly related to (and often solved in tandem with) the complementary problem of shape {\em correspondence}. In this setting, local shape descriptors are used as `probe' quantities to employ in more sophisticated pipelines to infer a functional \cite{rodola2017partial} or point-to-point \cite{bronstein2009partial} correspondence. \begin{figure}[t!] \centering \begin{overpic} [trim=0cm 0cm 0cm 0cm,clip,width=0.22\linewidth]{./figures/teaser/target.png} \put(34,56){\footnotesize $\mathcal{X}$} \end{overpic} \begin{overpic} [trim=0cm 0cm 0cm 0cm,clip,width=0.36\linewidth]{./figures/teaser/init.png} \put(58,43){\footnotesize $\mathcal{Y}$} \end{overpic}\\ % \begin{overpic} [trim=0cm -3cm 0cm 0cm,clip,width=0.32\linewidth]{./figures/teaser/middle1.png} \put(41,0.9){\footnotesize iteration 10} \put(59.5,55){\footnotesize $\color{white} v$} \end{overpic} \begin{overpic} [trim=0cm -3cm 0cm 0cm,clip,width=0.32\linewidth]{./figures/teaser/middle.png} \put(41,0.9){\footnotesize iteration 30} \put(59.5,55){\footnotesize $\color{black} v$} \end{overpic} \begin{overpic} [trim=0cm -3cm 0cm 0cm,clip,width=0.32\linewidth]{./figures/teaser/end.png} \put(41,0.9){\footnotesize iteration 60} \put(59.5,55){\footnotesize $\color{black} v^\ast$} \end{overpic} \setlength{\tabcolsep}{0pt} \begin{tabular}{ccc} \input{./figures/teaser/eig_middle1.tex}& \input{./figures/teaser/eig_middle.tex}& \input{./figures/teaser/eig_end.tex} \end{tabular} \caption{\label{fig:teaser} Given a non-rigid partial 3D query $\mathcal{X}$ and a full shape $\mathcal{Y}$, we propose a way to locate $\mathcal{X}$ in $\mathcal{Y}$ without having to compute a correspondence $\pi:\mathcal{X}\to\mathcal{Y}$. We do so by looking for an indicator function $v$ on $\mathcal{Y}$ which, when used to construct a Laplacian-like matrix on $\mathcal{Y}$, its eigenvalues become the same as those of the classical Laplacian on $\mathcal{X}$. The optimal $v^\ast$ attaining the eigenvalue alignment localizes the sought region. Here we show the evolution of $v$ (middle row) and of the corresponding eigenvalues (bottom row) across our iterative algorithm until convergence. } \end{figure} Even more challenging is the setting of {\em partial} shape similarity, which is the focus of this paper. In this case, only some {\em regions} of the shapes are expected to be similar due to the presence of clutter or missing geometry. Partial similarity arises in numerous practical tasks, ranging from object reassembly \cite{gregor2014towards,litany2016non} to protein docking \cite{shentu2008context} and deformable object-in-clutter detection \cite{cosmo2016matching} among others. In the partial setting, in addition to defining a similarity metric, one also has to identify the relevant similar regions of the given shapes, which is a difficult problem in itself (see Figure~\ref{fig:teaser}). As a result, while global similarity has been extensively studied, only few methods exist to address the (especially non-rigid) partial 3D similarity problem. A seemingly unrelated problem concerns the recovery of the geometry of an unknown shape (\ie, whose point coordinates in space are not given) from a minimal amount of input data. Notably, it has been recently shown \cite{isosp} that, in some cases, one can reconstruct the geometry of a shape even when an incomplete sequence of its Laplacian eigenvalues (its spectrum) are given as an input -- a problem widely known in mathematical physics as ``hearing the shape of the drum''~\cite{kac}. In vision and graphics, this problem finds applications in non-isometric shape matching as well as style transfer \cite{isosp} and acoustics design \cite{bharaj2015computational}. In this paper we show that partial shape similarity and shape-from-spectrum recovery, while apparently very distinct, can be phrased as instances of the same mathematical problem. We formulate this problem by exploiting the notion of the Hamiltonian operator on manifolds, and reduce it to an unconstrained continuous optimization problem over the vector space of real-valued functions defined over the surfaces; see Figure~\ref{fig:teaser} for an illustration of our methodology on a real example. \subsection{Related work}\label{sec:rel} Partial similarity of 3D shapes has long been researched by the vision and geometry processing communities, with the vast majority tackling the {\em rigid} setting. Since the focus of this work is on {\em non-rigid} structures, we discuss methods addressing deformable objects here, and refer the interested reader to the recent surveys \cite{sipiran2013shrec,pratikakis2016partial,phamshrec} for the former case. \vspace{1ex}\noindent\textbf{Partial shape retrieval.} At a high level our task is related to shape retrieval, where the goal is to produce a {\em ranking} of most similar shapes according to a similarity score. Even in this simpler task, surprisingly few methods have attempted to address the problem. We mention here the recent SHREC'17 challenge \cite{shrec17}, highlighting how deep learning-based methods may work well for producing rankings, provided that enough training examples are available (the organizers provided around two thousands). Our task is more challenging, as we aim at identifying the regions that two non-rigid objects have in common. \vspace{1ex}\noindent\textbf{Partial shape correspondence.} When a map $\pi:\mathcal{X}\to\mathcal{Y}$ between shapes $\mathcal{X}$ and $\mathcal{Y}$ is available, one may simply look at the image $\pi(\mathcal{X})\subset\mathcal{Y}$ in order to determine the corresponding region (for simplicity, here we assume that $\mathcal{X}$ is a deformed region of $\mathcal{Y}$ as in Figure~\ref{fig:teaser}). Thus, any partial shape matching method implicitly solves for the common region as a side product, at the cost of solving a computationally heavy correspondence problem. To date, solving a full correspondence problem is therefore the dominant approach. Bronstein~\etal \cite{bronstein2009partial} proposed to explicitly solve for a point-to-point map $\pi$ and a membership function $\mu$ (or ``fuzzy part'', measuring the degree of inclusion of each point into the subset), optimizing for $\pi$ and $\mu$ in an alternating fashion. Optimization for $\pi$ was posed as a NP-hard quadratic assignment problem \cite{burkard1998quadratic}, while solving for $\mu$ required solving a non-convex quadratic problem due to the presence of region regularizers. More recently, Rodol\`a~\etal \cite{rodola2017partial} followed a similar approach where the correspondence step was rephrased using the functional map representation \cite{ovsjanikov2012functional}. A membership function is still optimized for, with the same regularizers as those in \cite{bronstein2009partial}. The framework was extended in \cite{litany2016non} to address the case with $n>2$ regions (``non-rigid puzzle''), leading to a multi-label segmentation problem where $n$ functional maps are optimized simultaneously. The presence of clutter was investigated in \cite{cosmo2016matching} using the same formulation of \cite{rodola2017partial}, but where the local descriptors (which are used in all the methods above to drive the correspondence) are learned via deep metric learning on a representative dataset. Finally, Brunton~\etal \cite{brunton2014low} proposed an iterative approach where a partial map is recovered by an isometric growing procedure starting from sparse pre-matched features over the surfaces. In contrast to these methods, our approach does not require solving for dense correspondences, thus essentially eliminating the need for local descriptors, and does not make use of complex regularizers. Instead, we phrase the optimization problem in terms of solving for a real-valued (indicator) function aimed at identifying similar regions, and devise a correspondence-free metric that allows us to measure and optimize for the similarity of such functions directly. A related approach was previously introduced by Pokrass~\etal \cite{pokrass2013partial} for identifying region-wise similarity. However, unlike our method, that approach relies on the comparison of \emph{descriptor} statistics over the surface, thus strongly depending on the specific choice of descriptors. \vspace{1ex}\noindent\textbf{Isospectralization.} From an algebraic standpoint, ours may be seen as an ``inverse eigenvalue problem''~\cite{chu2005inverse}; despite the name, problems in this domain typically require knowledge of the eigenvectors of the sought operator, while our method does not. Perhaps, the most closely related to ours is the recent work on \emph{isospectralization} \cite{isosp} where the authors deform the shapes with the goal of aligning their Laplacian eigenvalues. We also use a similar observation that in practice these eigenvalues provide a powerful characterization of the shape's geometry. However, we focus on the partial setting and propose to solve for a characteristic function of a region, thus avoiding any explicit shape deformation. \subsection{Contribution} The key contribution of this paper is to show that for many practical problems, it is possible to side-step the need for a correspondence by looking at the eigenvalues of certain differential operators constructed on each surface. This leads to tangible consequences that we leverage in two challenging applications. Specifically, \begin{itemize} \item We introduce a new method for detecting similar regions among deformable shapes; for the first time, the optimization is completely {\em correspondence-free} and, at its core, descriptor-free \item Our optimization problem uses a single objective, thus avoiding possibly complex regularizers, and can be solved {\em efficiently} with off-the-shelf differentiable programming libraries; \item We provide a remarkably simple alternative to recent {\em isospectralization} techniques \cite{isosp}, while at the same time yielding qualitatively better results at a fraction of the time cost. \end{itemize} \section{Our method}\label{sec:method} \vspace{-0.5ex} We first present and discuss our general formulation, and then demonstrate its application to two separate tasks in Sections~\ref{sec:local} and \ref{sec:isosp}. The main idea behind our approach is to model regions $\mathcal{R}\subset\mathcal{X}$ via potential functions, rather than by explicitly manipulating points $x\in\mathcal{R}$. Further, similarly to \cite{isosp}, we rely upon the empirical observation that, in many practical cases, the Laplacian eigenvalues encode the geometry of the domain \vspace{1ex}\noindent\textbf{Optimization problem.} Our input is a given shape $\mathcal{X}$ and, separately, an increasing sequence of $k$ Dirichlet eigenvalues stored in a vector $\bm{\mu}\in\mathbb{R}^{k}$. The precise source of these eigenvalues is {\em not known}, but they are assumed to come from a manifold Laplacian. It is our task to identify the shape of this domain. To do so, we consider the following {\em eigenvalue alignment} problem: \begin{align}\label{eq:prob} \min_{\v\ge 0} \| \bm{\lambda}(\bm{\Delta}_\mathcal{X} + \mathrm{diag}(\v)) - \bm{\mu} \|_w^2\,, \end{align} where we seek for an optimal alignment (according to a weighted norm defined below) between the input eigenvalues $\bm{\mu}$ and the Hamiltonian eigenvalues $\bm{\lambda}$; the minimization is carried out over the space of non-negative potentials on $\mathcal{X}$. Problem \eqref{eq:prob} therefore models the input sequence $\bm{\mu}$ as the first $k$ eigenvalues of a Hamiltonian (whose potential $v$ we seek) constructed on $\mathcal{X}$. This allows us to model very general tasks in practice, as we show in our experiments. The $w$-norm used in Eq.~\eqref{eq:prob} is a weighted $L_2$ norm: \begin{align} \| \bm{\lambda} - \bm{\mu} \|_w^2 = \sum_{i=1}^k \frac{1}{\mu_i^2}(\lambda_i - \mu_i)^2\,, \end{align} where the weight $\frac{1}{\mu_i^2}$ balances the contribution of each term, thus avoiding unduly penalization of lower frequencies. \vspace{1ex}\noindent\textbf{Remark.} We emphasize that our objective is phrased entirely in terms of eigenvalues, while the eigenfunctions never appear explicitly. In the applications, we will show a remarkable property where alignment of eigenvalues also promotes alignment of the associated eigenfunctions. \vspace{1ex}\noindent\textbf{Algorithm.} Although the optimization problem in Eq. \eqref{eq:prob} is non-convex, it is still differentiable and we observed very good local optima by using standard numerical optimization methods. For example, projected gradient descent with step $\alpha>0$ can be easily implemented by the recursive relations: \begin{align*} \v^{(t)} \hspace{-0.1cm}&= \v^{(t-1)} \hspace{-0.065cm}-\hspace{-0.005cm} \Pi\left(\alpha \nabla \| \bm{\lambda}(\bm{\Delta}+\mathrm{diag}(\v^{(t-1)}))-\bm{\mu}\|^2_w\right)\nonumber\\ &=\v^{(t-1)} \hspace{-0.065cm}- \hspace{-0.005cm} \Pi\left( 2\alpha ( \bm{\Phi}^{(t-1)} \hspace{-0.04cm} \circ \bm{\Phi}^{(t-1)} ) ((\bm{\lambda}^{(t-1)}\hspace{-0.075cm}-\bm{\mu}){\scriptscriptstyle\oslash}\bm{\mu}^2) \right) \end{align*} Here, $\Pi(\mathbf{x})\equiv\max\{\mathbf{x},0\}$, with element-wise $\max$, is a projector onto $\mathbb{R}^n_+$; element-wise product and division are denoted by $\circ$ and $\scriptscriptstyle\oslash$ respectively. The matrix $\bm{\Phi}^{(t-1)}$ contains the eigenvectors of $\bm{\Delta}+\mathrm{diag}(\v^{(t-1)})$ as its columns; note that we do {\em not} optimize over these eigenvectors, but they appear naturally in the eigenvalue derivatives \cite{deigs}. To simplify even further, we consider the {\em unconstrained} problem \begin{align}\label{eq:prob2} \min_{\v\in\mathbb{R}^n} \| \bm{\lambda}(\bm{\Delta}_\mathcal{X} + \mathrm{diag}(\sigma(\v))) - \bm{\mu} \|_w^2\,, \end{align} where $\sigma(\v)= \frac{\tau}{2} (\tanh(\v) + 1)$ is a saturation function, acting element-wise, which maps the values of $\v$ to within the range $(0,\tau)$. This has the effect of promoting step potentials with height $\tau$, ensuring that all eigenfunctions with associated eigenvalue $\lambda_i<\tau$ will be confined within the region where $\sigma(v(x)) = 0$ (by Lemma~\ref{thm:step}). In our tests we simply set $\tau = 10 \, \mu_k $. We minimize problem~\eqref{eq:prob2} by a standard trust-region method implemented in Matlab. \section{Results} \vspace{-0.5ex} We showcase our eigenvalue alignment method on two distinct tasks. As we present these results, we also highlight some key properties of our technique that can be exploited in several applications. \subsection{Partial shape localization}\label{sec:local} As a first application, we consider the task of finding a region of a non-rigid shape from a partial (and possibly deformed) 3D query. Differently from prior work, we aim to do this without, at the same time, having to compute a map between full and partial shape. Let $\mathcal{X}$ and $\mathcal{Y}$ be the full and partial shapes, respectively, with the Laplacians $\Delta_\mathcal{X}$ and $\Delta_\mathcal{Y}$. Further, let $\{\mu_i\}_{i=1}^{k}$ be the first $k$ eigenvalues of $\Delta_\mathcal{Y}$. Our task is to find a region $\mathcal{R}\subseteq\mathcal{X}$ that corresponds to the partial query $\mathcal{Y}$ up to isometry. To solve this problem, we minimize Eq.~\eqref{eq:prob2} directly by using $\Delta_\mathcal{X}$ and $\{\mu_i\}$ as input. A local solution will be a potential function $v_\tau:\mathcal{X}\to(0,\tau)$ indicating the sought region $\mathcal{R}\subseteq\mathcal{X}$; see Figure~\ref{fig:examples} for qualitative examples. \begin{property} Our method is \textbf{correspondence-free}, since we never need to invoke the notion of a map $\pi:\mathcal{X}\to\mathcal{Y}$ in order to find the region $\mathcal{R}\subseteq\mathcal{X}$. In particular, we only operate with eigenvalue sequences $\{\lambda_i\},\{\mu_i\}$, which are invariant to point ordering (see Eq.~\eqref{eq:de}). \end{property} Given the property above, it is remarkable to observe that, at least empirically, aligning the (Hamiltonian) eigenvalues of $\mathcal{X}$ to the eigenvalues of $\mathcal{Y}$ provides a very strong prior that also induces an alignment of the associated {\em eigenfunctions}. This surprising property, illustrated in Figures~\ref{fig:puzzles} and \ref{fig:star}, is summarized below. \begin{property} Empirically, \textbf{eigenfunction alignment} is induced by our eigenvalue alignment. Formally, this means that $\lambda_i=\mu_i$ implies $\psi_i(x)=\phi_i(\pi(x))$ for all $x\in\mathcal{R}$ and an isometric map $\pi:\mathcal{R}\to\mathcal{Y}$. \label{thm:align} \end{property} We stress that the map $\pi$ is {\em not} solved for, and is not available to us after optimization. A similar property was also observed in \cite{isosp}, and might be a feature common to eigenvalue alignment approaches. A deeper comparison to \cite{isosp} will be provided in Section~\ref{sec:isosp}. Finally, invariance to deformations is put in evidence below: \begin{property} Since the eigenvalues of $\Delta_\mathcal{X}$ and $\Delta_\mathcal{Y}$ are \textbf{isometry-invariant}, so are all solutions to problem~\eqref{eq:prob2}. \end{property} The latter property suggests that other isometry-invariant methods from the shape analysis area might also be used for the same task. We now discuss the most relevant methods. \begin{figure}[t] \centering \input{./figures/IoU.tex} \caption{\label{fig:iou}Partial similarity comparisons. We compare with partial functional maps (PFM), a state-of-the-art partial shape matching method. We measure the intersection-over-union (IoU) between the regions identified by each method and the ground truth regions, and plot the cumulative scores over a set of 120 shape pairs.} \end{figure} \vspace{1ex}\noindent\textbf{Comparisons.} Partial shape matching methods such as \cite{bronstein2009partial,rodola2017partial,litany2016non} iteratively compute a map and a region. Such methods make use of regularization functionals for the region in order to reach a good solution. While our potential $v_\tau$ plays a similar role as the membership functions of these methods, we neither use any region regularizer, nor do we need to solve for a map. The fully spectral approach of Litany~\etal~\cite{litany2017fully} seeks for an optimal alignment between {\em eigenfunctions} rather than eigenvalues, thereby solving a pointwise matching problem in the process. We investigated extensively the effectiveness of our method in comparison with the state-of-the-art shape matching approach partial functional maps (PFM) \cite{rodola2017partial} on the SHREC'16 Partiality benchmark \cite{shrec16}, where PFM showed top performance. The dataset consists of 120 partial deformable shapes with large missing parts (`cuts' challenge), belonging to 8 sub-classes of humans and animals. The challenge is to locate each of the 120 partial shapes within a full template of the respective class (\eg, a dog in neutral pose). To make the setting even more challenging, we remeshed all the full models $\mathcal{X}$ to half of their density ($\sim$10$K$ to $\sim$5$K$ vertices) via edge collapse \cite{garland1997surface}, while keeping the partial shapes $\mathcal{Y}$ at their original resolution. This way, we eliminate the possibility for any method to work well by virtue of similar tessellation. For PFM we used public code released by the authors with default parameters. As a baseline, we also evaluate the co-segmentation approach of~\cite{toldo2009bag} with SHOT descriptors \cite{tombari2010unique}. Quantitative and qualitative comparisons are reported in Figure~\ref{fig:iou} and Figure~\ref{fig:pfm} respectively. % \begin{figure}[t] \centering \begin{overpic} [trim=0cm -0.5cm 0cm 0cm,clip,width=1.0\linewidth]{./figures/comparison_pfm.png} \put(17.3,31.3){\footnotesize 0.38} \put(68.5,31.3){\footnotesize 0.62} \put(17.3,0.5){\footnotesize 0.39} \put(68.5,0.5){\footnotesize 0.48} \put(37.1,31.3){\footnotesize \textbf{0.96}} \put(84.9,31.3){\footnotesize \textbf{0.96}} \put(37.1,0.5){\footnotesize \textbf{0.79}} \put(84.9,0.5){\footnotesize \textbf{0.77}} \end{overpic} \caption{\label{fig:pfm}Comparisons with PFM on the SHREC'16 benchmark. For each example we show the partial query, the PFM solution (orange), and our solution (green). The numerical score below each solution denotes the intersection-over-union with respect to the ground truth mask. Note how PFM tends to mix-up the bilateral symmetries of the shapes (left-right and front-back), since it relies on local descriptors that can not discriminate orientation.} \end{figure} \vspace{1ex}\noindent\textbf{Robustness to sampling.} Our method exhibits robustness to changes in resolution (see Figure~\ref{fig:sampling} for a full evaluation). We attribute this to the fact that eigenvalues are integral quantities (see Eq.~\ref{eq:de}). By contrast, PFM fully relies upon a data term based on local point descriptors, which are extremely sensitive to local meshing. \begin{figure*}[t] \centering \begin{overpic} [trim=0cm 0cm 0cm 0cm,clip,width=1.0\linewidth]{./figures/puzzle.pdf} \put(2.5,20.5){\footnotesize $\mathcal{Y}$} \put(2.5,7){\footnotesize $\mathcal{X}$} \put(5.5,10){\footnotesize $\color{white} v_\tau$} \put(20,25.5){\footnotesize $\phi_1$} \put(20,13){\footnotesize $\psi_1$} \put(30.5,25.5){\footnotesize $\phi_2$} \put(30.5,13){\footnotesize $\psi_2$} \put(41,25.5){\footnotesize $\phi_3$} \put(41,13){\footnotesize $\psi_3$} \put(51.5,25.5){\footnotesize $\phi_4$} \put(51.5,13){\footnotesize $\psi_4$} \put(62,25.5){\footnotesize $\phi_5$} \put(62,13){\footnotesize $\psi_5$} \put(79,4){\line(0,1){18}} \end{overpic} \caption{\label{fig:puzzles}Simultaneous localization of multiple disconnected regions. Given a query shape $\mathcal{Y}$ (here consisting of 3 pieces), our method solves for a potential $v_{\tau}: \mathcal{X} \to (0, \tau)$ which isolates the regions on $\mathcal{X}$ corresponding to $\mathcal{Y}$ up to isometry (leftmost column). By Property~\ref{thm:align}, the found $v_\tau$ induces alignment of the eigenfunctions (intermediate columns); we exploit this to easily associate a different label to each region. On the right we plot the identified regions with different colors. The rightmost column shows additional multi-piece examples.} \end{figure*} \begin{figure}[b] \centering \begin{overpic} [trim=0cm 0cm 0cm 0cm,clip,width=1.0\linewidth]{./figures/sampling_top.pdf} \put(40,29){\footnotesize $n=10K$} \put(77.5,29){\footnotesize $n=5K$} \end{overpic} \input{./figures/IoU_robustness.tex} \begin{overpic} [trim=0cm -1.5cm 0cm 0cm,clip,width=0.73\linewidth]{./figures/sampling_bottom.pdf} \put(05,1.7){\footnotesize PFM \cite{rodola2017partial}} \put(35,1.7){\footnotesize \textbf{Ours}} \put(54.5,1.7){\footnotesize PFM \cite{rodola2017partial}} \put(84.5,1.7){\footnotesize \textbf{Ours}} \end{overpic} \caption{\label{fig:sampling}Robustness to changes in vertex density. We show the results of PFM (in orange) and our method (in green) over two versions of the entire SHREC'16 dataset: a version where all meshes have similar resolution (dotted curves in the plots), and one where mild remeshing has been applied (solid curves). PFM shows a performance drop of 20\%, while our method remains stable.} \end{figure} \vspace{1ex}\noindent\textbf{Multiple pieces.} We highlight another useful property derived from working with potentials. In Figure~\ref{fig:puzzles} we show examples where the input 3D query consists of {\em multiple} disconnected parts (the ``non-rigid puzzle'' setting with non-overlapping pieces \cite{litany2016non}). By taking their union and treating them as one single shape $\mathcal{Y}$ in our optimization problem, we are still able to correctly identify the distinct portions on the full shape without any special adjustment to our algorithm. \vspace{1ex}\noindent\textbf{Implementation details.} In all our tests we use $k=20$ eigenvalues. As initialization for $\v$, we use Gaussians centered around $m=20$ Euclidean farthest samples on $\mathcal{X}$, with variance equal to $\sqrt{\mathrm{Area}(\mathcal{X})}$ and $2\sqrt{\mathrm{Area}(\mathcal{X})}$, leading to $2m$ different initializations which we optimize in parallel. To these, we also add the solutions produced by the baseline. To choose the final solution we rely on Property~\ref{thm:align}. For each found $v$, we compute projections of SHOT descriptors $F: \mathcal{X} \to \mathbb{R}$ over the first $5$ Hamiltonian eigenfunctions (squared), $c_{i} = \int_\mathcal{X} \psi_i^2(x) F(x) \mathrm{d}x$ for $i=1,\dots,5$. We then compute coefficients $d_i$ on $\mathcal{Y}$ similarly by using the Dirichlet eigenfunctions, and keep the $v$ which yields minimum distance $\sum_{i=1}^5 (d_i-c_i)^2$. By Property~\ref{thm:align}, we expect these coefficients to be the same for the correct solution. \subsection{Isospectralization}\label{sec:isosp} As a second application we address the shape-from-spectrum problem. This task was recently introduced in \cite{isosp} and is phrased as follows: Given as input a short sequence of Laplacian eigenvalues $\{\mu_i\}_{i=1}^{k}$ of an {\em unknown} shape $\mathcal{Y}$, recover a geometric embedding of $\mathcal{Y}$. We stress that the Laplacian $\Delta_\mathcal{Y}$ is {\em not} given; if given, it would lead to a shape-from-operator problem \cite{boscaini2015shape}. Instead, the goal here is to recover the shape directly from the eigenvalues alone. We model this problem by minimizing Eq.~\eqref{eq:prob2} with the following input. As full domain $\mathcal{X}$ we consider a finite portion of the plane $\mathcal{X}\subset\mathbb{R}^2$ of size $n\times n$, sampled on a Cartesian grid. The input eigenvalues $\{\mu_i\}$ are assumed to be coming from an unknown region $\mathcal{R}\subset\mathcal{X}$, which we identify by the potential $v_\tau$ on $\mathcal{X}$. Therefore, our optimization variables are simply $\v\in(0,\tau)^{n\times n}$ -- essentially, an image. \begin{property} We can recover shapes with \textbf{unknown topology}, \ie, no restricting assumptions are made on the topology of the sought shape. \label{thm:topo} \end{property} For example, if the shape to be recovered has holes, we do not need to know this fact beforehand to properly initialize the optimization. \vspace{1ex}\noindent\textbf{Comparisons.} In Figure~\ref{fig:isosp} we compare directly with the isospectralization technique of Cosmo~\etal~\cite{isosp}; to our knowledge, this is the only existing approach attempting to solve shape reconstruction purely from eigenvalues. Our method is different in many respects. The most crucial difference lies in the fact that in \cite{isosp} the authors optimize for a {\em deformation field} to apply to an initial template shape, which is assumed to be given as an input. In contrast, with Problem~\eqref{eq:prob2} we simply minimize over a vector space of scalar functions. The initial shape used in \cite{isosp} is also required to have the correct topology (\eg, disc-like or annulus-like), while by Property~\ref{thm:topo} our optimization is completely oblivious to the topology of the shape to recover. We illustrate this with an example in the rightmost column of Figure~\ref{fig:isosp}, where we directly compare with \cite{isosp}. Finally, optimizing over embedding coordinates as in \cite{isosp} requires the adoption of additional regularizers to avoid flipped triangles, and careful parameter tuning to avoid rough shapes and collapsing edges; this makes their energy more difficult to minimize, which is done using stochastic optimization tools \cite{kingma2014adam} and automatic differentiation as implemented in TensorFlow~\cite{tf}. By optimizing over scalar functions instead of deforming a given mesh, we do not encounter any of these issues; for this reason, our optimization can be made much simpler as detailed in Section~\ref{sec:method}. \begin{figure}[t] \centering \begin{overpic} [trim=0cm 0cm 0cm 0cm,clip,width=1.0\linewidth]{./figures/comparison_isosp2.pdf} \end{overpic} \caption{\label{fig:isosp}Shape recovery comparisons with \cite{isosp}. We show the ground truth shapes (blue outline) and our solutions (potential on the square, growing from white to red), all obtained in 2-3 minutes from $k=50$ input eigenvalues. We always use a constant initialization. On the bottom we show results for \cite{isosp} with their initial templates, which are required to always have the correct topology.} \end{figure} \begin{figure}[t] \centering \begin{overpic} [trim=0cm 0cm 0cm 0cm,clip,width=0.9\linewidth]{./figures/alignment.pdf} \put(-6.5,63.5){\footnotesize iter.} \put(-4.5,60.0){\footnotesize 0} \put(-4.5,56.0){\footnotesize $\downarrow$} \put(-7,7.0){\tiny ground} \put(-5.8,3.5){\tiny truth} \end{overpic} \caption{\label{fig:star}Shape recovery across iterations. Starting from a sequence of just $k=5$ Laplacian eigenvalues, our method recovers the correct shape in less than $1$ minute. The first column shows our solution, evolving from top to bottom. On the right we also show how the eigenfunctions (one per column) change across the iterations; observe how at convergence, they align with those of the ground truth shape (up to rotation).} \end{figure} \vspace{1ex}\noindent\textbf{Implementation details.} The planar domain $\mathcal{X}$ is discretized as a $30 \times 30$ grid with uniform triangles. We initialize simply with the constant potential $\v = \frac{\tau}{4} \mathbf{1}$, in order to emphasize the ability of our method to recover shape entirely from scratch irrespective of topology. We put this in contrast with \cite{isosp}, which needs an initial template as initialization, as mentioned above. See Figure~\ref{fig:star} for a visualization across some iterations of our optimization process. \section{Summary of our reasoning} \vspace{-0.5ex} \begin{figure}[t] \centering \setlength{\tabcolsep}{0pt} \begin{tabular}{ccc} \input{./figures/perc1.tex}& \input{./figures/perc2.tex}& \input{./figures/perc3.tex} \end{tabular} \begin{overpic} [trim=0cm -1.8cm 0cm 0cm,clip,width=1.0\linewidth]{./figures/statue_step.png} \end{overpic} \caption{\label{fig:stepwall}{\em Top}: A step potential $v_\tau$ (solid red) confines eigenfunction $\psi_i$ (solid blue) within the region where $v_\tau(x)=0$, as long as for the associated eigenvalue $\lambda_i$ (dashed gray) it holds $\lambda_i<\tau$. As soon as $\lambda_i \ge \tau$, a ``diffusion'' effect across the potential barrier takes place (rightmost plot). We illustrate this in $\mathbb{R}$ with three eigenfunctions at increasing eigenvalue (left to right). {\em Bottom}: We show the same phenomenon on a surface. Here, the potential with height $\tau$ is depicted on the left and is supported on the pedestal; observe the diffusion in the rightmost figure, due to the eigenvalue of the plotted eigenfunction being higher than $\tau$.} \end{figure} A classical result in mathematical physics \cite[Ch.~2]{griffiths} shows that the eigenfunctions $\psi_i$ of $H_\mathcal{X}$ exhibit {\em localization} depending not only on the geometry of the domain $\mathcal{X}$ \cite{heilman2010localized}, but also on the shape of the potential $v$. In this paper, we consider step potentials with finite height $\tau>0$: \begin{align}\label{eq:step} v_\tau(x) = \left\{ \begin{array}{ll} 0 & x\in \mathcal{R}\\ \tau & x\notin\mathcal{R}\end{array} \right. \end{align} for a given region $\mathcal{R}\subseteq\mathcal{X}$. The following lemma on the ``confinement'' property of step potentials is instrumental to our approach: \begin{lemma}[\!{\!\cite[Ch.~2.6]{griffiths}}] Let $\mathcal{R}\subseteq\mathcal{X}$ be a region of $\mathcal{X}$, and let $v_\tau:\mathcal{X}\to\{0,\tau\}$ be a finite step potential defined as in Eq.~\ref{eq:step}. Then, for the Hamiltonian $\Delta_\mathcal{X}+v_\tau$ all eigenfunctions $\psi_i$ with eigenvalue $\lambda_i<\tau$ vanish pointwise for $x\notin\mathcal{R}$. \label{thm:step} \end{lemma} According to Lemma~\ref{thm:step}, for large enough $\tau$, the Hamiltonian eigenfunctions will be entirely supported within $\mathcal{R}$. This result holds both on the real line (where the eigenfunctions are Fourier harmonics) and on manifolds\footnote{Berger \cite[p.403]{berger2012panoramic} described this analogy quite vividly, by depicting manifolds as ``quantum mechanical worlds''.}. We illustrate real examples of these facts in Figure \ref{fig:stepwall}. Key to our approach is the realization that the confined behavior or Hamiltonian eigenfunctions can be exploited by optimizing over the space of potentials $v_\tau$. We therefore establish the following lemma: \begin{lemma}[Eigenvalue equivalence] Let $\mathcal{R}\subseteq\mathcal{X}$ be a region of $\mathcal{X}$, and let $v_\tau:\mathcal{X}\to\{0,\tau\}$ be a finite step potential defined as in Eq.~\eqref{eq:step}. Now let $\{(\lambda_i,\psi_i)\}_{i=1}^{k}$ be $k$ eigenpairs of $\Delta_\mathcal{X}+v_\tau$, increasingly ordered and such that $\lambda_k<\tau$. If $(\mu_i,\phi_i)$ are the eigenpairs of $\Delta_{\mathcal{R}}$ computed with Dirichlet boundary conditions, then $\mu_i=\lambda_i$ for all $i=1,\dots,k$. \label{thm:diri} \end{lemma} \noindent\textbf{Sketch of proof.} For any eigenpair $(\lambda_i,\psi_i)$ of $\Delta_\mathcal{X}+v_\tau$ with $\lambda_i<\tau$, the following equality holds pointwise: \begin{align} \lambda_i \psi_i(x) &= \Delta_\mathcal{X}\psi_i(x) + v_\tau(x) \psi_i(x) \label{eq:l1} \\ &= \Delta_{\mathcal{R}}\psi_i(x) \label{eq:l2} \\ &= \mu_i\phi_i(x) \label{eq:l3} \,. \end{align} The equivalence~\eqref{eq:l2} follows directly from Lemma~\ref{thm:step}, since $\psi_i(x)$ vanishes for $x\notin\mathcal{R}$. Eq.~\eqref{eq:l3} stems from the homogeneous Dirichlet condition $\phi_i(x)=0$ for $x\in\partial\mathcal{R}$. \hfill $\square$ \vspace{1ex} An illustration of this result is given in Figure~\ref{fig:dirichlet}. Lemma~\ref{thm:diri} establishes that one can measure the Dirichlet eigenvalues of a partial shape $\mathcal{R}$ equivalently by measuring Hamiltonian eigenvalues over the complete shape $\mathcal{X}$ -- provided that an indicator for the corresponding region on $\mathcal{X}$ is given. This gives us a straightforward way to implement localization via optimization over the cone of non-negative real-valued functions on $\mathcal{X}$. Problem~\eqref{eq:prob} in the next Section formalizes precisely this idea. \begin{figure}[t] \centering \begin{overpic} [trim=0cm -1.8cm 0cm 0cm,clip,width=1.0\linewidth]{./figures/frog.png} \put(-4,24.5){\footnotesize $+1$} \put(-1,19.5){\footnotesize $0$} \put(-4,14.5){\footnotesize $-1$} \put(6,1){\footnotesize $v_\tau:\mathcal{X}\to\{0,\tau\}$} \put(44,22){\footnotesize $\mathcal{X}$} \put(73,22){\footnotesize $\mathcal{R}\subset\mathcal{X}$} \put(52,1){\footnotesize $(\lambda_5,\psi_5)$} \put(85,1){\footnotesize $(\mu_5,\phi_5)$} \end{overpic} \caption{\label{fig:dirichlet}{\em Left}: Given a region $\mathcal{R}$ (the face of the frog), we show the step potential $v_\tau$ such that $v_\tau(x)=0$ for $x\in\mathcal{R}$, and $v_\tau(x)=\tau$ otherwise. {\em Middle}: The eigenfunctions $\psi_i$ of the Hamiltonian $\Delta_\mathcal{X}+v_\tau$ are localized on $\mathcal{R}$, meaning that $\psi_i(x)\approx 0$ for $x\notin\mathcal{R}$. {\em Right}: If the region $\mathcal{R}$ is taken as a separate mesh with boundary $\partial\mathcal{R}$ (depicted in green), the Dirichlet eigenfunction $\phi_i$ of $\Delta_\mathcal{R}$ has the same values as $\psi_i$ at corresponding points. As a consequence, $\lambda_i=\mu_i$.} \end{figure} \section*{Acknowledgments} \vspace{-1.5ex} \noindent The authors wish to thank Luca Cosmo, Luca Balsanelli and Jing Ren for useful discussions and the technical help. AR and ER are supported by the ERC Starting Grant no. 802554 (SPECGEO). Parts of this work were supported by the KAUST OSR Award No. CRG-2017-3426, a gift from the NVIDIA Corporation and the ERC Starting Grant No. 758800 (EXPROTEA). } {\small \bibliographystyle{ieee} \section{Background} \vspace{-0.5ex} In this paper we model shapes as 2-dimensional Riemannian manifolds $\mathcal{X}$ (possibly with boundary $\partial\mathcal{X}$) equipped with the area element $\mathrm{d}x$. We denote by $\mathrm{int}(\mathcal{X})$ the interior of $\mathcal{X}$, namely the set of points $\mathcal{X}\setminus\partial\mathcal{X}$. \vspace{1ex}\noindent\textbf{Laplacian.} The positive semi-definite Laplace-Beltrami operator $\Delta_\mathcal{X}$ (or manifold Laplacian) generalizes the basic differential operator from Euclidean analysis to Riemannian manifolds. It admits a spectral decomposition \begin{align} \Delta_\mathcal{X} \phi_i(x) &= \mu_i \phi_i(x) &x\in\mathrm{int}(\mathcal{X}) \label{eq:eig} \\ \phi_i(x) &=0 &x\in\partial\mathcal{X}\,,\label{eq:d} \end{align} with homogeneous Dirichlet boundary conditions \eqref{eq:d}, where $\{ 0<\mu_1 \leq \mu_2 \leq \dots \}$ are the eigenvalues (each with finite multiplicity) and $\phi_i$ are the associated eigenfunctions. For the remainder of the paper, we always assume eigenvalues to be increasingly ordered. The {\em spectrum} of $\Delta_\mathcal{X}$ is the set of all eigenvalues, forming a discrete subset of $\mathbb{R}_+$. It encodes geometric and topological properties of $\mathcal{X}$; for instance, it has been used as a basic global shape descriptor for 3D shape retrieval \cite{reuter2006laplace}. A direct consequence of Eq.~\eqref{eq:eig} is that each eigenvalue $\mu_i$ is associated to an eigenfunction $\phi_i$ by the equality\footnote{In this equality we use the intrinsic gradient operator $\nabla_\mathcal{X}$ acting on scalar functions $f:\mathcal{X}\to\mathbb{R}$, which defines the direction (tangent to the surface) of the steepest change of $f$ around each point $x\in\mathcal{X}$.} \begin{align}\label{eq:de} \mu_i = \int_\mathcal{X} \| \nabla_\mathcal{X} \phi_i (x) \|^2_2 \,\mathrm{d}x \end{align} after normalization so that $\int_\mathcal{X} \phi_i^2(x) \mathrm{d}x =1$. Equation~\eqref{eq:de} makes the {\em global} nature of the eigenvalues clear, since they are computed as integrals over the entire surface. \vspace{1ex}\noindent\textbf{Hamiltonian operator.} Given a scalar {\em potential} function $v:\mathcal{X}\to\mathbb{R}_+$, one can define a Hamiltonian $H_\mathcal{X} = \Delta_\mathcal{X} + v$, operating on scalar functions $f$ as follows: \begin{align} H_\mathcal{X} f = \Delta_\mathcal{X} f + v f\,, \end{align} where the product $vf$ is taken point-wise. Trivially, for the null potential where $v(x)=0 ~~\forall x\in\mathcal{X}$, the Hamiltonian $H_\mathcal{X}$ simplifies to $\Delta_\mathcal{X}$. The operator $H_\mathcal{X}$ also admits a spectral decomposition: \begin{align} H_\mathcal{X} \psi_i(x) = \lambda_i \psi_i(x)\,, \end{align} with boundary conditions when necessary. Hamiltonian eigenfunctions have been used in shape analysis applications in \cite{choukroun2018hamiltonian,melzi2018localized,rodola2019functional}. \vspace{1ex} \setlength{\columnsep}{7pt} \setlength{\intextsep}{1pt} \begin{wrapfigure}[4]{r}{0.23\linewidth} \vspace{-0.6cm} \begin{center} \begin{overpic} [trim=0cm 0cm 0cm 0cm,clip,width=1.0\linewidth]{./figures/notation.pdf} \put(29,96){\footnotesize $h$} \put(34,45){\footnotesize $i$} \put(100,28){\footnotesize $k$} \put(93,77){\footnotesize $j$} \put(48,80){\footnotesize $\alpha_{ij}$} \put(72,45){\footnotesize $\beta_{ij}$} \end{overpic} \end{center} \end{wrapfigure} \noindent\textbf{Discretization.} In the discrete setting, $\mathcal{X}$ is approximated by a triangle mesh with $n$ vertices $v_i\in V_\mathrm{int} \cup V_\mathrm{bdr}$, and where each edge $e_{ij}\in E_\mathrm{int} \cup E_\mathrm{bdr}$ belongs to at most two triangle faces $F_{ijk}$ and $F_{jih}$ (see inset for notation). We use the subscripts $\mathrm{int}$ and $\mathrm{bdr}$ on vertices and edges to denote interior and boundary, respectively. The Laplacian is defined in terms of two $n\times n$ matrices $\mathbf{W}$ and $\mathbf{A}$, where $\mathbf{A}$ is a diagonal matrix of local area elements $a_i$ and $\mathbf{W}$ is a symmetric matrix of edge-wise weights (also known as cotangent formula, see \eg \cite{meyer2003discrete}): \begin{eqnarray} \label{eq:cotan} w_{ij} \hspace{-0.3cm} &=& \hspace{-0.4cm} \left\{ \begin{array}{lc} {\scriptstyle -(\cot \alpha _{ij} + \cot \beta _{ij})/2} & {\scriptstyle e_{ij} \in E_\mathrm{int};} \\ {\scriptstyle 0} & {\scriptstyle (i\neq j) \wedge (i \in V_\mathrm{bdr} \vee j \in V_\mathrm{bdr})}; \\ {\scriptstyle \sum_{k\neq i} (\cot \alpha _{ik} + \cot \beta _{ik})/2} & {\scriptstyle (i = j) \wedge v_i\in V_\mathrm{int};} \\ {\scriptstyle 1} & {\scriptstyle (i = j) \wedge v_i\in V_\mathrm{bdr};} \end{array} \right.\\ a_i \hspace{-0.3cm} &=& \hspace{-0.4cm} \left\{ \begin{array}{lc} \frac{1}{3}\sum_{jk:ijk\in F} A_{ijk} & v_i \in V_\mathrm{int}; \\ 0 & v_i \in V_\mathrm{bdr}; \end{array} \right. \end{eqnarray} where $A_{ijk}$ is the area of triangle $F_{ijk}$. In the formulas above, the special treatment of boundary edges and vertices imposes the Dirichlet boundary conditions of Eq.~\eqref{eq:d}. A generalized eigenproblem $\mathbf{W}\bm{\Phi} = \mathbf{A}\bm{\Phi}\mathrm{diag}(\bm{\mu})$ is solved for computing the Laplacian eigenvalues and eigenvectors. In the case of the Hamiltonian, it takes the form \begin{align}\label{eq:eigs} (\mathbf{W}+\mathbf{A}\mathrm{diag}(\v))\bm{\Psi} = \mathbf{A}\bm{\Psi}\mathrm{diag}(\bm{\lambda})\,. \end{align} Above, $\mathbf{v}$ is a $n$-dimensional vector containing the values of the potential $v$ at each vertex, $\bm{\Phi}$ and $\bm{\Psi}$ are matrices containing the first $k$ eigenvectors as their columns, and $\bm{\lambda},\bm{\mu}$ are the corresponding $k$-dimensional vectors of eigenvalues. For brevity, we will write $\bm{\lambda}(\bm{\Delta}_\mathcal{X}+\mathrm{diag}(\v))$ to denote the eigenvalues appearing in Eq.~\eqref{eq:eigs}. \section{Conclusions} \vspace{-0.5ex} In this paper we presented a new approach for partial shape similarity, based on aligning short sequences of eigenvalues computed on the given shapes. Our approach is correspondence-free, is invariant to non-rigid transformations, it can be solved efficiently, and only makes use of descriptors for post-processing refinement. Our formulation is also general enough to be applied to other relevant tasks in vision and graphics. We demonstrated this on a challenging shape-from-spectrum recovery problem, where it compares favorably with respect to a very recent method. % \begin{figure}[bt] \centering \begin{overpic} [trim=0cm 0cm 0cm 0cm,clip,width=0.85\linewidth]{./figures/fail.png} \put(0,16.5){\footnotesize 0.51} \put(51,16.5){\footnotesize 0.13} \end{overpic} \begin{overpic} [trim=0cm 0cm 0cm -2.0cm,clip,width=0.85\linewidth]{./figures/fail_2D.pdf} \end{overpic} \caption{\label{fig:fail}Failure cases. {\em Top}: On the left example, the eigenvalues did not align well at the local optimum; as a result, the partial shape was localized only roughly. On the right, the found region is wrongly classified as correct since it has similar eigenvalues to the partial input within the limited bandwidth. In both cases we report the IoU. {\em Bottom}: Shape-from-spectrum recovery of shapes with non-trivial topology can be difficult to achieve, due to the narrow bandwidth and first-order discretization of the operators.} \end{figure} \vspace{1ex}\noindent\textbf{Limitations and future work.} We did observe some failure cases during our tests (see Figure~\ref{fig:fail}). In the partial similarity setting, this typically happens whenever the chosen bandwidth (\ie, the number $k$ of input eigenvalues) is too small for discriminating regions that only differ at medium-high frequencies; \eg, a human arm might be confused with a leg. This can be remedied to some extent by increasing the value of $k$. For large values ($k>100$), however, a more accurate discretization of the operator $\Delta$ should be used in place of the cotangent formulas of Eq.~\eqref{eq:cotan}, to avoid artifacts related to mesh tessellation. Using second- or third-order FEM discretization \cite{ciarlet2002finite} might be a promising solution. Furthermore, while we only showed 2D examples of shape-from-spectrum recovery, the exact same algorithm can be used invariantly for reconstructing the geometry of 3D (volumetric) shapes. However, this would require solving for a potential defined in $\mathbb{R}^3$, for which efficient data structures (such as octrees) could be necessary. We leave this exciting possibility to future work. Finally, a theoretical question that we left open concerns the empirical observation that eigenfunction alignment is induced in many practical situations. We believe that this requires a deeper understanding, with potentially profound consequences in many applied domains. \section{Introduction} \vspace{-0.5ex} Assessing similarity between non-rigid shapes is an active research topic in computer vision, pattern recognition and graphics \cite{biasotti2016recent}. At the heart of such methods lies the definition of shape {\em descriptors}, characterizing the shape either locally or globally (\eg, via the Bag-of-Words \cite{toldo2009bag} paradigm or via deep learning \cite{monti2017geometric}). Deformation-invariant shape descriptors often require careful tuning and hand-crafting, or sufficient training examples to enable learned-based methods. While similarity by itself is usually expressed by a numerical score, the problem as a whole is also strictly related to (and often solved in tandem with) the complementary problem of shape {\em correspondence}. In this setting, local shape descriptors are used as `probe' quantities to employ in more sophisticated pipelines to infer a functional \cite{rodola2017partial} or point-to-point \cite{bronstein2009partial} correspondence. \begin{figure}[t!] \centering \begin{overpic} [trim=0cm 0cm 0cm 0cm,clip,width=0.22\linewidth]{./figures/teaser/target.png} \put(34,56){\footnotesize $\mathcal{X}$} \end{overpic} \begin{overpic} [trim=0cm 0cm 0cm 0cm,clip,width=0.36\linewidth]{./figures/teaser/init.png} \put(58,43){\footnotesize $\mathcal{Y}$} \end{overpic}\\ % \begin{overpic} [trim=0cm -3cm 0cm 0cm,clip,width=0.32\linewidth]{./figures/teaser/middle1.png} \put(41,0.9){\footnotesize iteration 10} \put(59.5,55){\footnotesize $\color{white} v$} \end{overpic} \begin{overpic} [trim=0cm -3cm 0cm 0cm,clip,width=0.32\linewidth]{./figures/teaser/middle.png} \put(41,0.9){\footnotesize iteration 30} \put(59.5,55){\footnotesize $\color{black} v$} \end{overpic} \begin{overpic} [trim=0cm -3cm 0cm 0cm,clip,width=0.32\linewidth]{./figures/teaser/end.png} \put(41,0.9){\footnotesize iteration 60} \put(59.5,55){\footnotesize $\color{black} v^\ast$} \end{overpic} \setlength{\tabcolsep}{0pt} \begin{tabular}{ccc} \input{./figures/teaser/eig_middle1.tex}& \input{./figures/teaser/eig_middle.tex}& \input{./figures/teaser/eig_end.tex} \end{tabular} \caption{\label{fig:teaser} Given a non-rigid partial 3D query $\mathcal{X}$ and a full shape $\mathcal{Y}$, we propose a way to locate $\mathcal{X}$ in $\mathcal{Y}$ without having to compute a correspondence $\pi:\mathcal{X}\to\mathcal{Y}$. We do so by looking for an indicator function $v$ on $\mathcal{Y}$ which, when used to construct a Laplacian-like matrix on $\mathcal{Y}$, its eigenvalues become the same as those of the classical Laplacian on $\mathcal{X}$. The optimal $v^\ast$ attaining the eigenvalue alignment localizes the sought region. Here we show the evolution of $v$ (middle row) and of the corresponding eigenvalues (bottom row) across our iterative algorithm until convergence. } \end{figure} Even more challenging is the setting of {\em partial} shape similarity, which is the focus of this paper. In this case, only some {\em regions} of the shapes are expected to be similar due to the presence of clutter or missing geometry. Partial similarity arises in numerous practical tasks, ranging from object reassembly \cite{gregor2014towards,litany2016non} to protein docking \cite{shentu2008context} and deformable object-in-clutter detection \cite{cosmo2016matching} among others. In the partial setting, in addition to defining a similarity metric, one also has to identify the relevant similar regions of the given shapes, which is a difficult problem in itself (see Figure~\ref{fig:teaser}). As a result, while global similarity has been extensively studied, only few methods exist to address the (especially non-rigid) partial 3D similarity problem. A seemingly unrelated problem concerns the recovery of the geometry of an unknown shape (\ie, whose point coordinates in space are not given) from a minimal amount of input data. Notably, it has been recently shown \cite{isosp} that, in some cases, one can reconstruct the geometry of a shape even when an incomplete sequence of its Laplacian eigenvalues (its spectrum) are given as an input -- a problem widely known in mathematical physics as ``hearing the shape of the drum''~\cite{kac}. In vision and graphics, this problem finds applications in non-isometric shape matching as well as style transfer \cite{isosp} and acoustics design \cite{bharaj2015computational}. In this paper we show that partial shape similarity and shape-from-spectrum recovery, while apparently very distinct, can be phrased as instances of the same mathematical problem. We formulate this problem by exploiting the notion of the Hamiltonian operator on manifolds, and reduce it to an unconstrained continuous optimization problem over the vector space of real-valued functions defined over the surfaces; see Figure~\ref{fig:teaser} for an illustration of our methodology on a real example. \subsection{Related work}\label{sec:rel} Partial similarity of 3D shapes has long been researched by the vision and geometry processing communities, with the vast majority tackling the {\em rigid} setting. Since the focus of this work is on {\em non-rigid} structures, we discuss methods addressing deformable objects here, and refer the interested reader to the recent surveys \cite{sipiran2013shrec,pratikakis2016partial,phamshrec} for the former case. \vspace{1ex}\noindent\textbf{Partial shape retrieval.} At a high level our task is related to shape retrieval, where the goal is to produce a {\em ranking} of most similar shapes according to a similarity score. Even in this simpler task, surprisingly few methods have attempted to address the problem. We mention here the recent SHREC'17 challenge \cite{shrec17}, highlighting how deep learning-based methods may work well for producing rankings, provided that enough training examples are available (the organizers provided around two thousands). Our task is more challenging, as we aim at identifying the regions that two non-rigid objects have in common. \vspace{1ex}\noindent\textbf{Partial shape correspondence.} When a map $\pi:\mathcal{X}\to\mathcal{Y}$ between shapes $\mathcal{X}$ and $\mathcal{Y}$ is available, one may simply look at the image $\pi(\mathcal{X})\subset\mathcal{Y}$ in order to determine the corresponding region (for simplicity, here we assume that $\mathcal{X}$ is a deformed region of $\mathcal{Y}$ as in Figure~\ref{fig:teaser}). Thus, any partial shape matching method implicitly solves for the common region as a side product, at the cost of solving a computationally heavy correspondence problem. To date, solving a full correspondence problem is therefore the dominant approach. Bronstein~\etal \cite{bronstein2009partial} proposed to explicitly solve for a point-to-point map $\pi$ and a membership function $\mu$ (or ``fuzzy part'', measuring the degree of inclusion of each point into the subset), optimizing for $\pi$ and $\mu$ in an alternating fashion. Optimization for $\pi$ was posed as a NP-hard quadratic assignment problem \cite{burkard1998quadratic}, while solving for $\mu$ required solving a non-convex quadratic problem due to the presence of region regularizers. More recently, Rodol\`a~\etal \cite{rodola2017partial} followed a similar approach where the correspondence step was rephrased using the functional map representation \cite{ovsjanikov2012functional}. A membership function is still optimized for, with the same regularizers as those in \cite{bronstein2009partial}. The framework was extended in \cite{litany2016non} to address the case with $n>2$ regions (``non-rigid puzzle''), leading to a multi-label segmentation problem where $n$ functional maps are optimized simultaneously. The presence of clutter was investigated in \cite{cosmo2016matching} using the same formulation of \cite{rodola2017partial}, but where the local descriptors (which are used in all the methods above to drive the correspondence) are learned via deep metric learning on a representative dataset. Finally, Brunton~\etal \cite{brunton2014low} proposed an iterative approach where a partial map is recovered by an isometric growing procedure starting from sparse pre-matched features over the surfaces. In contrast to these methods, our approach does not require solving for dense correspondences, thus essentially eliminating the need for local descriptors, and does not make use of complex regularizers. Instead, we phrase the optimization problem in terms of solving for a real-valued (indicator) function aimed at identifying similar regions, and devise a correspondence-free metric that allows us to measure and optimize for the similarity of such functions directly. A related approach was previously introduced by Pokrass~\etal \cite{pokrass2013partial} for identifying region-wise similarity. However, unlike our method, that approach relies on the comparison of \emph{descriptor} statistics over the surface, thus strongly depending on the specific choice of descriptors. \vspace{1ex}\noindent\textbf{Isospectralization.} From an algebraic standpoint, ours may be seen as an ``inverse eigenvalue problem''~\cite{chu2005inverse}; despite the name, problems in this domain typically require knowledge of the eigenvectors of the sought operator, while our method does not. Perhaps, the most closely related to ours is the recent work on \emph{isospectralization} \cite{isosp} where the authors deform the shapes with the goal of aligning their Laplacian eigenvalues. We also use a similar observation that in practice these eigenvalues provide a powerful characterization of the shape's geometry. However, we focus on the partial setting and propose to solve for a characteristic function of a region, thus avoiding any explicit shape deformation. \subsection{Contribution} The key contribution of this paper is to show that for many practical problems, it is possible to side-step the need for a correspondence by looking at the eigenvalues of certain differential operators constructed on each surface. This leads to tangible consequences that we leverage in two challenging applications. Specifically, \begin{itemize} \item We introduce a new method for detecting similar regions among deformable shapes; for the first time, the optimization is completely {\em correspondence-free} and, at its core, descriptor-free \item Our optimization problem uses a single objective, thus avoiding possibly complex regularizers, and can be solved {\em efficiently} with off-the-shelf differentiable programming libraries; \item We provide a remarkably simple alternative to recent {\em isospectralization} techniques \cite{isosp}, while at the same time yielding qualitatively better results at a fraction of the time cost. \end{itemize} \section{Our method}\label{sec:method} \vspace{-0.5ex} We first present and discuss our general formulation, and then demonstrate its application to two separate tasks in Sections~\ref{sec:local} and \ref{sec:isosp}. The main idea behind our approach is to model regions $\mathcal{R}\subset\mathcal{X}$ via potential functions, rather than by explicitly manipulating points $x\in\mathcal{R}$. Further, similarly to \cite{isosp}, we rely upon the empirical observation that, in many practical cases, the Laplacian eigenvalues encode the geometry of the domain \vspace{1ex}\noindent\textbf{Optimization problem.} Our input is a given shape $\mathcal{X}$ and, separately, an increasing sequence of $k$ Dirichlet eigenvalues stored in a vector $\bm{\mu}\in\mathbb{R}^{k}$. The precise source of these eigenvalues is {\em not known}, but they are assumed to come from a manifold Laplacian. It is our task to identify the shape of this domain. To do so, we consider the following {\em eigenvalue alignment} problem: \begin{align}\label{eq:prob} \min_{\v\ge 0} \| \bm{\lambda}(\bm{\Delta}_\mathcal{X} + \mathrm{diag}(\v)) - \bm{\mu} \|_w^2\,, \end{align} where we seek for an optimal alignment (according to a weighted norm defined below) between the input eigenvalues $\bm{\mu}$ and the Hamiltonian eigenvalues $\bm{\lambda}$; the minimization is carried out over the space of non-negative potentials on $\mathcal{X}$. Problem \eqref{eq:prob} therefore models the input sequence $\bm{\mu}$ as the first $k$ eigenvalues of a Hamiltonian (whose potential $v$ we seek) constructed on $\mathcal{X}$. This allows us to model very general tasks in practice, as we show in our experiments. The $w$-norm used in Eq.~\eqref{eq:prob} is a weighted $L_2$ norm: \begin{align} \| \bm{\lambda} - \bm{\mu} \|_w^2 = \sum_{i=1}^k \frac{1}{\mu_i^2}(\lambda_i - \mu_i)^2\,, \end{align} where the weight $\frac{1}{\mu_i^2}$ balances the contribution of each term, thus avoiding unduly penalization of lower frequencies. \vspace{1ex}\noindent\textbf{Remark.} We emphasize that our objective is phrased entirely in terms of eigenvalues, while the eigenfunctions never appear explicitly. In the applications, we will show a remarkable property where alignment of eigenvalues also promotes alignment of the associated eigenfunctions. \vspace{1ex}\noindent\textbf{Algorithm.} Although the optimization problem in Eq. \eqref{eq:prob} is non-convex, it is still differentiable and we observed very good local optima by using standard numerical optimization methods. For example, projected gradient descent with step $\alpha>0$ can be easily implemented by the recursive relations: \begin{align*} \v^{(t)} \hspace{-0.1cm}&= \v^{(t-1)} \hspace{-0.065cm}-\hspace{-0.005cm} \Pi\left(\alpha \nabla \| \bm{\lambda}(\bm{\Delta}+\mathrm{diag}(\v^{(t-1)}))-\bm{\mu}\|^2_w\right)\nonumber\\ &=\v^{(t-1)} \hspace{-0.065cm}- \hspace{-0.005cm} \Pi\left( 2\alpha ( \bm{\Phi}^{(t-1)} \hspace{-0.04cm} \circ \bm{\Phi}^{(t-1)} ) ((\bm{\lambda}^{(t-1)}\hspace{-0.075cm}-\bm{\mu}){\scriptscriptstyle\oslash}\bm{\mu}^2) \right) \end{align*} Here, $\Pi(\mathbf{x})\equiv\max\{\mathbf{x},0\}$, with element-wise $\max$, is a projector onto $\mathbb{R}^n_+$; element-wise product and division are denoted by $\circ$ and $\scriptscriptstyle\oslash$ respectively. The matrix $\bm{\Phi}^{(t-1)}$ contains the eigenvectors of $\bm{\Delta}+\mathrm{diag}(\v^{(t-1)})$ as its columns; note that we do {\em not} optimize over these eigenvectors, but they appear naturally in the eigenvalue derivatives \cite{deigs}. To simplify even further, we consider the {\em unconstrained} problem \begin{align}\label{eq:prob2} \min_{\v\in\mathbb{R}^n} \| \bm{\lambda}(\bm{\Delta}_\mathcal{X} + \mathrm{diag}(\sigma(\v))) - \bm{\mu} \|_w^2\,, \end{align} where $\sigma(\v)= \frac{\tau}{2} (\tanh(\v) + 1)$ is a saturation function, acting element-wise, which maps the values of $\v$ to within the range $(0,\tau)$. This has the effect of promoting step potentials with height $\tau$, ensuring that all eigenfunctions with associated eigenvalue $\lambda_i<\tau$ will be confined within the region where $\sigma(v(x)) = 0$ (by Lemma~\ref{thm:step}). In our tests we simply set $\tau = 10 \, \mu_k $. We minimize problem~\eqref{eq:prob2} by a standard trust-region method implemented in Matlab. \section{Results} \vspace{-0.5ex} We showcase our eigenvalue alignment method on two distinct tasks. As we present these results, we also highlight some key properties of our technique that can be exploited in several applications. \subsection{Partial shape localization}\label{sec:local} As a first application, we consider the task of finding a region of a non-rigid shape from a partial (and possibly deformed) 3D query. Differently from prior work, we aim to do this without, at the same time, having to compute a map between full and partial shape. Let $\mathcal{X}$ and $\mathcal{Y}$ be the full and partial shapes, respectively, with the Laplacians $\Delta_\mathcal{X}$ and $\Delta_\mathcal{Y}$. Further, let $\{\mu_i\}_{i=1}^{k}$ be the first $k$ eigenvalues of $\Delta_\mathcal{Y}$. Our task is to find a region $\mathcal{R}\subseteq\mathcal{X}$ that corresponds to the partial query $\mathcal{Y}$ up to isometry. To solve this problem, we minimize Eq.~\eqref{eq:prob2} directly by using $\Delta_\mathcal{X}$ and $\{\mu_i\}$ as input. A local solution will be a potential function $v_\tau:\mathcal{X}\to(0,\tau)$ indicating the sought region $\mathcal{R}\subseteq\mathcal{X}$; see Figure~\ref{fig:examples} for qualitative examples. \begin{property} Our method is \textbf{correspondence-free}, since we never need to invoke the notion of a map $\pi:\mathcal{X}\to\mathcal{Y}$ in order to find the region $\mathcal{R}\subseteq\mathcal{X}$. In particular, we only operate with eigenvalue sequences $\{\lambda_i\},\{\mu_i\}$, which are invariant to point ordering (see Eq.~\eqref{eq:de}). \end{property} Given the property above, it is remarkable to observe that, at least empirically, aligning the (Hamiltonian) eigenvalues of $\mathcal{X}$ to the eigenvalues of $\mathcal{Y}$ provides a very strong prior that also induces an alignment of the associated {\em eigenfunctions}. This surprising property, illustrated in Figures~\ref{fig:puzzles} and \ref{fig:star}, is summarized below. \begin{property} Empirically, \textbf{eigenfunction alignment} is induced by our eigenvalue alignment. Formally, this means that $\lambda_i=\mu_i$ implies $\psi_i(x)=\phi_i(\pi(x))$ for all $x\in\mathcal{R}$ and an isometric map $\pi:\mathcal{R}\to\mathcal{Y}$. \label{thm:align} \end{property} We stress that the map $\pi$ is {\em not} solved for, and is not available to us after optimization. A similar property was also observed in \cite{isosp}, and might be a feature common to eigenvalue alignment approaches. A deeper comparison to \cite{isosp} will be provided in Section~\ref{sec:isosp}. Finally, invariance to deformations is put in evidence below: \begin{property} Since the eigenvalues of $\Delta_\mathcal{X}$ and $\Delta_\mathcal{Y}$ are \textbf{isometry-invariant}, so are all solutions to problem~\eqref{eq:prob2}. \end{property} The latter property suggests that other isometry-invariant methods from the shape analysis area might also be used for the same task. We now discuss the most relevant methods. \begin{figure}[t] \centering \input{./figures/IoU.tex} \caption{\label{fig:iou}Partial similarity comparisons. We compare with partial functional maps (PFM), a state-of-the-art partial shape matching method. We measure the intersection-over-union (IoU) between the regions identified by each method and the ground truth regions, and plot the cumulative scores over a set of 120 shape pairs.} \end{figure} \vspace{1ex}\noindent\textbf{Comparisons.} Partial shape matching methods such as \cite{bronstein2009partial,rodola2017partial,litany2016non} iteratively compute a map and a region. Such methods make use of regularization functionals for the region in order to reach a good solution. While our potential $v_\tau$ plays a similar role as the membership functions of these methods, we neither use any region regularizer, nor do we need to solve for a map. The fully spectral approach of Litany~\etal~\cite{litany2017fully} seeks for an optimal alignment between {\em eigenfunctions} rather than eigenvalues, thereby solving a pointwise matching problem in the process. We investigated extensively the effectiveness of our method in comparison with the state-of-the-art shape matching approach partial functional maps (PFM) \cite{rodola2017partial} on the SHREC'16 Partiality benchmark \cite{shrec16}, where PFM showed top performance. The dataset consists of 120 partial deformable shapes with large missing parts (`cuts' challenge), belonging to 8 sub-classes of humans and animals. The challenge is to locate each of the 120 partial shapes within a full template of the respective class (\eg, a dog in neutral pose). To make the setting even more challenging, we remeshed all the full models $\mathcal{X}$ to half of their density ($\sim$10$K$ to $\sim$5$K$ vertices) via edge collapse \cite{garland1997surface}, while keeping the partial shapes $\mathcal{Y}$ at their original resolution. This way, we eliminate the possibility for any method to work well by virtue of similar tessellation. For PFM we used public code released by the authors with default parameters. As a baseline, we also evaluate the co-segmentation approach of~\cite{toldo2009bag} with SHOT descriptors \cite{tombari2010unique}. Quantitative and qualitative comparisons are reported in Figure~\ref{fig:iou} and Figure~\ref{fig:pfm} respectively. % \begin{figure}[t] \centering \begin{overpic} [trim=0cm -0.5cm 0cm 0cm,clip,width=1.0\linewidth]{./figures/comparison_pfm.png} \put(17.3,31.3){\footnotesize 0.38} \put(68.5,31.3){\footnotesize 0.62} \put(17.3,0.5){\footnotesize 0.39} \put(68.5,0.5){\footnotesize 0.48} \put(37.1,31.3){\footnotesize \textbf{0.96}} \put(84.9,31.3){\footnotesize \textbf{0.96}} \put(37.1,0.5){\footnotesize \textbf{0.79}} \put(84.9,0.5){\footnotesize \textbf{0.77}} \end{overpic} \caption{\label{fig:pfm}Comparisons with PFM on the SHREC'16 benchmark. For each example we show the partial query, the PFM solution (orange), and our solution (green). The numerical score below each solution denotes the intersection-over-union with respect to the ground truth mask. Note how PFM tends to mix-up the bilateral symmetries of the shapes (left-right and front-back), since it relies on local descriptors that can not discriminate orientation.} \end{figure} \vspace{1ex}\noindent\textbf{Robustness to sampling.} Our method exhibits robustness to changes in resolution (see Figure~\ref{fig:sampling} for a full evaluation). We attribute this to the fact that eigenvalues are integral quantities (see Eq.~\ref{eq:de}). By contrast, PFM fully relies upon a data term based on local point descriptors, which are extremely sensitive to local meshing. \begin{figure*}[t] \centering \begin{overpic} [trim=0cm 0cm 0cm 0cm,clip,width=1.0\linewidth]{./figures/puzzle.pdf} \put(2.5,20.5){\footnotesize $\mathcal{Y}$} \put(2.5,7){\footnotesize $\mathcal{X}$} \put(5.5,10){\footnotesize $\color{white} v_\tau$} \put(20,25.5){\footnotesize $\phi_1$} \put(20,13){\footnotesize $\psi_1$} \put(30.5,25.5){\footnotesize $\phi_2$} \put(30.5,13){\footnotesize $\psi_2$} \put(41,25.5){\footnotesize $\phi_3$} \put(41,13){\footnotesize $\psi_3$} \put(51.5,25.5){\footnotesize $\phi_4$} \put(51.5,13){\footnotesize $\psi_4$} \put(62,25.5){\footnotesize $\phi_5$} \put(62,13){\footnotesize $\psi_5$} \put(79,4){\line(0,1){18}} \end{overpic} \caption{\label{fig:puzzles}Simultaneous localization of multiple disconnected regions. Given a query shape $\mathcal{Y}$ (here consisting of 3 pieces), our method solves for a potential $v_{\tau}: \mathcal{X} \to (0, \tau)$ which isolates the regions on $\mathcal{X}$ corresponding to $\mathcal{Y}$ up to isometry (leftmost column). By Property~\ref{thm:align}, the found $v_\tau$ induces alignment of the eigenfunctions (intermediate columns); we exploit this to easily associate a different label to each region. On the right we plot the identified regions with different colors. The rightmost column shows additional multi-piece examples.} \end{figure*} \begin{figure}[b] \centering \begin{overpic} [trim=0cm 0cm 0cm 0cm,clip,width=1.0\linewidth]{./figures/sampling_top.pdf} \put(40,29){\footnotesize $n=10K$} \put(77.5,29){\footnotesize $n=5K$} \end{overpic} \input{./figures/IoU_robustness.tex} \begin{overpic} [trim=0cm -1.5cm 0cm 0cm,clip,width=0.73\linewidth]{./figures/sampling_bottom.pdf} \put(05,1.7){\footnotesize PFM \cite{rodola2017partial}} \put(35,1.7){\footnotesize \textbf{Ours}} \put(54.5,1.7){\footnotesize PFM \cite{rodola2017partial}} \put(84.5,1.7){\footnotesize \textbf{Ours}} \end{overpic} \caption{\label{fig:sampling}Robustness to changes in vertex density. We show the results of PFM (in orange) and our method (in green) over two versions of the entire SHREC'16 dataset: a version where all meshes have similar resolution (dotted curves in the plots), and one where mild remeshing has been applied (solid curves). PFM shows a performance drop of 20\%, while our method remains stable.} \end{figure} \vspace{1ex}\noindent\textbf{Multiple pieces.} We highlight another useful property derived from working with potentials. In Figure~\ref{fig:puzzles} we show examples where the input 3D query consists of {\em multiple} disconnected parts (the ``non-rigid puzzle'' setting with non-overlapping pieces \cite{litany2016non}). By taking their union and treating them as one single shape $\mathcal{Y}$ in our optimization problem, we are still able to correctly identify the distinct portions on the full shape without any special adjustment to our algorithm. \vspace{1ex}\noindent\textbf{Implementation details.} In all our tests we use $k=20$ eigenvalues. As initialization for $\v$, we use Gaussians centered around $m=20$ Euclidean farthest samples on $\mathcal{X}$, with variance equal to $\sqrt{\mathrm{Area}(\mathcal{X})}$ and $2\sqrt{\mathrm{Area}(\mathcal{X})}$, leading to $2m$ different initializations which we optimize in parallel. To these, we also add the solutions produced by the baseline. To choose the final solution we rely on Property~\ref{thm:align}. For each found $v$, we compute projections of SHOT descriptors $F: \mathcal{X} \to \mathbb{R}$ over the first $5$ Hamiltonian eigenfunctions (squared), $c_{i} = \int_\mathcal{X} \psi_i^2(x) F(x) \mathrm{d}x$ for $i=1,\dots,5$. We then compute coefficients $d_i$ on $\mathcal{Y}$ similarly by using the Dirichlet eigenfunctions, and keep the $v$ which yields minimum distance $\sum_{i=1}^5 (d_i-c_i)^2$. By Property~\ref{thm:align}, we expect these coefficients to be the same for the correct solution. \subsection{Isospectralization}\label{sec:isosp} As a second application we address the shape-from-spectrum problem. This task was recently introduced in \cite{isosp} and is phrased as follows: Given as input a short sequence of Laplacian eigenvalues $\{\mu_i\}_{i=1}^{k}$ of an {\em unknown} shape $\mathcal{Y}$, recover a geometric embedding of $\mathcal{Y}$. We stress that the Laplacian $\Delta_\mathcal{Y}$ is {\em not} given; if given, it would lead to a shape-from-operator problem \cite{boscaini2015shape}. Instead, the goal here is to recover the shape directly from the eigenvalues alone. We model this problem by minimizing Eq.~\eqref{eq:prob2} with the following input. As full domain $\mathcal{X}$ we consider a finite portion of the plane $\mathcal{X}\subset\mathbb{R}^2$ of size $n\times n$, sampled on a Cartesian grid. The input eigenvalues $\{\mu_i\}$ are assumed to be coming from an unknown region $\mathcal{R}\subset\mathcal{X}$, which we identify by the potential $v_\tau$ on $\mathcal{X}$. Therefore, our optimization variables are simply $\v\in(0,\tau)^{n\times n}$ -- essentially, an image. \begin{property} We can recover shapes with \textbf{unknown topology}, \ie, no restricting assumptions are made on the topology of the sought shape. \label{thm:topo} \end{property} For example, if the shape to be recovered has holes, we do not need to know this fact beforehand to properly initialize the optimization. \vspace{1ex}\noindent\textbf{Comparisons.} In Figure~\ref{fig:isosp} we compare directly with the isospectralization technique of Cosmo~\etal~\cite{isosp}; to our knowledge, this is the only existing approach attempting to solve shape reconstruction purely from eigenvalues. Our method is different in many respects. The most crucial difference lies in the fact that in \cite{isosp} the authors optimize for a {\em deformation field} to apply to an initial template shape, which is assumed to be given as an input. In contrast, with Problem~\eqref{eq:prob2} we simply minimize over a vector space of scalar functions. The initial shape used in \cite{isosp} is also required to have the correct topology (\eg, disc-like or annulus-like), while by Property~\ref{thm:topo} our optimization is completely oblivious to the topology of the shape to recover. We illustrate this with an example in the rightmost column of Figure~\ref{fig:isosp}, where we directly compare with \cite{isosp}. Finally, optimizing over embedding coordinates as in \cite{isosp} requires the adoption of additional regularizers to avoid flipped triangles, and careful parameter tuning to avoid rough shapes and collapsing edges; this makes their energy more difficult to minimize, which is done using stochastic optimization tools \cite{kingma2014adam} and automatic differentiation as implemented in TensorFlow~\cite{tf}. By optimizing over scalar functions instead of deforming a given mesh, we do not encounter any of these issues; for this reason, our optimization can be made much simpler as detailed in Section~\ref{sec:method}. \begin{figure}[t] \centering \begin{overpic} [trim=0cm 0cm 0cm 0cm,clip,width=1.0\linewidth]{./figures/comparison_isosp2.pdf} \end{overpic} \caption{\label{fig:isosp}Shape recovery comparisons with \cite{isosp}. We show the ground truth shapes (blue outline) and our solutions (potential on the square, growing from white to red), all obtained in 2-3 minutes from $k=50$ input eigenvalues. We always use a constant initialization. On the bottom we show results for \cite{isosp} with their initial templates, which are required to always have the correct topology.} \end{figure} \begin{figure}[t] \centering \begin{overpic} [trim=0cm 0cm 0cm 0cm,clip,width=0.9\linewidth]{./figures/alignment.pdf} \put(-6.5,63.5){\footnotesize iter.} \put(-4.5,60.0){\footnotesize 0} \put(-4.5,56.0){\footnotesize $\downarrow$} \put(-7,7.0){\tiny ground} \put(-5.8,3.5){\tiny truth} \end{overpic} \caption{\label{fig:star}Shape recovery across iterations. Starting from a sequence of just $k=5$ Laplacian eigenvalues, our method recovers the correct shape in less than $1$ minute. The first column shows our solution, evolving from top to bottom. On the right we also show how the eigenfunctions (one per column) change across the iterations; observe how at convergence, they align with those of the ground truth shape (up to rotation).} \end{figure} \vspace{1ex}\noindent\textbf{Implementation details.} The planar domain $\mathcal{X}$ is discretized as a $30 \times 30$ grid with uniform triangles. We initialize simply with the constant potential $\v = \frac{\tau}{4} \mathbf{1}$, in order to emphasize the ability of our method to recover shape entirely from scratch irrespective of topology. We put this in contrast with \cite{isosp}, which needs an initial template as initialization, as mentioned above. See Figure~\ref{fig:star} for a visualization across some iterations of our optimization process. \section{Summary of our reasoning} \vspace{-0.5ex} \begin{figure}[t] \centering \setlength{\tabcolsep}{0pt} \begin{tabular}{ccc} \input{./figures/perc1.tex}& \input{./figures/perc2.tex}& \input{./figures/perc3.tex} \end{tabular} \begin{overpic} [trim=0cm -1.8cm 0cm 0cm,clip,width=1.0\linewidth]{./figures/statue_step.png} \end{overpic} \caption{\label{fig:stepwall}{\em Top}: A step potential $v_\tau$ (solid red) confines eigenfunction $\psi_i$ (solid blue) within the region where $v_\tau(x)=0$, as long as for the associated eigenvalue $\lambda_i$ (dashed gray) it holds $\lambda_i<\tau$. As soon as $\lambda_i \ge \tau$, a ``diffusion'' effect across the potential barrier takes place (rightmost plot). We illustrate this in $\mathbb{R}$ with three eigenfunctions at increasing eigenvalue (left to right). {\em Bottom}: We show the same phenomenon on a surface. Here, the potential with height $\tau$ is depicted on the left and is supported on the pedestal; observe the diffusion in the rightmost figure, due to the eigenvalue of the plotted eigenfunction being higher than $\tau$.} \end{figure} A classical result in mathematical physics \cite[Ch.~2]{griffiths} shows that the eigenfunctions $\psi_i$ of $H_\mathcal{X}$ exhibit {\em localization} depending not only on the geometry of the domain $\mathcal{X}$ \cite{heilman2010localized}, but also on the shape of the potential $v$. In this paper, we consider step potentials with finite height $\tau>0$: \begin{align}\label{eq:step} v_\tau(x) = \left\{ \begin{array}{ll} 0 & x\in \mathcal{R}\\ \tau & x\notin\mathcal{R}\end{array} \right. \end{align} for a given region $\mathcal{R}\subseteq\mathcal{X}$. The following lemma on the ``confinement'' property of step potentials is instrumental to our approach: \begin{lemma}[\!{\!\cite[Ch.~2.6]{griffiths}}] Let $\mathcal{R}\subseteq\mathcal{X}$ be a region of $\mathcal{X}$, and let $v_\tau:\mathcal{X}\to\{0,\tau\}$ be a finite step potential defined as in Eq.~\ref{eq:step}. Then, for the Hamiltonian $\Delta_\mathcal{X}+v_\tau$ all eigenfunctions $\psi_i$ with eigenvalue $\lambda_i<\tau$ vanish pointwise for $x\notin\mathcal{R}$. \label{thm:step} \end{lemma} According to Lemma~\ref{thm:step}, for large enough $\tau$, the Hamiltonian eigenfunctions will be entirely supported within $\mathcal{R}$. This result holds both on the real line (where the eigenfunctions are Fourier harmonics) and on manifolds\footnote{Berger \cite[p.403]{berger2012panoramic} described this analogy quite vividly, by depicting manifolds as ``quantum mechanical worlds''.}. We illustrate real examples of these facts in Figure \ref{fig:stepwall}. Key to our approach is the realization that the confined behavior or Hamiltonian eigenfunctions can be exploited by optimizing over the space of potentials $v_\tau$. We therefore establish the following lemma: \begin{lemma}[Eigenvalue equivalence] Let $\mathcal{R}\subseteq\mathcal{X}$ be a region of $\mathcal{X}$, and let $v_\tau:\mathcal{X}\to\{0,\tau\}$ be a finite step potential defined as in Eq.~\eqref{eq:step}. Now let $\{(\lambda_i,\psi_i)\}_{i=1}^{k}$ be $k$ eigenpairs of $\Delta_\mathcal{X}+v_\tau$, increasingly ordered and such that $\lambda_k<\tau$. If $(\mu_i,\phi_i)$ are the eigenpairs of $\Delta_{\mathcal{R}}$ computed with Dirichlet boundary conditions, then $\mu_i=\lambda_i$ for all $i=1,\dots,k$. \label{thm:diri} \end{lemma} \noindent\textbf{Sketch of proof.} For any eigenpair $(\lambda_i,\psi_i)$ of $\Delta_\mathcal{X}+v_\tau$ with $\lambda_i<\tau$, the following equality holds pointwise: \begin{align} \lambda_i \psi_i(x) &= \Delta_\mathcal{X}\psi_i(x) + v_\tau(x) \psi_i(x) \label{eq:l1} \\ &= \Delta_{\mathcal{R}}\psi_i(x) \label{eq:l2} \\ &= \mu_i\phi_i(x) \label{eq:l3} \,. \end{align} The equivalence~\eqref{eq:l2} follows directly from Lemma~\ref{thm:step}, since $\psi_i(x)$ vanishes for $x\notin\mathcal{R}$. Eq.~\eqref{eq:l3} stems from the homogeneous Dirichlet condition $\phi_i(x)=0$ for $x\in\partial\mathcal{R}$. \hfill $\square$ \vspace{1ex} An illustration of this result is given in Figure~\ref{fig:dirichlet}. Lemma~\ref{thm:diri} establishes that one can measure the Dirichlet eigenvalues of a partial shape $\mathcal{R}$ equivalently by measuring Hamiltonian eigenvalues over the complete shape $\mathcal{X}$ -- provided that an indicator for the corresponding region on $\mathcal{X}$ is given. This gives us a straightforward way to implement localization via optimization over the cone of non-negative real-valued functions on $\mathcal{X}$. Problem~\eqref{eq:prob} in the next Section formalizes precisely this idea. \begin{figure}[t] \centering \begin{overpic} [trim=0cm -1.8cm 0cm 0cm,clip,width=1.0\linewidth]{./figures/frog.png} \put(-4,24.5){\footnotesize $+1$} \put(-1,19.5){\footnotesize $0$} \put(-4,14.5){\footnotesize $-1$} \put(6,1){\footnotesize $v_\tau:\mathcal{X}\to\{0,\tau\}$} \put(44,22){\footnotesize $\mathcal{X}$} \put(73,22){\footnotesize $\mathcal{R}\subset\mathcal{X}$} \put(52,1){\footnotesize $(\lambda_5,\psi_5)$} \put(85,1){\footnotesize $(\mu_5,\phi_5)$} \end{overpic} \caption{\label{fig:dirichlet}{\em Left}: Given a region $\mathcal{R}$ (the face of the frog), we show the step potential $v_\tau$ such that $v_\tau(x)=0$ for $x\in\mathcal{R}$, and $v_\tau(x)=\tau$ otherwise. {\em Middle}: The eigenfunctions $\psi_i$ of the Hamiltonian $\Delta_\mathcal{X}+v_\tau$ are localized on $\mathcal{R}$, meaning that $\psi_i(x)\approx 0$ for $x\notin\mathcal{R}$. {\em Right}: If the region $\mathcal{R}$ is taken as a separate mesh with boundary $\partial\mathcal{R}$ (depicted in green), the Dirichlet eigenfunction $\phi_i$ of $\Delta_\mathcal{R}$ has the same values as $\psi_i$ at corresponding points. As a consequence, $\lambda_i=\mu_i$.} \end{figure}
{'timestamp': '2019-06-17T02:15:06', 'yymm': '1906', 'arxiv_id': '1906.06226', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06226'}
arxiv
\section{Introduction}\label{sec_intro} Data centers are the most critical infrastructure to host large-scale, complex enterprise and cloud applications \cite{barroso2009datacenter}. Over the years, data centers have undergone great growth in two aspects. On one hand, the hardware capacity of a data center has become much more powerful than ever before. On the other hand, the popularity of cloud computing has motivated the growth of multi-tenant support in data centers \cite{wang2008study, shen2011cloudscale, miller2008microsoft}. As a result, it is typical that today's data centers host tens or even hundreds of tenants and that each tenant runs tens or hundreds of applications. With such unprecedented system scale and application complexity, there comes a great challenge: how to deal with anomalies caused by a variety of factors, such as hardware faults, configuration mistakes, software bugs, flaws in application designs, and attacks. This paper addresses large-scale anomaly detection and mitigation. In such cases an anomaly in a particular device or application could ``spill off'' to affect many other applications in the same data center. In the worst case, such an anomaly could trigger a sequence of problems and lead to system-wide outages, known as a cascading failure \cite{dobson2007complex, nedic2006criticality, brewer2001lessons}. For multi-tenant data centers, a cascading failure could affect a large number of tenants and result in considerable loss. The Amazon AWS outage in April 2011 is a typical example of cascading failure \cite{a1}. During a routine maintenance, a routing misconfiguration created congestion on a small number of links. The congestion caused loss of keep-alive messages between many primary and backup storage nodes. As a results, the primary nodes mistakenly decided that the backup nodes were down, and thus started to create new mirror nodes. The mirroring operation intensified the congestion and subsequently triggered even more mirroring operations, which in turn exhausted the data center storage and bandwidth resources. Furthermore, the above events triggered such a large number of messages to the control plane that the load eventually brought down the control plane. The outage of the control plane caused even more impacts to the entire system. Although the initial misconfiguration was detected and fixed quickly, the damage had been made and the outage affected a large number of tenants running on top of AWS. It took four days to completely restore the entire system. Due to the complexity of large-scale data centers and applications, it is often non-trivial to detect an anomaly, locate the root causes, and perform mitigation. While insightful discoveries have been made on data center traffic patterns that suggest regardless of applications running in a data center some trends tend to be consistent \cite{kandula2009nature, benson2010network, aghdai2013traffic}, current solutions heavily rely on case-specific analysis and are often labor-intensive \cite{wu2012netpilot, yu2011profiling}. One must have certain knowledge on the type and characteristics of an application to monitor its operation and perform anomaly detection. While such approaches are indispensable, it is not the best choice to solely rely on experienced system administrators to perform the tasks, especially in large-scale systems such as a data center. In particular, it is often impossible for the operator of a multi-tenant data center to obtain the type and characteristics of a tenant's applications. According to a recent analysis \cite{cloudfail}, from 2009 to 2011 the number of cloud vulnerability incidents more than doubled. In particular, some disruptions were so severe that they caused large-scale service outage lasting for hours or even days. For example, the Amazon AWS experienced several large-scale outages \cite{armbrust2010view}. Reddit and NetFlix are just a few example of web services that experienced wide disruptions during recent Amazon AWS incidents \cite{a2, a3}. Other major cloud players such as Microsoft and Google have experienced similar incidents as well \cite{mi1, g1}. Table \ref{Outages} lists a few well-documented major data center failures in the past few years. This list is by no means exhaustive. Many service providers even choose not to report incidents for various reasons. We estimate that the actual impacts from data center anomalies are far more intense than what has been reported. We propose to design a highly resilient data center with the following key properties: \begin{itemize} \item \textbf{Detect anomalies as quickly as possible.} Errors should not propagate through the entire data center. Detecting anomalies in real time enables data center operators to proceed with quick mitigation actions. This will prevent the cascading failures so as to confine the damage that could possibly caused by a small application or network error. \item \textbf{Avoid using application-specific information for detection.} Multi tenancy, widely adapted in warehouse-scale data centers, limits amount of information that is available to data center operators. For example, detecting a misconfiguration in a local name resolution service is pretty straightforward by analyzing its logs. However, these logs are only available to the tenant. Thus, data center operators cannot rely on application-specific metrics for anomaly detection. A solid and useful anomaly detection scheme should make the most from information accessible to data center operators. \item \textbf{Mitigate errors using simple actions.} Our analysis of previous failures shows that examples of cascading failure errors could easily be prevented by using simple mitigation actions such as throttling flows in the data center. Such simple actions are effective to prevent errors from spreading to the entire system and do not generate severe negative impact to the system. \end{itemize} \begin{table}[t] \centering \begin{tabular} {c c c c} \hline Service & Date & Duration & Refer to\\ \hline Amazon AWS & Apr. 2011 & 4 Days & \cite{a1}\\ Amazon AWS & Oct. 2012 & 8 Hours & \cite{a2}\\ Amazon AWS & Dec. 2012 & 12 Hours & \cite{a3}\\ Sidekick & Fall 2009 & 1 Week & \cite{s1}\\ Hotmail & Dec. 2010 & 3 Days & \cite{mi1}\\ Intuit & Jun. 2010 & 3 Days & \cite{i1}\\ Google services & Jan. 2014 & 30-60 Minutes & \cite{g1}\\ \hline \end{tabular} \caption{Recent well-documented data center outages} \label{Outages} \end{table} \subsection*{Contributions} We propose an automated anomaly detection and mitigation scheme for data centers. Our scheme uses data mining over network-level traffic metrics to detect anomalies. We also study several cases of well-documented outages in Amazon AWS. A multi-stage detection and mitigation scheme is used to prevent propagation of errors in data centers. During the first stage, our algorithm detects traces of abnormal behavior in specific traffic metrics. At the next stage, the correlation between detected traces of anomalies will be determined. Those with high correlation are potentially anomalies. Once an abnormality is detected, it is essential to perform mitigation actions so as to avoid potential cascading failures. Small-scale and local anomalies are neglected as long as they do not spread. \subsection*{Organization} The rest of the paper is organized as follows. \hyperref[Sec_Frm]{\S \ref*{Sec_Frm}} introduces our design for anomaly detection and mitigation in data centers. \hyperref[sec_sym]{\S \ref*{sec_sym}} defines and explores symptoms of abnormal behavior in traffic patterns. \hyperref[sec_2s]{\S \ref*{sec_2s}} elaborates the proposed 2-step anomaly detection algorithm. \hyperref[DC_Analysis]{\S \ref*{DC_Analysis}} explores well-documented outages in Amazon AWS. \hyperref[sec_sim]{\S \ref*{sec_sim}} explores existing work in this area. Finally, \hyperref[sec_conc]{\S \ref*{sec_conc}} concludes the paper. \section{Anomaly Detection and \\ Mitigation Framework} \label{Sec_Frm} In this paper, we target high-impact anomalies that pose threat to the data center at large scale. That is, the anomaly affects many VMs or services. Traffic traces from affected VMs are influenced during the anomaly. We show that certain traffic metrics are influenced the most during anomalies. To detect anomalies, our design monitors traffic traces. VMs with suspicious traffic patterns are further analyzed. Our algorithms are designed to find groups of VMs that suffer from the same anomaly. Upon detection of such groups, data center operators are immediately notified. Furthermore, mitigation actions are performed so as to prevent anomalies from spreading through the data center. \subsection{Symptoms} Our scheme constantly monitors traffic traces looking for \emph{symptoms} of anomalous behavior. A symptom is a certain type of pattern in traffic traces, such as an increase in Round Trip Time (RTT), or abrupt change in creation/termination rate of flows. We base our detection on observing and analyzing symptoms. A large-scale anomaly that affects a lot of VMs in a data center creates a good deal of symptoms. In particular, the same type of symptoms tend to be observed in large quantity at many hosts. For example, a misconfigured router may cause increased RTT and packet losses for many flows. A malfunctioning cloud application may cause many of its VMs to create new flows at an abnormal speed. Generated symptoms caused by a specific anomaly are \emph{correlated} in time domain as well as space domain. More specifically, an anomaly creates symptoms with the same pattern over time and the symptoms appear on malfunctioning hosts at roughly the same time. These two types of relations between the observed symptoms are called time domain and space domain \emph{correlation} respectively. Our design relies on global scale correlation-based analysis of the symptoms to detect anomalies. While it is true that certain anomalies cause application outages but do not generate obvious symptoms, neither do such anomalies affect the data center operation at large. Detection and mitigation of such anomalies are beyond the scope of this work. \subsection{Architecture} \begin{figure}[t] \centering \includegraphics[keepaspectratio=true,width=0.45\textwidth]{F1.pdf} \caption{Proposed architecture for anomaly detection.} \label{Arch_fig} \end{figure} Figure \ref{Arch_fig} illustrates the architecture of our design. The main components are Agents and the Controller. \begin{itemize} \item \textbf{Agent}: An agent is a VM that runs on a physical server hosting application VMs. The agent monitors and analyzes the inbound and outbound traffic to identify various types of symptoms. Agents communicate with controller to report detected symptoms. Hypervisors are modified to recognize the special role of the agent. Thus, they interact with agents accordingly. At fine granularity, the hypervisor duplicates the header of each inbound and outbound packet and passes the header to the agent for analysis. Packet duplication at hypervisor ensures that our scheme does not incur any additional delay in packet forwarding. \item \textbf{Controller}: Controller receives symptoms' reports from the agents and performs the correlation. It make decisions on anomaly detection based on the global correlation of symptoms in time and space domains. Controller is responsible for raising alerts to data center operators and having hypervisors initiate the automated mitigation. Mitigation is done by limiting the resource access (typically bandwidth) of certain type of traffic or certain VMs. \end{itemize} The design can scale out by using multiple controllers. \subsection{Detection Method} A specific anomaly triggers similar symptoms in affected hosts. These symptoms are observed at affected hosts at roughly the same time. Therefore, they are correlated in space domain. Similarly hosts affected by the same anomaly experience the same pattern of symptoms. Hence, symptoms are also correlated in time domain. For example, a link congestion causes increased round trip times followed by increased number of packet drops. As a result, affected hosts eventually experience large number of packet drops. Spatial correlation can detect these hosts. During the anomaly, all of the affected hosts experience increased RTT as well. Therefore, time-series correlation can analyze spatial correlation results and find group of hosts that show correlation in time domain as well as space domain. In our framework, agents periodically monitor and analyze traffic traces and summarize observed symptoms into a report. Controller correlates reports in space domain to reveal clusters of hosts that experience similar symptoms at roughly the same time. Then, the controller performs time domain analysis on each of the spatially-correlated clusters. Groups of hosts with high spatial as well as time domain correlation are considered to be abnormal. These groups are reported to the data center operators and are marked for performing mitigation. \section{Symptoms} \label{sec_sym} \begin{table*}[t] \centering \begin{tabular} {c c c c c} \hline RTT & RST & Duplicate Acks & Active Flows & Flows Size \\ \hline Similarity & Frequency & Frequency & Fluctuations & Fluctuations \\ \hline \end{tabular} \caption{Methods to generate elemnts in SR.} \label{report_generation} \end{table*} We adopted the following set of symptoms for anomaly detection: \begin{itemize} \item \emph{Change of active flows:} Sudden change in creation/termination rate of flows is a symptom of abnormal behavior. The key observation is that the creation of new flows by a large number of hosts in a short duration is often a suspicious phenomenon that needs careful monitoring and analysis. \item \emph{Change of flow size:} Abrupt change in average flow size is another symptom of suspicious application activities. Due to the nature of general applications, the flow size (the total amount of data exchanged) often has consistent patterns in both the time domain and spatial domain. A sudden change of the attribute either indicates a radical change of the application or an anomaly. \item \emph{Similarity of observed RTTs:} A sudden change in pattern of observed round trip times between a pair hosts compared to their history, is another symptom of potential anomalies. The RTT between a pair of hosts is determined by several factors: propagation delay, processing delay in switches and routers, queuing delay in switches and routers, and processing delay at the receiver. In data centers, the main factors to consider include the queuing delay and the processing delay. A dramatic increase of the queuing delay is mostly caused by congestion, while an increase of the processing delay can be caused by overloading or malfunctioning at the receiver. While a small number of isolated RTT increases do not pose any threat, a large number of concurrent such symptoms could indicate a critical problem that requires attention. \item \emph{Number of duplicate TCP ACKs:} Observing large number of triple duplicate acknowledgments in a TCP flow is another symptom of potential anomaly in networks. Duplicate TCP ACKs are generated if some TCP segments are dropped in the network. This symptom can be observed during normal operation because occasional packet dropping is normal and could even be caused by certain algorithms such as random early detection (RED) \cite{floyd1993random}. However, a network problem such as prolonged congestion or misconfiguration could trigger an unusual number of such symptoms in large scale. \item \emph{Number of TCP RST signals:} Observing TCP RST signals is another symptom indicating anomalous behavior in applications or operating system's protocol stack. TCP reset (RST) is a one-bit flag in the TCP header \cite{postel1981transmission}. A host sends out a TCP RST if it notices that it is not receiving acknowledgements for anything it sends and thus the connection is unsynchronized. The signal could also be triggered by certain middleboxes. In normal operation, such flags should be scarce. Therefore, this symptom is a good indicator of abnormal behavior. \end{itemize} \subsection{Generation of Symptom Reports} Each agent reports to the controller one or multiple metrics of an observed symptom. The metrics are: \begin{itemize} \item \emph{Frequency:} Agents count the number of occurrences for each symptom. This metric is used for observed triple duplicate acknowledgments and RST flags. These incidents by themselves indicate an abnormal behavior in TCP connections, therefore no further processing is needed for these types of symptom. \item \emph{Fluctuations:} Local agents observe average size of a symptom in each time window. The signed relative change of the attribute in comparison to that of the previous time window is calculated and reported in SR: $\Delta X = \frac{X_{Current Sample} - X_{Previous Sample}}{X_{Current Sample}}$ This metric is used for detecting change in number of active flows and change in average size of flows. \item \emph{Similarity:} Local agents keep track of observed symptoms in each time window. The objective is to determine how similar the current set of observed symptoms is to that of the previous time window. The calculated similarity is reported in SR. \begin{figure}[b] \centering \includegraphics[keepaspectratio=true,width=0.45\textwidth]{F2.pdf} \caption{An example of calculating similarity.} \label{RTT_Sample} \end{figure} We use Jaccars's similarity coefficient \cite{rajaraman2012mining} to calculate the similarity between observed RTTs. Jaccard's similarity coefficient measures similarity between finite sample sets, and is defined as the size of the intersection divided by the size of the union of the sample sets. To calculate the Jaccardian similarity of current time window to that of the previous window, agents dequantize observed symptoms into labels. Jaccardian similarity is calculated between current set of labels and the set from the previous time window. This value is reported as the similarity of observed symptoms to those of the previous time window. This metric is used for detecting changes in RTT. Due to the nature of physical communication at network observed observed RTTs do fluctuate for a flow. However, a simultaneous increase in observed RTTs may indicate a problem with the network and/or applications. Figure \ref{RTT_Sample} illustrates an example of this process. In this example observed RTTs from two consecutive time windows are shown using dots. Numbers are converted to labels using four bands. Finally Jaccardian similarity between the two sets is calculated and reported. \end{itemize} Table \ref{report_generation} presents the method used for each symptom. \section{Symptom Analysis for Anomaly Detection} \label{sec_2s} Our detection scheme relies on two algorithms to reveal correlation between observed symptoms in both space and time domains. \subsection{Distributed Analysis of SRs\\ in Space Domain (DAS)} Spatial correlation is performed using SR vectors. VMs with similar SRs are considered to have correlation. From this point of view, the problem of finding spatial correlation is quite similar to clustering problem in statistical data analysis \cite{rajaraman2012mining, hartigan1979algorithm, steinbach2000comparison}. That is, given a set of vectors, identify one or more groups in such a way that vectors in the same group are more similar to each other than to those not belonging to that group. The clustering problem has been extensively studied in statistical data analysis and has been applied in a variety of fields such as data mining \cite{rajaraman2012mining} and machine learning \cite{rajaraman2012mining}. DAS is a distributed modification of K-Means clustering \cite{hartigan1979algorithm}. DAS has 2 components, the first component is performed at each agent. It outputs local VMs that show similar symptoms. Second component, running at controller, has a global view of VMs. It receives SRs that shown similar symptoms, and outputs VMs with similar symptoms at data center scale. \begin{algorithm}[b] \SetAlgoLined\DontPrintSemicolon \SetKwFunction{algol}{DAS at agent} \SetKwProg{myalgl}{Algorithm}{}{} \myalgl{\algol{SR}}{ $P_{0} \leftarrow \bar{0} $\; $P_{i:1..5} \leftarrow i$th. unity vector \; $C_{i:0..5} \leftarrow \emptyset $\; \While{There are SRs left}{ Read $SR_j$\; $D_{i:0..5} \leftarrow$ Distance($SR_j$, $P_i$)\; $k \leftarrow$ ArgMin($D_{i:0..5}$)\; $C_k.$Add($SR_j$)\; } \Return{$C_{i:1..5}$}\; } \caption{DAS at Agents} \label{DAS_agent} \end{algorithm} \subsubsection{DAS at Local Agents} Agents send VMs with similar SRs to controller, filtering out normal VMs. In order to perform this task, agents run modified clustering with $K = 6$ clusters. Algorithm \ref{DAS_agent} performs clustering with predefined cluster representatives. It finds closest cluster representative, $P_{i:0..5}$ to each SR and puts the SR in appropriate cluster, $C_{i:0..5}$. Euclidean distance \cite{rajaraman2012mining} is used as the metric. $P_0 = \bar{0}$, indicates experiencing no symptom. $P_{i:1..5}$ is the $i$th. unity vector in $R^5$, which indicates experiencing $i$th. symptom. VMs showing no specific symptom will be clustered in default cluster, with representative: $P_0$. While, potentially abnormal VMs are clustered according to their dominant symptom. For VMs clustered in $C_{i:1..5}$ their SRs are sent to controller for further analysis. \subsubsection{DAS at Controller} Main part of clustering is done at the controller. Controller periodically receives all SRs showing symptoms. It runs a highly modified K-Means clustering, Algorithm \ref{DAS_ctrlr}, to find clusters of VMs that experience similar symptoms simultaneously. At each iteration of clustering, SRs are clustered into $K_i$ clusters. It starts with $K_0 = 6 * L$ where L is number agents. At each iteration, number of clusters is halved: $K_i = K_{i-1}/2$. To find optimal number of clusters, we use an elbow criterion \cite{zu2002analysis}. At each iteration with $K = K_i$, clustering cost, $CC_i$ is defined to be $CC_i = \frac{CG_i}{K_i}$. Where $CG_i$ indicates clustering gain, defined as $CG_i = \bar{CS}_{i} - \bar{CS}{i-1}$ where $\bar{CS}_{i}$ denotes average cluster size at $i$th. iteration. Clustering is continued while $CC_i$ is improved. It is stopped when $CC_i$ is in the 5\% range of $CC_{i-1}$, or $K_i$ reaches one. \begin{algorithm}[t] \SetAlgoLined\DontPrintSemicolon \SetKwFunction{algo}{DAS at Controller} \SetKwProg{myalg}{Algorithm}{}{} \myalg{\algo{SR}}{ $K \leftarrow 6L$ \; $i, CS_0, CC_0, \Delta CC \leftarrow 0$ \; \While{$K > 0$ and $\Delta CC < 0.95$}{ Clusters$_{K} \leftarrow$ Cluster(SR, $K$) \; $i \leftarrow i + 1$ \; $CS_i \leftarrow$ Clusters$_{K_i}.$AverageSize \; $CC_i \leftarrow \frac{CS_i - CS_{i-1}}{K_i}$\; $\Delta CC \leftarrow \frac{CC_i - CC_{i-1}}{CC_{i-1}}$ \; $K \leftarrow$ Floor($K/2$) \; } \Return{Clusters$_K$}\; } \setcounter{AlgoLine}{0} \SetKwFunction{proc}{Cluster} \SetKwProg{myproc}{Function}{}{} \myproc{\proc{SR, K}}{ $P_{i:1..K} \leftarrow$ K Random SRs \; Clusters$_{NEW} \leftarrow \emptyset$ \; \Repeat{Clusters$_{NEW} =$ Clusters$_{OLD}$}{ Clusters$_{OLD} \leftarrow$ Clusters$_{NEW}$ \; Clusters$_{NEW}, C_{i:0..K} \leftarrow \emptyset$ \; \While{There are SRs left}{ Read $SR_j$\; $D_{i:0..K} \leftarrow$ Distance($SR_j$, $P_i$)\; $k \leftarrow$ ArgMin($D_{i:0..K}$)\; $C_k.$Add($SR_j$)\; } Clusters$_{NEW}.$Add($C_{i:1..K}$) \; $P_{i:1..K} \leftarrow$ $C_i.$Mean \; } \Return{Cluster$_{NEW}$}\; } \caption{DAS at Controller} \label{DAS_ctrlr} \end{algorithm} \begin{table*}[] \centering \begin{tabular} {c c c c c c} \hline \textbf{Anomaly Type} & \textbf{RTT} & \textbf{RST} & \textbf{Duplicate Ack}s & \textbf{Flow Size} & \textbf{Active Flows} \\ \hline Router misconfig (AWS, Apr. 12) \cite{a1} & increase & increase & increase & large & increase\\ \hline DNS misconfig (AWS, Oct. 12) \cite{a2} & increase & & & small & increase\\ \hline Load balancer misconfig (AWS, Dec. 12) \cite{a3} & increase & increase & increase & & change \\ \hline \end{tabular} \caption{Analysis of recent well-documanted incidents at Amazon AWS} \label{case_study} \end{table*} \subsection{Time Domain Analysis of Clusters (TAC)} Controller further scrutinizes the historical records of spatially-related VMs to perform time domain correlation. There are two objectives to conduct this operation. Firstly, it is possible that a group of hosts happen to exhibit similar symptoms even though the symptoms are simply random and isolated events. Although DAS filters out many coincidences, it is not possible to eliminate such false alarms. Therefore, we need to perform time domain correlation to look back to the history to see whether the symptoms are persistent or ephemeral. Secondly, anomalies tend to trigger multiple symptoms in a sequential way. For example, overloading on a link leads to increased RTT for many flows, and persistent overloading further triggers duplicate ACKs and possibly TCP RST signals. The time domain correlation is performed using Time Domain Analysis of Clusters (TAC). TAC is performed on the output of DAS. Initially, agents send 5 most recent reports of all the hosts in DAS output clusters to the controller. Supposing symptom $S_j$ has been detected among a set of hosts using space correlation, we set a look-back window and observe the occurrence of all the symptoms $S_1$, $S_2$, ..., $S_k$ (not including the final detected symptom by DAS) in the window for each host. The result for host $i$ in the cluster, $h_i$, is a vector $\Gamma_i = [\alpha_{i, 1} , \alpha_{i, 2} , ..., \alpha_{i, k}]$, where $\alpha_{i, k}$ is the indicator for symptom $S_k$ at host $h_i$. Then, pairwise Jaccardian similarity is calculated between all $\Gamma_i$ vectors. If vectors $\Gamma_i$ and $\Gamma_j$ have similar values for $\alpha_{i, k}$ and $\alpha_{j, k}$, it means that symptom $S_j$ has been persistent and. In addition, hosts i and j in the set have exhibited at least one symptom $S_k$ in the first place since they have been outputted by DAS. TAC outputs VMs with high similarity in their pair-wise $\Gamma$-vector. These VMs experienced at least one similar symptom at roughly the same time while showing similar pattern of symptoms in their provided history of time windows. Therefore, they have shown correlation both in space domain and time domain and are abnormal. \subsection{Mitigation} The mitigation process includes two steps. The first step is to classify the flows or VMs to different groups based on their symptoms. The goal is to distinguish misbehaving flows and VMs that worsen the problem from victim flows and VMs that are suffering from the misbehaving ones. For example, while many flows may be suffering from increased RTTs, a specific type of flows are reported to be increasing in quantities. So it is very likely that this group of specific flows are taking much of the bandwidth and overloading the networks, causing other flows to suffer from congestion. The second step is to limit bandwidth allocation to the misbehaving flows and VMs. Therefore, we will not simply block the traffic of all the suspicious flows and VMs. Instead, we will selectively throttle the bandwidth of VMs that shown abnormal behavior. \section{Case Study} \label{DC_Analysis} We have further elaborate our design by analyzing how well it would have worked on well-explored large scale data center outages. Table \ref{case_study} lists cases of recent reported large-scale anomalies at Amazon AWS. The first case happened in April 2011 \cite{a1}, where a mistake in routing caused data center wide congestions. This incident was explored in detail in \S1. During the incident, primary nodes started to create new mirror nodes, which affects average flow sizes shifting it towards larger flows. At this stage we expect agents to create large number of reports triggered with change in flow size. This correlation in space domain will create clusters of hosts experiencing this phenomena. As anomaly continues link congestions start to appear. Appearing link congestion increases the RTT as well as number of triple duplicate acks. At this stage agents report large number of hosts that experience increase in RTT with large number of triple duplicate acks. Controller receives the second wave of reports that belong to a portion of hosts that experienced space domain correlation. Therefore, clusters experience similar patterns of symptoms and show time domain correlation as well. Hence, as link utilizations increase our scheme will discover space domain as well as time domain correlation. Automated mitigation will throttle flows from affected hosts which in turn alleviates congestion on links. Our design is able to detect this anomaly and keep the network alive by throttling flows. By notifying system administrators in a timely manner, it will provide sufficient time for them to find the root cause. Meanwhile basic services are kept alive thanks to the automated mitigation actions. In the second case, happened at October 2012, a bug in an operational data collection agent degraded Amazon Elastic Compute Cloud (EC2) and Amazon Elastic Block Store (EBS) performance. In some cases, EBS volumes became stuck \cite{a2}. The root cause for this problem goes back to 1 week earlier when one of the data collection servers was replaced. While not noticed at the time, the DNS update did not successfully propagate to all of the internal DNS servers, and as a result, a fraction of the storage servers did not get the updated server address and continued to attempt to contact the failed data collection server \cite{a2}. Because of the design of the data collection service (which is tolerant to missing data), this did not cause any immediate issues or set off any alarms. However, the inability to contact a data collection server triggered a latent memory leak bug in the reporting agent on the storage servers. Rather than gracefully dealing with the failed connection, the reporting agent continued trying to contact the collection server in a way that slowly consumed system memory until it reached a critical mass and caused some of the provisioning services to become stuck eventually. During the period where storage servers tried to reach the missing server, we expect a lot of flows to be created and terminated rapidly. This, translates to increase in flow creation rate, huge number of triple duplicate acks, and shift in average flow size to smaller flows. Therefore, this complex anomaly caused by a misconfiguration in DNS entries, could have been detected after replacing the data collection server. Although our scheme is not able to pinpoint to the memory allocation bug, it is able to detect the original anomaly in a timely manner. In another example, during a maintenance in December 2012 \cite{a3} human error caused disruptions and down times in services that use Amazon Elastic Load Balancing. On a group of load balancers, state data was partially deleted by a maintenance process. As this continued, some customers began to experience performance issues with their running load balancers. During the anomaly, partial loss in load balancer's state data caused severe changes in traffic matrix. Therefore, VMs may have experienced overload or underload which directly affects number of active connections. Overloaded VMs cause increased average processing time for replying messages. As a increase in RTT would have been observed, had our scheme were used at Amazon. Also it is safe to assume that overloaded VMs started to drop packets resulting in increased number of triple duplicate acks and TCP RSTs. Therefore based on the huge number of correlated symptoms that were generated, this anomaly would have been detected in a matter of tens of seconds using our design. \section{Related Work} \label{sec_sim} Anomaly detection and mitigation in data centers have recently received a lot of attention \cite{yu2011profiling, wu2012netpilot, tan2012prepare, arefindiagnosing, sun2011identifying, zhou2011tap, attariyan2012x, jeswani2012adaptive}. However, research in this area is still in its early stage. The most relevant works to our design include include SNAP \cite{yu2011profiling}, NetPilot \cite{wu2012netpilot}, PREPARE \cite{tan2012prepare}, and FlowDiff \cite{arefindiagnosing}. SNAP (Simplified Network-Application Profiler) is designed to perform data analysis offline for identifying misbehaving applications. It collects TCP statistics and socket-call logs from all the hosts and performs centralized correlation to identify application flaws. However, typical data center operators may not have access to individual hosts and thus could not get the TCP statistics and socket-call log files. This is often the case for multi-tenant data centers. SNAP does not address real time detection and mitigation of anomalies. NetPilot is designed to automate data center network failure mitigation. Its objective is to quickly mitigate failures rather than finding a root cause and ultimately resolving the problem. The mitigation process is the same as those adopted by today's network operators: deactivating or restarting offending components. However, NetPilot is unique in that it takes an intelligent trial-and-error approach to automate the process, including an Impact Estimator that helps guard against overly disruptive mitigation actions and a failure-specific mitigation planner that minimizes the number of trials. However, NetPilot is unable to deal with complex errors caused by application/network/devices misconfigurations. PREPARE is designed to provide anomaly prevention for virtualized cloud computing infrastructures. In other words, preventive measures are taken to prevent applications from experiencing any anomaly. The proposed anomaly prediction scheme relies on system-level metrics such as CPU, memory, and disk I/O usage, and adopts a 2-dependent Markov model in conjunction with a tree-augmented Bayesian networks (TAN) model that is used as the classifier Once an alarm detected, PREPARE identifies faulty VMs and steers the system away from the violation state. The scheme also performs elastic VM resource scaling and VM migration. PREPARE does not analyze traffic characteristics, as it is designed to detect application errors. It does not address the errors caused by network device failures or network misconfigurations. FlowDiff collects information from all entities involved in the operation of a data center and builds behavioral models to detect operational problems in the data centers. By comparing the current model with pre-computed and known-to-be-stable models, FlowDiff detects operational problems ranging from host and network failures to unauthorized accesses. It relies on passive measurements on control traffic from programmable switches to a centralized controller in a software-defined networking (SDN) environment. The design consists of two phases: modeling and diagnosis. In modeling, FlowDiff creates signatures for applications using flow attributes, connectivity graph and delay distribution of packets belonging to the flows from specific application such as domain name systems (DNS). During diagnosis, FlowDiff looks for changes in application and/or infrastructure signatures and raises alerts. However, FlowDiff does not perform automatic mitigation. Instead, its purpose is to alert the operator. Also FlowDiff targets only data centers that are based on SDN. \section{Conclusions} \label{sec_conc} We propose a novel application-agnostic scheme to rapidly detect and mitigate anomalies in data centers. We use distributed processing and data mining techniques to detect anomalies in a timely manner. Detected anomalies are mitigated using simple actions such as throttling flows that belong to abnormal VMs. Mitigation ensures that anomalies do not spread throughout the data center. Our solution not only prevents cascading failures, but also provides sufficient time and information for data center operators to locate the root cause of the anomaly and resolve it with a profound solution. \small{\bibliographystyle{abbrv}
{'timestamp': '2019-06-18T02:02:19', 'yymm': '1906', 'arxiv_id': '1906.06388', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06388'}
arxiv
\section{Experimental details and further results} \label{sec:extra-experiments} \subsection{Experimental details and hyperparameters}\label{appdix:hyperparameters} For all experiments on MNIST, we used a convolutional architecture consisting of $3$ convolutional layers followed by a fully-connected output layer. Each convolutional layer consisted of $32$ $3 \times 3$ filters and used sufficient padding so as to keep the layer's output the same shape as its input. All networks were trained on an NVIDIA Tesla K20c GPU for $5000$ iterations with a batch size of $64$ using stochastic gradient descent with an initial learning rate of $0.1$ and a decay rate of $1\text{E}^{-6}$. No significant hyperparameter tuning was applied. For the left and right plots in Figure~\ref{fig:mnist}, we report results averaged over $5$ random trials and error bars corresponding to the standard deviation over these trials. For the center plot we simply computed the loss and accuracy over a linear path between a particular convolutional net and a single dropout version of itself. Specific to Figure~\ref{fig:mnist}, in applying dropout with probability $p$ we randomly sample a subset of $\lfloor 32 (1-p) \rfloor$ units and rescale these units by $1/(1-p)$ while setting the remaining units to zero. In the left plot, each trial consisted of sampling $20$ such dropout networks and reporting the performance of the network achieving the lowest loss. Losses and accuracies in all plots were computed on a random batch of $4096$ training images. On CIFAR-10, we trained VGG-11 networks on an NVIDIA Titan X GPU for 300 epochs with SGD with a batch size of 128, with weight decay 5e-4, momentum 0.9, and an initial learning rate of 0.05 which is decayed by factor of 2 every 30 epochs. We used channel-wise dropout at all convolutional layers. The dropout rates are $p=0.25$ at the first three layers and are $p=0.5$ at the others. Ordinary dropout with $p=0.5$ is used at every fully-connected layers except for the last one (the softmax layer). \subsection{Verification of noise stability conditions}\label{appdix:verification} \subsubsection{Layer cushion} \begin{figure}[H] \centering \def\mydata{ 1,2,3,4,5,6,7,8} \foreach \x in \mydata { \begin{subfigure}[t]{0.3\textwidth} \centering \includegraphics[width=4.5cm]{figures/cushion_layer_\x.pdf} \end{subfigure} } \end{figure} \subsubsection{Interlayer cushion}\label{appendix:interlayer-cushion} \begin{figure}[H] \centering \def\mydata{ 1,2,3,4,5,6,7,8} \foreach \x in \mydata { \begin{subfigure}[t]{0.3\textwidth} \centering \includegraphics[width=4.5cm]{figures/interlayer_cushion_layer_\x.pdf} \end{subfigure} } \end{figure} \subsubsection{Activation contraction} \begin{figure}[H] \centering \def\mydata{ 1,2,3,4,5,6,7,8} \foreach \x in \mydata { \begin{subfigure}[t]{0.3\textwidth} \centering \includegraphics[width=4.5cm]{figures/contraction_layer_\x.pdf} \end{subfigure} } \end{figure} \subsubsection{Interlayer smoothness} \begin{figure}[H] \centering \def\mydata{ 2,3,4,5,6,7,8} \foreach \x in \mydata { \begin{subfigure}[t]{0.3\textwidth} \centering \includegraphics[width=4.5cm]{figures/smoothness_layer_\x.pdf} \end{subfigure} } \end{figure} \section{Proofs for disconnected modes in two-layer nets} \label{sec:example} \begin{proofof}{Theorem~\ref{thm:counterexample}} Define our loss over parameter space such that $L(f_\theta) = \frac{1}{n}\sum l(y_i,f_\theta(\xx_i))$, where $\xx_i \in \RR^{h+2}$ is our $i^{\text{th}}$ data sample, $y_i \in \RR$ the associated label, and $f_\theta(\xx_i) = \ww^T \phi ( A \xx_i )$ for $\theta = (\ww,A) \in {\mathbb{R}}^{(h+2) \times h} \times {\mathbb{R}}^{h}$. We can represent the data samples as rows in a matrix $X \in \RR^{n \times (h+2)}$---with $\mathbf{f}_i$ denoting the $i^{\text{th}}$ ``feature'' (i.e. column) of $X$---and the labels as elements of $\mathbf y \in \RR^{n \times 1}$, as illustrated in Figure~\ref{fig:counterexample}. Choose $k,l,m,n$ such that $k < l < m < n$ where $k > h$, $l - k > h$, $m-l > 2$ and $n-m > h$. When $i \leq l$, let \begin{align*} x_{i,j} &= \begin{cases} i,&j=1\\ i-1,&j=2\\ 1,&i\equiv j\pmod h\\ -1,&i\nequiv j \pmod h,\, i\le l\\ 0,&i\nequiv j \pmod h,\, k<i\le l. \end{cases} \end{align*} When $l<i\le m$, let \begin{align*} x_{i,j} &= \begin{cases} -1, &j\le 2,\, i\equiv j\pmod h\\ 0, &j\le 2,\, i\nequiv j \pmod h\\ 0, &j>2,\, l<i\le m. \end{cases} \end{align*} When $i>m$, let \begin{align*} x_{i,j} &=\begin{cases} 0, &j\le 2\\ -1, &j>2,\, i\equiv j\pmod h\\ 0, &j>2,\, i\nequiv j\pmod h. \end{cases} \end{align*} Finally, let $y_i = 1$ when $i \leq l$ and $0$ otherwise. From the fact that $\phi(\mathbf{f}_1) - \phi(\mathbf{f}_2) = \sum_{j=3}^{h+2} \phi(\mathbf{f}_j) = \mathbf y$ it follows that there exist networks with both two active hidden units and $h$ active hidden units that achieve minimal loss, with the former corresponding to the ground truth teacher network which generated our dataset. Note in particular that the output layer weight corresponding to $\phi(\mathbf{f}_2)$ in the network with two active hidden units is negative, whereas in the network with $h$ active hidden units the output layer weights are all positive. Thus, any path between the two networks must pass through a point in parameter space where at least one output layer weight is zero while the other $h-1$ are positive. However, as shown in Lemma \ref{lem:emp-counterexample}, there does not exist such a point in parameter space that achieves minimal loss. It follows that there exists a barrier in the loss landscape separating the original networks, both of which are global minima. Moreover, by adjusting $k$, $l$, and $m$ we can somewhat arbitrarily raise or lower this barrier. \end{proofof} \begin{figure} $$% X = \begin{blockarray}{ccccccc} & \mathbf{f}_1 & \mathbf{f}_2 & \mathbf{f}_3 & \mathbf{f}_4 & \dots & \mathbf{f}_{h+2} \\ \begin{block}{c[cc|cccc]} \xx_1 & 1 & 0 & 1 & -1 & \cdots & -1 \bigstrut[t] \\ \xx_2 & 2 & 1 & -1 & 1 & \ddots & \vdots \\ \vdots & \vdots & \vdots & \vdots & \ddots & \ddots & -1 \\ \vdots & \vdots & \vdots & -1 & \cdots & -1 & 1 \\ \xx_k & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots \\ \cmidrule{4-7} \vdots & \vdots & \vdots & \BAmulticolumn{4}{c}{\multirow{2}{*}{$I_h$}}\\ \xx_l & l & l-1 & \vdots & \ddots & \ddots & \ddots \\ \cmidrule{2-7} \vdots & \BAmulticolumn{2}{c|}{\multirow{2}{*}{$-I_2$}} & \BAmulticolumn{4}{c}{\multirow{2}{*}{$0$}}\\ \vdots & & & & & & \\ \xx_m & \vdots & \ddots & \vdots & \vdots & \vdots & \vdots \\ \cmidrule{2-7} \vdots & \BAmulticolumn{2}{c|}{\multirow{2}{*}{$0$}} & \BAmulticolumn{4}{c}{\multirow{2}{*}{$-I_{h}$}} \\ \vdots & & & & & & \\ \xx_n & \vdots & \vdots & \vdots & \ddots & \ddots & \ddots \bigstrut[b]\\ \end{block} \end{blockarray}\vspace*{-1.25\baselineskip} \quad \mathbf y = \begin{blockarray}{cc} \\ \begin{block}{c[c]} y_1 & 1 \bigstrut[t] \\ \vdots & \vdots \\ \vdots & \vdots \\ \vdots & \vdots \\ \vdots & \vdots \\ \vdots & \vdots \\ y_l & \vdots \\ \cmidrule{2-2} \vdots & 0 \\ \vdots & \vdots \\ \vdots & \vdots \\ \vdots & \vdots \\ \vdots & \vdots \\ y_n & \vdots \bigstrut[b] \\ \end{block} \end{blockarray}\vspace*{-1.25\baselineskip} $$ \vspace{0.5cm} \caption{Our dataset.} \label{fig:counterexample} \end{figure} \begin{lemma}\label{lem:emp-counterexample} There does not exist a set of $h-1$ positive weights $w_i$ and vectors $\hh_i \in \spn X$ such that $\sum_{i=1}^{h-1} w_i \phi(\hh_i) = \mathbf y$. \end{lemma} \begin{proof} We can think of each $\hh_i$ as the output a particular hidden unit over all $n$ samples in our dataset and $w_i$ as the output layer weight associated to this hidden unit. We then have $\hh_i = \sum a_{i,j} \mathbf{f}_j$, where the coefficients $a_{i,j}$ are elements of $A$. First, if there did exist $w_i$ and $\hh_i$ such that $\sum_{i=1}^{h-1} w_i \phi(\hh_i) = \mathbf y$, then it must be the case for all $i$ that $\hh_i = \sum a_{i,j} \mathbf{f}_j$ where $a_{i,j} \ge 0$ for all $j$. Otherwise, there would be non-zero elements in some $\hh_i$ between indexes $l+1$ and $n$ that would be impossible to eliminate in $\sum_{i=1}^{h-1} w_i \phi(\hh_i)$ given that $w_i > 0$ for all $i$. Second, any linear combination of $\mathbf{f}_1$ and $\mathbf{f}_2$ with positive coefficients would result in a vector whose first $l$ elements are positive and increasing. In contrast, the first $l$ elements of $Y$ are constant. And so from the fact that there does not exist $a_{i,j} > 0$ such that the first $l$ elements of $\sum a_{i,j} \mathbf{f}_j$ are decreasing---in particular because the first $k$ elements and next $l-k$ elements of $\sum_{j=3}^{h+2} a_{ij}x_j$ are periodic with length $h$---it follows that $a_{i,1},a_{i,2} = 0$ for all $\hh_i$. Thus, we need only consider linear combinations of $\mathbf{f}_3$ through $\mathbf{f}_{h+2}$ with positive coefficients as candidates for $\hh_i$. To this end, note that if a particular $\mathbf{f}_j$ has zero coefficient in all of $\hh_1$ through $\hh_{h-1}$, then $\sum_{i=1}^{h-1} w_i \phi(\hh_i)$ will have zeros in every index congruent to $j \mod h$ and therefore cannot equal $\mathbf y$. Hence by the pigeonhole principle, in order to have $\sum_{i=1}^{h-1} w_i \phi(\hh_i) = \mathbf y$ there must be some $i$ such that $\hh_i = \sum_{j=3}^{h+2} a_{i,j} \mathbf{f}_j$ with at least two coefficients being non-zero. However, in any linear combination $\sum_{j=3}^{h+2} a_{i,j} \mathbf{f}_j$ where $a_{i,j},a_{i,j'} > 0$ for at least two distinct $j,j'$, the elements in indexes $k+1$ to $l$ will be greater than the elements in indexes $1$ to $k$ that are congruent to $j \mod h$ and $j' \mod h$. In contrast, the first $l$ elements of $\mathbf y$ are constant. Hence, similar to the case of $\mathbf{f}_1$ and $\mathbf{f}_2$, there cannot exist $\hh_i = \sum_{j=3}^{h+2} a_{i,j} \mathbf{f}_j$ and positive coefficients $w_i$ such that $\sum_{i=1}^{h-1} w_i \phi(\hh_i) = Y$. \end{proof} \section{Proofs for connectivity of dropout-stable optima}\label{sec:dropout_proof} \begin{proofof}{Lemma~\ref{lem:original_sparse}} Without loss of generality, suppose for each $\theta_i$ that the subset of $\lfloor h_i/2 \rfloor$ non-zero hidden units in each layer are all indexed between $1$ and $\lfloor h_i/2 \rfloor$. For $1 < i < d$, we can partition $A_i$ into quadrants such that $A_i=\left[\begin{array}{c|c} L_i & C_i \\ \hline D_i & R_i \end{array}\right]$. (Here, $L_i\in {\mathbb{R}}^{\fl{h_i/2}\times \fl{h_i/2}}$. If $h_i$ is odd, when we write $L_i$ in the other quadrants we implicitly pad it with zeros in a consistent manner.) Similarly, we can partition $A_1$ such that $A_1 = \left[\begin{array}{c} L_1 \\ \hline B_1 \end{array}\right]$ and $A_d$ such that $A_d = \left[\begin{array}{c|c} L_d & R_d \\ \end{array}\right]$. We will sometimes use the notation $A_i$ to refer to the value of $A_i$ at a given point on our path, while $A_i^\theta$ will always refer to the value of $A_i$ at $\theta$. We now proceed to prove via induction the existence of a path from $\theta$ to $\theta_i$ for all $i$ whose loss is bounded by $L(f_\theta)+\epsilon$, from which the main result immediately follows.\\ \noindent\textbf{Base case: from $\theta$ to $\theta_{d-1}$} As a base case of the induction, we need to construct a path from $\theta$ to $\theta_{d-1}$, such that the loss is bounded by $L(f_\theta)+\epsilon$. First, note that setting a particular subset of columns (e.g. the right half of columns) in $A_i$ to zero is equivalent to setting the corresponding rows (e.g. the bottom half of rows) of $A_{i-1}$ to zero. So from the fact that $L(f_{\theta_{d-1}}) \leq L(f_\theta)+\epsilon$ it follows that we can equivalently replace $A_d^{\theta}$ with $\left[\begin{array}{c|c} r L_d^{\theta} & 0 \\ \end{array}\right]$ without increasing our loss by more than $\epsilon$. In fact, because our loss function is convex over $A_d$ we can actually interpolate $A_d$ between $A_d^{\theta}$ and $\left[\begin{array}{c|c} r L_d^{\theta} & 0 \\ \end{array}\right]$ while keeping our loss below $L(f_\theta)+\epsilon$ at every point along this subpath. Then, because $R_d = 0$ we can modify both $D_{d-1}$ and $R_{d-1}$ any way we'd like without affecting the output of our network. In particular, we can interpolate $A_{d-1}$ between $A_{d-1}^{\theta}$ and $\left[\begin{array}{c|c} L_{d-1}^{\theta} & C_{d-1}^{\theta} \\ \hline 0 & 0 \end{array}\right]$ while keeping our loss constant long this subpath, thus arriving at $\theta_{d-1}$. \noindent \textbf{From $\theta_k$ to $\theta_{k-1}$} Suppose we have found a path from $\theta$ to $\theta_k$ such that (1) $A_d^{\theta_k} = \left[\begin{array}{c|c} r L_d^{\theta} & 0 \\ \end{array}\right]$, (2) $A_i^{\theta_k} = \left[\begin{array}{c|c} r L_{i}^{\theta} & 0 \\ \hline 0 & 0 \end{array}\right]$ for $k < i < d$, (3) $A_k^{\theta_k} = \left[\begin{array}{c|c} L_{k}^{\theta} & C_{k}^{\theta} \\ \hline 0 & 0 \end{array}\right]$, and (4) $A_i^{\theta_k} = A_i^{\theta}$ for $i < k$, such that the loss along the path is at most $L(f_{\theta}) + \epsilon$. Note that $\theta_{d-1}$ satisfies all these assumptions, including in particular (2) as there are of course no $A_i$ between $A_{d-1}$ and $A_{d}$. Now let us extend this path to $\theta_{k-1}$. First, because the rightmost columns of $A_i$ are zero for $k < i \leq d$, we can modify the bottom rows of $A_i$ for $k \leq i < d$ without affecting the output of our network. In particular, we can set $A_k$ to $\left[\begin{array}{c|c} L_k^{\theta} & C_k^{\theta} \\ \hline r L_k^{\theta} & 0 \end{array}\right]$, as well as $A_i$ to $\left[\begin{array}{c|c} r L_i^{\theta} & 0 \\ \hline 0 & r L_i^{\theta} \end{array}\right]$ for $k < i < d$. From the fact that the loss is convex over $A_d$ and that $L(f_{\theta_{k-1}}) < L(f_{\theta}) + \epsilon$, it then follows that we can set $A_d$ to $\left[\begin{array}{c|c} 0 & r L_d^{\theta} \\ \end{array}\right]$ via interpolation while keeping our loss below $L(f_{\theta}) + \epsilon$. In particular, note that because the off-diagonal blocks of $A_i$ are zero for $k < i < d$, interpolating between the leftmost columns of $A_d$ being non-zero and the rightmost columns of $A_d$ being non-zero simply amounts to interpolating between the outputs of the two subnetworks comprised respectively of the first $\lfloor h_i/2 \rfloor$ and last $\lfloor h_i/2 \rfloor$ rows of $A_i$ for $k \leq i < d$. Once we have the leftmost columns of $A_d$ set to zero and $A_i$ in block-diagonal form for $k < i < d$, we can proceed to modify the top rows of $A_k$ however we'd like without affecting the output of our network. Specifically, let us set $A_k$ to $\left[\begin{array}{c|c} r L_k^{\theta} & 0 \\ \hline r L_k^{\theta} & 0 \end{array}\right]$. We can then reset $A_d$ to $\left[\begin{array}{c|c} r L_d^{\theta} & 0 \\ \end{array}\right]$ via interpolation---this time without affecting our loss since the weights of our two subnetworks are equivalent---and afterwards set $D_k$ to zero and $R_i$ to zero for $k \leq i < d$---again without affecting our loss since the rightmost columns of $A_d$ are now zero, meaning that the bottom rows of $A_i$ have no affect on our network's output. Following these steps, we will have $A_i = \left[\begin{array}{c|c} r L_i^{\theta} & 0 \\ \hline 0 & 0 \end{array}\right]$ for $k \leq i < d$ and $A_d = \left[\begin{array}{c|c} r L_d^{\theta} & 0 \\ \end{array}\right]$. And so we are now free to set the bottom rows of $A_{k-1}$ to zero without affecting our loss, thus arriving at $\theta_{k-1}$. \iffalse \begin{figure}[ht] \centering \begin{align*} \begin{matrix} \rtwog{2L_5}{0}& \mattg{2L_4}{}{}{} & \mattg{2L_3}{}{}{} &\mattg{L_2}{C_2}{D_2}{R_2}\\ \rtwog{2L_5}{0}& \mattg{2L_4}{}{}{2L_4} & \mattg{2L_3}{}{}{2L_3}& \mattg{L_2}{C_2}{2L_2}{}\\ \rtwog{}{2L_5}& \mattg{2L_4}{}{}{2L_4} & \mattg{2L_3}{}{}{2L_3}& \mattg{L_2}{C_2}{2L_2}{}\\ \rtwog{}{2L_5} &\mattg{2L_4}{}{}{2L_4} & \mattg{2L_3}{}{}{2L_3} &\mattg{2L_2}{}{2L_2}{}\\ \rtwog{2L_5}{} &\mattg{2L_4}{}{}{2L_4} & \mattg{2L_3}{}{}{2L_3}& \mattg{2L_2}{}{2L_2}{}\\ \rtwog{2L_5}{} &\mattg{2L_4}{}{}{} & \mattg{2L_3}{}{}{} &\mattg{2L_2}{}{}{} \end{matrix} \end{align*} \caption{Example path, $d=5$, from $\theta_3$ to $\theta_2$. $L_i^\theta$ for $2\le i\le 5$ are shown. \rcknote{I think now that the proof has been cleaned up we no longer need the figure. But if we do keep it, then I can polish it.}} \label{fig:path-ex} \end{figure} \fi \end{proofof} \begin{lemma}\label{lem:permutation} Let $\theta$ be a parameter such that at least $\lceil h_i/2 \rceil$ of the units in each hidden layer have been set to zero. Then we can achieve an arbitrary permutation of the non-zero hidden units of $\theta$ via a path consisting of just 5 line segments such that our loss is constant along this path. \end{lemma} \begin{proof} Let $\pi: [h_i] \mapsto [h_i]$ be some permutation over the units in layer $i$. Without loss of generality, suppose all non-zero units in layer $i$ are indexed between $0$ and $\lfloor h_i/2 \rfloor$, and define $\pi':\left[\lfloor h_i/2 \rfloor\right] \mapsto [h_i] \setminus \left[\lfloor h_i/2 \rfloor\right]$ as any one-to-one mapping such that $\pi'(i) = \pi(i)$ if $\pi(i) \in [h_i] \setminus \left[\lfloor h_i/2 \rfloor\right]$. Note that when we refer to a unit $j$ as ``set to zero'', we mean that both row $j$ of $A_i$ and column $j$ of $A_{i+1}$ have been set to zero. To permute the units of layer $i$, we can first simultaneously copy the non-zero rows of $A_i$ into a subset of the rows that have been set to zero. Specifically, for $j \in \left[\lfloor h_i/2 \rfloor\right]$ we can copy row $j$ of $A_i$ into row $\pi'(j)$ via interpolation and without affecting our loss, due to the fact that column $\pi'(j)$ in $A_{i+1}$ is set to zero. We can then set column $j$ of $A_{i+1}$ to zero while copying its value to column $\pi'(j)$, again via interpolation and without affecting our loss since rows $j$ and $\pi'(j)$ of $A_i$ are now equivalent. Following these first two steps, the first $\lfloor h_i/2 \rfloor$ columns of $A_{i+1}$ will have been set to zero. Thus, for all $j \in \left[\lfloor h_i/2 \rfloor\right]$ such that $\pi(j) \in [h_i/2]$ we can copy row $\pi'(j)$ of $A_i$ into row $\pi(j)$ without affecting our loss. We can then set column $\pi'(j)$ of $A_{i+1}$ to zero while copying its value into column $\pi(j)$ via interpolation and without affecting our loss since rows $\pi'(j)$ and $\pi(j)$ of $A_i$ are now equivalent. Setting row $\pi'(j)$ to zero---again for all $j \in \left[\lfloor h_i/2 \rfloor\right]$ such that $\pi(j) \in [h_i/2]$---completes the permutation for layer $i$. Note that because we leave the output of layer $i$ unchanged throughout the course of permuting the units of layer $i$, it follows that we can perform all swaps across all layers simultaneously. And so from the fact that permuting each layer can be done in 5 steps---each of which consists of a single line segment in parameter space---the main result immediately follows. \end{proof} \begin{proofof}{Lemma~\ref{lem:drop-connect}} Without loss of generality, suppose for $\theta$ that the subset of $\lfloor h_i/2 \rfloor$ non-zero hidden units in each layer $i$ are all indexed between $0$ and $\lfloor h_i/2 \rfloor$. Note that when we refer to a unit as ``set to zero", we mean that both the corresponding row of $A_i$ and column of $A_{i+1}$ have been set to zero. Adopting our notation in Lemma \ref{lem:original_sparse}, we can construct a path from $\theta$ to $\theta'$ as follows. First, from the fact that the second half of units in each hidden layer $i$ have been set to zero in $\theta$ we have that $A_1^{\theta} = \left[\begin{array}{c} L_1^{\theta} \\ \hline 0 \end{array}\right]$, $A_i^{\theta} = \left[\begin{array}{c|c} L_i^{\theta} & 0 \\ \hline 0 & 0 \end{array}\right]$ for $1 < i < d$, and $A_d^{\theta} = \left[\begin{array}{c|c} L_d^{\theta} & 0 \\ \end{array}\right]$. Similarly, half the rows of $A_1^{\theta'}$ are zero, half the rows and columns of $A_i^{\theta'}$ are zero for $1 < i < d$, and half the columns of $A_d^{\theta'}$ are zero. Note that the indices of the non-zero units in $\theta'$ may intersect with those of the non-zero units in $\theta$. For $1 \leq i \leq d$, let $B_i$ denote the submatrix of $A_i$ corresponding to the non-zero rows and columns of $A_i^{\theta'}$. Because $A_i^{\theta}$ are block-diagonal for $1 < i < d$ and the rightmost columns of $A_d^{\theta}$ are zero, starting from $\theta$ we can modify the bottom rows of $A_i$ for $1 \leq i < d$ any way we'd like without affecting our loss---as done in our path construction for Lemma \ref{lem:original_sparse}. In particular, let us set $A_i$ to $\left[\begin{array}{c|c} L_i^{\theta} & 0 \\ \hline 0 & B_i^{\theta'} \end{array}\right]$ for $1 < i < d$ and $A_1$ to $\left[\begin{array}{c} L_1^{\theta} \\ \hline B_1^{\theta'} \end{array}\right]$. Then, from the fact that our loss function is convex over $A_d$ it follows that we can set $A_d$ to $\left[\begin{array}{c|c} 0 & B_d^{\theta'} \\ \end{array}\right]$ via interpolation while keeping our loss below $\max\{L(f_{\theta}),L(f_{\theta'})\}$. Finally, from the fact that the leftmost columns of $A_d$ are now zero and $A_i$ are still block-diagonal for $1 < i < d$, it follows that we can set $L_i$ to zero for $1 \leq i < d$ without affecting our loss---thus making $A_i$ equal to $\left[\begin{array}{c|c} 0 & 0 \\ \hline 0 & B_i^{\theta'} \end{array}\right]$ for $1 < i < d$ and $A_1$ equal to $\left[\begin{array}{c} 0 \\ \hline B_1^{\theta'} \end{array}\right]$. To complete our path from $\theta$ to $\theta'$ we now simply need to permute the units of each hidden layer so as to return the elements of $B_i^{\theta'}$ to their original positions in $A_i$ for each $i$. From Lemma~\ref{lem:permutation} it follows that we can accomplish this permutation via 5 line segments in parameter space without affecting our loss. Combined with the previous steps above, we have constructed path from $\theta$ to $\theta'$ consisting of a total of 8 line segments whose loss is bounded by $\max\{L(f_{\theta}),L(f_{\theta'})\}$. \end{proofof} \begin{proofof}{Theorem~\ref{thm:connect_via_dropout}} First, from Lemma \ref{lem:original_sparse} we know we can construct paths from both $\theta^A$ to $\theta_1^A$ and $\theta^B$ to $\theta_1^B$ while keeping our loss below $L(f_{\theta^A})+\epsilon$ and $L(f_{\theta^B})+\epsilon$ respectively. From Lemma \ref{lem:drop-connect} we know that we can construct a path from $\theta_1^A$ to $\theta_1^B$ such that the loss along the path is bounded by $\max\{L(f_{\theta_1^A}),L(f_{\theta_1^B})\}$. The main result then follows from the fact that $L(f_{\theta_1^A}) \leq L(f_{\theta^A})+\epsilon$ and $L(f_{\theta_1^B}) \leq L(f_{\theta^B})+\epsilon$ due to $\theta^A$ and $\theta^B$ both being $\epsilon$-dropout stable. \end{proofof} \section{Connectivity of dropout-stable optima} \label{sec:dropout} In this section we show that \emph{dropout-stable} solutions are connected. More concretely, we define a solution $\theta$ to be $\epsilon$-dropout stable if we can remove a subset of half its neurons in each layer such that the loss remains steady. \begin{definition} \label{def:drop-stability} (Dropout Stability) A solution $\theta$ is \vocab{$\epsilon$-dropout stable} if for all $i$ such that $1 \leq i < d$, there exists a subset of at most $\lfloor h_j/2 \rfloor$ hidden units in each of the layers $j$ from $i$ through $d-1$ such that after rescaling the outputs of these hidden units (or equivalently, the corresponding rows and/or columns of the relevant weight matrices) by some factor $r$\footnote{Note our results will also work if $r$ is allowed to vary for each layer $i$.} and setting the outputs of the remaining units to zero, we obtain a parameter $\theta_i$ such that $L(f_{\theta_i}) \leq L(f_\theta) + \epsilon$. \end{definition} Intuitively, if a solution is $\epsilon$-dropout stable then it is essentially only using half of the network's capacity. We show that such solutions are connected: \begin{theorem} \label{thm:connect_via_dropout} Let $\theta^A$ and $\theta^B$ be two $\epsilon$-dropout stable solutions. Then there exists a path in parameter space $\pi : [0,1] \to \Theta$ between $\theta^A$ and $\theta^B$ such that $L(f_{\pi(t)}) \leq \max \{L(f_{\theta^A}),L(f_{\theta^B})\}+\epsilon$ for $0 \leq t \leq 1$. In other words, letting $\mathcal C$ be the set of solutions that are $\epsilon$-dropout stable, a ReLU network has the $\epsilon$-mode connectivity property with respect to $\mathcal C$. \end{theorem} Our path construction in Theorem~\ref{thm:connect_via_dropout} consists of two key steps. First we show that we can rescale at least half the hidden units in both $\theta^A$ and $\theta^B$ to zero via continuous paths of low loss, thus obtaining two parameters $\theta_1^A$ and $\theta_1^B$ satisfying the criteria in Definition~\ref{def:drop-stability}. \begin{lemma}\label{lem:original_sparse} Let $\theta$ be an $\epsilon$-dropout stable solution and let $\theta_i$ be specified as in Definition \ref{def:drop-stability} for $1 \leq i < d$. Then there exists a path in parameter space $\pi: [0,1] \to \Theta$ between $\theta$ and $\theta_1$ such that $L(f_{\pi(t)}) \leq L(f_\theta) + \epsilon$ for $0 \leq t \leq 1$. \end{lemma} Though na\"ively one might expect to be able to directly connect the weights of $\theta$ and $\theta_1$ via interpolation, such a path may incur high loss as the loss function is not convex over $\Theta$. In our proof of Lemma~\ref{lem:original_sparse}, we rely on a much more careful construction. The construction uses two types of steps: (a) interpolate between two weights in the top layer (the loss is convex in the top layer weights); (b) if a set of neurons already have 0 output weights, then we can change their input weights arbitrarily. See Figure~\ref{fig:path-ex} for a path for a 3-layer network. Here we have separated the weight matrices into blocks: $A_3 = \rtwog{L_3}{R_3}$, $A_2 = \mattg{L_2}{C_2}{D_2}{R_2}$ and $A_1 = \ctwog{L_1}{B_1}$. The path consist of 6 steps alternating between type (a) and type (b). Note that for all the type (a) steps, we only update the top layer weights; for all the type (b) steps, we only change rows of a weight matrix (inputs to neurons) if the corresponding columns in the previous matrix (outputs of neurons) are already 0. In Section~\ref{sec:dropout_proof} we show how such a path can be generalized to any number of layers. \begin{figure}[ht] \centering \begin{align*} \begin{matrix} & A_3 & A_2 & A_1 & \\ (1) & \rtwog{L_3}{R_3}& \mattg{L_2}{C_2}{D_2}{R_2} & \ctwog{L_1}{B_1} & \\ (2) & \rtwog{rL_3}{0}& \mattg{L_2}{C_2}{D_2}{R_2} & \ctwog{L_1}{B_1} & (a)\\ (3) & \rtwog{rL_3}{0}& \mattg{L_2}{C_2}{rL_2}{0} & \ctwog{L_1}{B_1} & (b)\\ (4) & \rtwog{0}{rL_3}& \mattg{L_2}{C_2}{rL_2}{0} & \ctwog{L_1}{B_1} & (a)\\ (5) & \rtwog{0}{rL_3}& \mattg{rL_2}{0}{rL_2}{0} & \ctwog{L_1}{B_1} & (b)\\ (6) & \rtwog{rL_3}{0}& \mattg{rL_2}{0}{rL_2}{0} & \ctwog{L_1}{B_1} & (a)\\ (7) & \rtwog{rL_3}{0}& \mattg{rL_2}{0}{0}{0} & \ctwog{L_1}{0} & (b) \end{matrix} \end{align*} \caption{Example path, 6 line segments from a 3-layer network to its dropout version.} \label{fig:path-ex} \end{figure} We then show that we can permute the hidden units of $\theta_1^A$ such that its non-zero units do not intersect with those of $\theta_1^B$, thus allowing us two interpolate between these two parameters. This is formalized in the following lemma and the proof is deferred to supplementary material. \begin{lemma}\label{lem:drop-connect} Let $\theta$ and and $\theta'$ be two solutions such that at least $\lceil h_i/2 \rceil$ of the units in each hidden layer have been set to zero in both. Then there exists a path in parameter space $\pi: [0,1] \to \Theta$ between $\theta$ and $\theta'$ with 8 line segments such that $L(f_{\pi(t)}) \leq \max\{L(f_\theta),L(f_{\theta'})\}$. \end{lemma} Theorem~\ref{thm:connect_via_dropout} follows immediately from Lemma~\ref{lem:original_sparse} and Lemma~\ref{lem:drop-connect}, as one can first connect $\theta^A$ to its dropout version $\theta^A_1$ using Lemma~\ref{lem:original_sparse}, then connect $\theta^A_1$ to dropout version $\theta^B_1$ of $\theta^B$ using Lemma~\ref{lem:drop-connect}, and finally connect $\theta^B_1$ to $\theta^B$ using Lemma~\ref{lem:original_sparse} again. Finally, our results can be generalized to convolutional networks if we do {\em channel-wise} dropout~\citep{tompson2015efficient, keshari2018guided}. \begin{remark} \label{rmk:channelwise} For convolutional networks, a {\em channel-wise} dropout will randomly set entire channels to 0 and rescale the remaining channels using appropriate factor. Theorem~\ref{thm:connect_via_dropout} can be extended to work with channel-wise dropout on convolutional networks. \end{remark} \section{Disconnected modes in two-layer nets} \label{sec:example:main}\label{sec:examples:main} The mode connectivity property is not true for every neural network. \citet{freeman2016topology} gave a counter-example showing that if the network is not overparametrized, then there can be different global minima of the neural network that are not connected. \citet{venturi2018spurious} showed that spurious valleys can exist for 2-layer ReLU nets with an arbitrary number of hidden units, but again they do not extend their result to the overparametrized setting. In this section, we show that even if a neural network is overparametrized---in the sense that there exists a network of smaller width that can achieve optimal loss---there can still be two global minimizers that are not connected. \iffalse How overparametrized does a network need to be in order for its modes to be connected? In this section we answer this problem on a simple setting of two-layer neural network. We first show that if the input distribution has support in all directions of ${\mathbb{R}}^d$, then the global minima of the neural network are connected. \begin{theorem}\label{thm:tess_twotimes} Suppose $2h\leq h'$ and the loss function $l(\cdot, \cdot)$ is convex in the output of the student network and $l(y,\hat{y}) = 0$ if and only if $y = \hat{y}$. Then the set of global minimizers is connected. \end{theorem} Intuitively, this is true because when the support of $x$ contains every direction, in order for the output of the student network to be the same as the teacher network, they must have the same {\em tessellation} in the sense that the linear regions of the output needs to be the same. Note that this result only gives a weaker notion of mode connectivity where all the global minimizers are connected, it does not imply that there cannot be local minimizers that are not connected to any global minimizers. The above theorem seems to confirm the intuition that one only needs two overparametrize the network by a factor of 2 in order to have mode connectivity. However, it heavily relies on the fact that the input distribution has support in every direction. \fi In particular, suppose we are training a two-layer ReLU student network with $h$ hidden units to fit a dataset generated by a ground truth two-layer ReLU teacher network with $h_t$ hidden units such that the samples in the dataset are drawn from some input distribution and the labels computed via forward passes through the teacher network. The following theorem demonstrates that regardless of the degree to which the student network is overparametrized, we can always construct such a dataset for which global minima are not connected. \begin{theorem}\label{thm:counterexample} For any width $h$ and and convex loss function $l: {\mathbb{R}} \times {\mathbb{R}} \mapsto {\mathbb{R}}$ such that $l(y,\hat y)$ is minimized when $y = \hat y$, there exists a dataset generated by ground-truth teacher network with two hidden units (i.e. $h_t = 2$) and one output unit such that global minimizers are not connected for a student network with $h$ hidden units. \end{theorem} Our proof is based on an explicit construction. The detailed construction is given in Section~\ref{sec:example}. \section{Experiments} \label{sec:experiments} We now demonstrate that our assumptions and theoretical findings accurately characterize mode connectivity in practical settings. In particular, we empirically validate our claims using standard convolutional architectures---for which we treat individual filters as the hidden units and apply channel-wise dropout (see Remark~\ref{rmk:channelwise})---trained on datasets such as CIFAR-10 and MNIST. Training with dropout is not necessary for a network to be either dropout-stable or noise-stable. Recall that our definition of dropout-stability merely requires the existence of a particular sub-network with half the width of the original that achieves low loss. Moreover, as Theorem~\ref{cor:teacher_student} suggests, if there exists a narrow network that achieves low los , then we need only be able to drop out a number of filters equal to the width of the narrow network to connect local minima. \begin{figure}[!htb] \minipage{0.32\textwidth} \includegraphics[width=1\linewidth]{figures/drop.png} \endminipage\hfill \minipage{0.32\textwidth} \includegraphics[width=1\linewidth]{figures/interpolate.png} \endminipage\hfill \minipage{0.32\textwidth}% \includegraphics[width=1\linewidth]{figures/width.png} \endminipage \caption{Results for convolutional networks trained on MNIST.} \label{fig:mnist} \end{figure} First, we demonstrate in the left plot in Figure~\ref{fig:mnist}, on MNIST that 3-layer convolutional nets (not counting the output layer) with 32 $3 \times 3$ filters in each layer tend to be fairly dropout stable---both in the original sense of Definition~\ref{def:drop-stability} and especially if we relax the definition to allow for wider subnetworks---despite the fact that no dropout was applied in training. For each trial, we randomly sampled $20$ dropout networks with $\emph{exactly}$ $\lfloor 32(1-p) \rfloor$ non-zero filters in each layer and report the performance of the best one. In the center plot, we verify for $p = 0.2$ we can construct a linear path $\pi(t):{\mathbb{R}} \to \Theta$ from our convolutional net to a dropout version of itself. Similar results were observed when varying $p$. Finally, in the right plot we demonstrate the existence of 3-layer convolutional nets just a few filters wide that are able to achieve low loss on MNIST. Taken together, these results indicate that our path construction in Theorem~\ref{cor:teacher_student} performs well in practical settings. \begin{figure}[!th] \begin{minipage}[b]{0.8\textwidth} \begin{subfigure}[t]{0.27\textwidth} \centering \includegraphics[height=2.9cm, width=3.5cm]{figures/pannel_cushion_layer_6.pdf} \end{subfigure} \begin{subfigure}[t]{0.27\textwidth} \centering \includegraphics[height=2.9cm, width=3.5cm]{figures/pannel_contraction_layer_6.pdf} \end{subfigure} \begin{subfigure}[t]{0.27\textwidth} \centering \includegraphics[height=2.9cm, width=3.5cm]{figures/pannel_interlayer_cushion_layer_6.pdf} \end{subfigure} \begin{subfigure}[t]{0.27\textwidth} \centering \includegraphics[height=2.9cm, width=3.5cm]{figures/pannel_smoothness_layer_6.pdf} \end{subfigure} \end{minipage} \hspace{-4.5cm} \begin{minipage}[b]{0.1\textwidth} \centering \begin{subfigure}[t]{0.8\textwidth} \centering \includegraphics[height=5cm, width=7cm]{figures/vgg_path.png} \end{subfigure} \end{minipage} \caption{Left) Distribution of layer cushion, activation contraction, interlayer cushion and interlayer smoothness of the 6-th layer of a VGG-11 network on the training set. The other layers' parameters are exhibited in Section~\ref{appdix:verification}. Right) The loss and training accuracy along the interpolation path between two noise stable VGG-11 networks, described by Theorem~\ref{lem:dropout_crosslayer}.} \label{fig:properties} \end{figure} We also demonstrate that the VGG-11~\citep{simonyan2014very} architecture trained with channel-wise dropout~\citep{tompson2015efficient, keshari2018guided} with $p=0.25$ at the first three layers\footnote{we find the first three layers are less resistant to channel-wise dropout.} and $p=0.5$ at the others on CIFAR-10 converges to a noise stable minima---as measured by layer cushion, interlayer cushion, activation contraction and interlayer smoothness. The networks under investigation achieves 95\% training and 91\% test accuracy with channel-wise dropout \emph{activated}, in comparison to 99\% training and 92\% test accuracy with dropout turned off. Figure~\ref{fig:properties} plots the distribution of the noise stability parameters over different data points in the training set. These plots suggest that they behave nicely. Interestingly, we also discovered that networks trained without channel-wise dropout exhibit similarly nice behavior on all but the first few layers. Finally, we demonstrate that the training loss and accuracy along the path described by Theorem~\ref{lem:dropout_crosslayer} between two noise stable VGG-11 networks $\theta_A$ and $\theta_B$ remain fairly low and high respectively. Further details on all experiments are provided in Section~\ref{appdix:hyperparameters}. \section{Introduction} Efforts to understand how and why deep learning works have led to a focus on the {\em optimization landscape} of training loss. Since optimization to near-zero training loss occurs for many choices of random initialization, it is clear that the landscape contains many global optima (or near-optima). However, the loss can become quite high when interpolating between found optima, suggesting that these optima occur at the bottom of \textquotedblleft valleys\textquotedblright\ surrounded on all sides by high walls. Therefore the phenomenon of {\em mode connectivity}~\citep{garipov2018loss,draxler2018essentially} came as a surprise: optima (at least the ones discovered by gradient-based optimization) are connected by simple paths in the parameter space, on which the loss function is almost constant. In other words, the optima are not walled off in separate valleys as hitherto believed. More surprisingly, the paths connecting discovered optima can be piece-wise linear with as few as two segments. Mode connectivity begs for theoretical explanation. One paper~\citep{freeman2016topology} attempted such an explanation for $2$-layer nets, even before the discovery of the phenomenon in multilayer nets. However, they require the width of the net to be exponential in some relevant parameters. Others \citep{venturi2018spurious, liang2018understanding, nguyen2018loss, nguyen2019connected} require special structure in neural network where the number of neurons need to be more than the number of training data points. Thus it remains an open problem to explain even the 2-layer case with realistic parameter settings, let alone standard multilayer architectures. At first sight, finding a mathematical explanation of mode connectivity phenomenon for multilayer nets---e.g., for a $50$-layer ResNet on ImageNet---appears very challenging. However, the glimmer of hope is that since the phenomenon exists for a variety of architectures and datasets, it must arise from some generic property of trained nets. The fact that the connecting paths between optima can have as few as two linear segments further bolsters this hope. Strictly speaking, empirical findings such as in~\citep{garipov2018loss,draxler2018essentially} do not show connectivity between {\em all} optima, but only for {\em typical} optima discovered by gradient-based optimization. It seems an open question whether connectivity holds for all optima in overparametrized nets. Section~\ref{sec:example:main} answers this question, via a simple example of an overparametrized two-layer net, not all of whose optima are connected via low-cost paths. Thus to explain mode connectivity one must seek generic properties that hold for optima obtained via gradient-based optimization on realistic data. A body of work that could be a potential source of such generic properties is the ongoing effort to understand the generalization puzzle of over-parametrized nets---specifically, to understand the \textquotedblleft true model capacity\textquotedblright. For example, \citet{morcos2018importance} note that networks that generalize are insensitive to linear restrictions in the parameter space. \citet{arora2018stronger} define a {\em noise stability} property of deep nets, whereby adding Gaussian noise to the output of a layer is found to have minimal effect on the vector computed at subsequent layers. Such properties seem to arise in a variety of architectures purely from gradient-based optimization, without any explicit noise-injection during training---though of course using small-batch gradient estimates is an implicit source of noise-injection. (Sometimes training also explicitly injects noise, e.g. dropout or batch-normalization, but that is not needed for the noise stability to emerge.) Since resilience to perturbations arises in a variety of architectures, such resilience counts as a \textquotedblleft generic\textquotedblright\ property, and it is natural to prove mode-connectivity as a consequence of this property. We carry this out in the current paper. Note that our goal here is not to explain every known detail of mode connectivity, but rather to give a plausible first-cut explanation. First, in Section~\ref{sec:dropout} we explain mode connectivity by assuming the network is trained via dropout. In fact, the desired property is weaker: so long as there {\em exists} even a {\em single} dropout pattern that keeps the training loss close to optimal on the two solutions, our proof constructs a piece-wise linear path between them. The number of linear segments grows linearly with the depth of the net. Then, in Section~\ref{sec:noise_stable} we make a stronger assumption of noise stability along the lines of \cite{arora2018stronger} and show that it implies mode-connectivity using paths with $10$ linear segments. While this assumption is strong, it appears to be close to what is satisfied in practice. (Of course, one could explicitly train deep nets to satisfy the needed noise stability assumption, and the theory applies directly to them.) \iffalse Efforts to understand how and why deep learning works has also led to a focus on the {\em optimization landscape} of training loss. neural networks, in particular, the properties of local and global optima of the loss function. Recent empirical results~\citep{garipov2018loss,draxler2018essentially} concern the interesting phenomena of mode connectivity: minima of neural networks can be connected by a simple path, such that the loss function is almost constant along the path. If all minima of neural networks are connected, then the loss function cannot have a spurious valley -- a point with suboptimal objective value that cannot be connected to any global minima without increasing the loss value. Prior works have conjectured that the mode connectivity property is related to the overparametrization of neural networks. Indeed, if there are two local minima each using only 1/2 of the neurons in every layer, then it is clear that one can use the extra neurons in the network to connect the two points \rcknote{unclear what "using only" 1/2 means (pretty unlikely that half would just be zero), maybe instead we can say half are "redundant" (e.g. they lie in the span of the remaining units)}. This intuition suggests that local minima can be connected as long as the network is overparametrized by a constant factor. However, existing theoretical analysis of mode connectivity \citep{freeman2016topology, venturi2018spurious, liang2018understanding, nguyen2018loss} require the neural network to be extremely overparametrized with number of neuron in a layer more than the number of training samples \rcknote{Freeman and Bruna don't require more units than data points, rather they need exponential width relative to the desired energy barrier. Also, some of the others require $>2\times$ the number of training samples, not just $>$.} . Our paper bridges the gap by showing the following results: \begin{enumerate} \item For a two-layer neural network, even if the number of neurons in the hidden layer is much larger than the minimal number of neurons for a ground truth neural network, there can still exist two local minima that cannot be connected. \item On the other hand, if the two local minima are drop-out stable (the loss does not change significantly even if 1/2 of neurons are randomly turned off), then the two minima can be connected by a path. \item If the local minima are further \rcknote{"further" understates our result since it implies that we must assume both noise stability and dropout stability, when in reality we show that noise stability implies dropout stability} noise stable (in a notion similar to that defined in \citet{arora2018stronger}), then the two minima can be connected by a simple path with 4 line segments \rcknote{the exact number may be slightly higher, will confirm later}. \end{enumerate} In summary, when the network is extremely overparametrized, although not all local minima are connected, those that are robust (either in the sense of drop-out or noise stability) are still connected. \fi \subsection{Related work} The landscape of the loss function for training neural networks has received a lot of attention. \citet{dauphin2014identifying, choromanska2015loss} conjectured that local minima of multi-layer neural networks have similar loss function values, and proved the result in idealized settings. For linear networks, it is known \citep{kawaguchi2016deep} that all local minima are also globally optimal. Several theoretical works explored whether a neural network has spurious valleys (non-global minima that are surrounded by other points with higher loss). \citet{freeman2016topology} showed that for a two-layer net, if it is sufficiently overparametrized then all the local minimizers are (approximately) connected. However, in order to guarantee a small loss along the path they need the number of neurons to be exponential in the number of input dimensions. \citet{venturi2018spurious} proved that if the number of neurons is larger than the number of training samples or the intrinsic dimension (infinite for standard architectures), then the neural network cannot have spurious valleys. \citet{liang2018understanding} proved similar results for the binary classification setting. \citet{nguyen2018loss, nguyen2019connected} relaxed the requirement on overparametrization, but still requires the output layer to have more direct connections than the number of training samples. Some other papers study the existence of spurious local minima. \citet{yun2018critical} showed that in most cases neural networks have spurious local minima. Note that a local minimum only need to have loss no larger than the points in its neighborhood, so a local minimum is not necessarily a spurious valley. \citet{safran2018spurious} found spurious local minima for simple two-layer neural networks under a Gaussian input distribution. These spurious local minima are indeed spurious valleys as they have positive definite Hessian. \section{Proofs for connectivity via noise stability}\label{sec:noise_stability_proof} In this section, we give detailed proofs showing that noise stability implies connectivity. In the following lemma, we first show that the network output is stable if we randomly dropout columns in a single layer using Algorithm~\ref{alg:dropout}. \begin{lemma}\label{lem:dropout_layer} For any layer $2\leq i\leq d$, let $G=\{(U^{(l)},x^{(l)})\}_{l=1}^m$ be a set of matrix/vector pairs of size $m$ where $U\in{\mathbb{R}}^{h_d \times h_i}$ and $x\in{\mathbb{R}}^{h_{i-1}}$ satisfying $\n{x}_{\infty} = O\pa{\frac{\n{x}}{\sqrt{h_{i-1}}}}$. Given $A_i$, let $\hat{A}_i\in {\mathbb{R}}^{h_{i}\times h_{i-1}}$ be the output of Algorithm~\ref{alg:dropout} with dropout probability $0<p\le\fc 34$. Assume $\n{[A_i]_j}=O(\sqrt{p})\n{A_i}_F$ for $1\leq j\leq h_{i-1}.$ Given any $0<\delta<1$, let $\epsilon'=O\pa{\sqrt{\frac{\log(mh_d/\delta)p}{h_{\min}}} }$, with probability at least $1-\delta$, we have for any $(U,x)\in G$ that $\|U (\hat{A}_i - A_i) x\| \leq {\epsilon}'\|A_i\|_F\|U\|\|x\|$. Further assuming $h_{\min}=\Omega\pa{\frac{\log(1/\delta)}{p}}$, we know with probability at least $1-\delta,$ no less than $\frac{2}{3}p$ fraction of columns in $\hat{A}_i$ are zero vectors. \end{lemma} Intuitively, this lemma upper-bounds the change in the network output after dropping out a single layer. In the lemma, we should think of $x$ as the input to the current layer, $A_i$ as the layer matrix and $U$ as the Jacobian of the network output with respect to the layer output. If the activation pattern does not change after the dropping out, $U\hat{A}_i x$ is exactly the output of the dropped out network and $\|U (\hat{A}_i - A_i) x\|$ is the change in the network output. \begin{proofof}{Lemma~\ref{lem:dropout_layer}} Fixing $2\leq i\leq d$ and one pair $(U,x)\in G$, we show with probability at least $1-\frac{\delta}{m}$, $\|U (\hat{A}_i - A_i) x\| \leq {\epsilon}'\|A_i\|_F\|U\|\|x\|$. Let $U_k$ be the $k$-th column of $U$. Then by definition of $\hat A_i$ in the algorithm, we know \begin{align*} U(\hat{A}_i-A_i)x & = \sum_{k,j}U_k [A_i]_{kj} x_j (\delta_j-1)\\ &= \sum_{j}\pa{\sum_k U_k [A_i]_{kj}} x_j (\delta_j-1), \end{align*} where $\delta_j$ is an i.i.d. Bernoulli random variable which takes the value $0$ with probability $p$ and takes the value $\frac{1}{1-p}$ with probability $(1-p)$. Let $[A_i]_j$ be the $j$-th column of $A_i$. Because $p\le \fc 34$, $\rc{1-p}=O(1)$ (any $p$ bounded away from 1 will work). Hence the norm for each individual term can be bounded as follows. \begin{align*} \ve{\pa{\sum_k U_k [A_i]_{kj}} x_j (\delta_j-1)}&\stackrel{(*)}\leq O\pf{\n{x}}{\sqrt{h_{i-1}}}\n{U[A_i]_j}\\ &\leq O\pf{\n{x}}{\sqrt{h_{\min}}} \n{U}\n{[A_i]_j}\\ &\stackrel{(\dagger)}{\leq} O\pf{\sqrt{p}\n{U}\n{A_i}_F\n{x}}{\sqrt{h_{\min}}}, \end{align*} where (*) uses the assumption that $\n{x}_{\infty} = O\pf{\n{x}}{\sqrt{h_{i-1}}}$ and $(\dagger)$ holds because we assume $\n{[A_i]_j}=O(\sqrt{p})\n{A_i}_F$ for $1\leq j\leq h_{i-1}.$ For the total variance, we have \begin{align*} \sigma^2 :&= \sum_j {\mathbb{E}}\ba{\ve{ \pa{\sum_k U_k [A_i]_{kj}} x_j (\delta_j-1)}^2}\\ &\leq \sum_j \ns{U[A_i]_j}|x_j|^2\pa{(0-1)^2\times p + \pa{\frac{1}{1-p}-1}^2\times (1-p) }\\ &\stackrel{(*)}= \sum_j \ns{U[A_i]_j}\cdot O\pf{\ns{x}}{h_{i-1}}\cdot p\pa{1+\frac{p}{1-p}}\\ &\leq \ns{UA_i}_F\cdot O\pf{\ns{x}}{h_{\min}}\cdot p\\ &\leq O\pf{p\ns{U}\ns{A_i}_F\ns{x}}{h_{\min}}, \end{align*} where inequality $(*)$ uses the assumption that $\n{x}_{\infty} = O\pf{\n{x}}{\sqrt{h_{i-1}}}$. Then, by the vector Bernstein inequality (Lemma~\ref{lm:vectorBernstein}), we know given $0<\delta<1$, there exists $\epsilon'=O\pa{\sqrt{\frac{p \log(mh_d/\delta)}{h_{\min}}} }$, with probability at least $1-\frac{\delta}{m}$, we have $$\|U (\hat{A}_i - A_i) x\| \leq {\epsilon}'\|A_i\|_F\|U\|\|x\|.$$ Taking the union bound over all $(U,x)$ pairs in $G$, we know that with probability at least $1-\delta$, for any $(U,x)\in G$, $\|U (\hat{A}_i- A_i) x\| \leq {\epsilon}'\|A_i\|_F\|U\|\|x\|.$ Suppose $h_{\min}=\Omega\pa{\frac{\log(1/\delta)}{p}}$; then by the Chernoff bound, we know with probability at least $1-\delta,$ the dropped out fraction is at least $\frac{2}{3}p$. Taking another union bound concludes our proof. \end{proofof} Now we are ready to prove Lemma~\ref{lem:dropout_crosslayer}. The idea is similar to \citep{arora2018stronger}, but we give the proof here for completeness. \dropoutcrosslayer* \begin{proofof}{Lemma~\ref{lem:dropout_crosslayer}} We first bound the difference between the dropped out network $\theta_1$ and the original network $\theta$. \paragraph{Bounding $\|f_\theta(x) - f_{\theta_1}(x)\|$:} We first show that with probability at least $1/2-\delta,$ $\|f_\theta(x) - f_{\theta_1}(x)\| =\|x^d - \hat x^d_d\| \le {\epsilon}'\|f_{\theta}(x)\|,$ where ${\epsilon}'$ will be specified later. For any layer $i\geq 1$ and letting $\hat{x}^j_i$ be the vector before activation at layer $j$ if the weights $A_2,\dots,A_i$ are replaced by $\hat{A}_2,\dots,\hat{A}_i$. According to Lemma~\ref{lem:dropout_layer}, for any layer $2\leq i\leq d$, given $0<\delta<1$, let $\epsilon'=O\pa{\sqrt{\frac{p c^2d^2\log(md h_d/\delta)}{h_{\min}\min\limits_{2\leq i\leq d}(\mu_i^2\icu^2) }}}$, with probability at least $1-\delta/d$ over $\hat{A}_i,$ we have \begin{equation} \|U (\hat{A}_i - A_i) x\| \leq \frac{{\epsilon}'\mu_i\icu}{6cd}\|A\|_F\|U\|\|x\|\label{eq:noise_layer} \end{equation} for any $(U,x)\in \{(J^{i,j}_{x^i},\phi({\hat{x}}^{i-1}_{i-1}))|x\in S,i\leq j\leq d\}$. By taking a union bound over $i$, we know inequality~(\ref{eq:noise_layer}) holds with probability at least $1-\delta$ for every $i.$ Recall that the interlayer smoothness holds with probability at least $1/2.$ Taking another union, we know with probability at least $1/2-\delta,$ interlayer smoothness holds and inequality~(\ref{eq:noise_layer}) holds for every $2\leq i\leq d.$ Next, conditioning on the success of these two events, we will inductively prove for any $1\leq i\leq d$, for any $i\leq j\leq d,$ $$ \|\hat{x}^j_i - x^j\|\le (i/d){\epsilon}'\|x^j\|. $$ For the base case $i = 1$, since we are not dropping out any weight matrix, the inequality is trivial. For any $1\leq i-1\leq d-1,$ suppose $\|\hat{x}^j_{i-1} - x^j\|\le \frac{i-1}{d}{\epsilon}'\|x^j\|$ for any $i-1\leq j\leq d$; we prove the induction hypothesis holds for layer $i.$ For any $i\leq j\leq d$ we have \begin{equation*} \|\hat{x}^j_i - x^j\| = \|(\hat{x}^j_i - \hat{x}^j_{i-1})+(\hat{x}^j_{i-1} - x^j)\| \leq \|\hat{x}^j_i - \hat{x}^j_{i-1}\| +\|\hat{x}^j_{i-1} - x^j\|. \end{equation*} By the induction hypothesis, we know the second term can be bounded by $(i-1){\epsilon}'\|x^j\|/d$. Therefore, in order to complete the induction step, it suffices to show that the first term is bounded by ${\epsilon}'\|x^j\|/d$. For simplicity, we also denote $\hat{x}^{i-1}_{i-1}$ as $\hat{x}^{i-1}$. Let $\Delta_i = \hat{A}_i - A_i$. We can decompose the error into two terms: \begin{align} \nonumber \|\hat{x}^j_i - \hat{x}^j_{i-1}\| & = \|M^{i,j}(\hat{A}_i \phi(\hat{x}^{i-1})) - M^{i,j}(A_i \phi(\hat{x}^{i-1}))\|\\ \nonumber & = \|M^{i,j}(\hat{A}_i \phi(\hat{x}^{i-1})) - M^{i,j}(A_i \phi(\hat{x}^{i-1})) + J^{i,j}_{x^i}(\Delta_i \phi(\hat{x}^{i-1})) - J^{i,j}_{x^i}(\Delta_i \phi(\hat{x}^{i-1}))\| \\ & \leq \|J^{i,j}_{x^i}(\Delta_i \phi(\hat{x}^{i-1}))\| + \|M^{i,j}(\hat{A}_i \phi(\hat{x}^{i-1})) - M^{i,j}(A_i \phi(\hat{x}^{i-1})) - J^{i,j}_{x^i}(\Delta_i \phi(\hat{x}^{i-1}))\| \label{e:induct-error} \end{align} The first term of~\eqref{e:induct-error} can be bounded as follows: \begin{align} \nonumber & \|J^{i,j}_{x^i}\Delta_i \phi(\hat{x}^{i-1})\|\\ \nonumber & \le ({\epsilon}'\mu_i\icu/6cd)\|J^{i,j}_{x^i}\|\|A_i\|_F\|\phi(\hat{x}^{i-1})\|&& \mbox{Lemma~\ref{lem:dropout_layer}}\\ \nonumber & \le ({\epsilon}'\mu_i\icu/6cd)\|J^{i,j}_{x^i}\|\|A_i\|_F\|\hat{x}^{i-1}\|&& \mbox{$\phi$ (ReLU) is 1-Lipschitz}\\ \nonumber &\le ({\epsilon}'\mu_i\icu/3cd)\|J^{i,j}_{x^i}\|\|A_i\|_F\|x^{i-1}\|&& \mbox{Induction hypothesis,}\\ \nonumber &&&\ve{\hat{x}^{i-1}-x^{i-1}}\le \fc{(i-1)\epsilon' \ve{x^{i-1}}}d<\ve{x^{i-1}} \\ \nonumber &\le ({\epsilon}'\mu_i\icu/3d)\|J^{i,j}_{x^i}\|\|A_i\|_F \|\phi(x^{i-1})\|&& \mbox{Activation Contraction} \\ \nonumber &\le ({\epsilon}'\icu/3d)\|J^{i,j}_{x^i}\|\|A_i \phi(x^{i-1})\|&& \mbox{Layer Cushion} \\ \nonumber & = ({\epsilon}'\icu/3d)\|J^{i,j}_{x^i}\|\|x^i\|&& x^i = A_i\phi(x^{i-1})\\ \label{e:induct-error1} & \le ({\epsilon}'/3d) \|x^j\|&& \mbox{Interlayer Cushion} \end{align} The second term of~\eqref{e:induct-error} can be bounded as: \begin{align} \nonumber & \|M^{i,j}(\hat{A}_i \phi(\hat{x}^{i-1})) - M^{i,j}(A_i \phi(\hat{x}^{i-1})) - J^{i,j}_{x^i}(\Delta_i\phi( \hat{x}^{i-1}))\| \\ \nonumber & = \|(M^{i,j}-J^{i,j}_{x^i})(\hat{A}_i \phi(\hat{x}^{i-1})) - (M^{i,j}-J^{i,j}_{x^i})(A_i \phi(\hat{x}^{i-1}))\| \\ \label{e:induct-error2} & \leq \|(M^{i,j}-J^{i,j}_{x^i})(\hat{A}_i \phi(\hat{x}^{i-1}))\| + \|(M^{i,j}-J^{i,j}_{x^i})(A_i \phi(\hat{x}^{i-1}))\|. \end{align} Both terms of~\eqref{e:induct-error2} can be bounded using the interlayer smoothness condition. For the second term of~\eqref{e:induct-error2}, notice that $A_i\phi(\hat{x}^{i-1}) = \hat{x}^i_{i-1}$. Thus by the induction hypothesis, we know \begin{align}\|A_i\phi(\hat{x}^{i-1}) - x^i\| = \|\hat{x}^i_{i-1} - x^i\| \le (i-1){\epsilon}'\|x^i\|/d \le {\epsilon}'\|x^i\|. \label{e:induct-xii1} \end{align} Now, by interlayer smoothness, \begin{align} \nonumber \n{(M^{i,j}-J^{i,j}_{x^i})(A_i \phi(\hat{x}^{i-1}))} &= \n{(M^{i,j}-J^{i,j}_{x^i})(x^i+(A_i\phi (\hat{x}^{i-1})-x^i))}\\ \nonumber &\le \fc{\n{A_i\phi (\hat{x}^{i-1})-x^i}\n{x^j}}{\rho \n{x^i}}\\ \label{e:induct-error22} &\stackrel{(*)}\le \fc{\epsilon'\n{x^i}\n{x^j}}{3d\n{x^i}} =\fc{{\epsilon}'\n{x^j}}{3d} \end{align} where in (*) we use~\eqref{e:induct-xii1} and the assumption $\rho\ge 3d.$ For the first term of~\eqref{e:induct-error2}, we know $\hat{A}_i\phi(\hat{x}^{i-1}) = \hat{x}^i_{i-1} + \Delta_i\phi(\hat{x}^{i-1})$. Therefore by the induction hypothesis and~\eqref{e:induct-error1} for $i=j$, \begin{align*}\|\hat{A}_i\phi(\hat{x}^{i-1}) - x^i\| \le \|\hat{x}^i_{i-1} - x^i\| + \|\Delta_i\phi(\hat{x}^{i-1})\| \le (i-1){\epsilon}'\n{x^i}/d+{\epsilon}'\n{x^i}/3d \le {\epsilon}'\n{x^i}, \end{align*} so again we have \begin{align}\label{e:induct-error21} \|(M^{i,j}-J^{i,j}_{x^i})(\hat{A}_i \phi(\hat{x}^{i-1}))\| \le ({\epsilon}'/3d)\|x^j\|. \end{align} Together,~\eqref{e:induct-error21} and~\eqref{e:induct-error22} show that~\eqref{e:induct-error2} is $\le \fc{2{\epsilon}'}{3d}\n{x^j}$. Together with~\eqref{e:induct-error1} we obtain from~\ref{e:induct-error} that $\|\hat{x}^j_i - \hat{x}^j_{i-1}\|\le \fc{{\epsilon}'}{d} \n{x^j}$, and hence that $\n{\hat x_i^j - x^j}\le \fc{i{\epsilon}' \ve{x^j}}{d}$, completing the induction step. Conditioning on the success of interlayer smoothness and inequality~(\ref{eq:noise_layer}), we've shown, $$ \|\hat{x}^j_i - x^j\|\le (i/d){\epsilon}'\|x^j\|, $$ for any $i\leq j\leq d$. Recall that with probability at least $1/2-\delta$, interlayer smoothness holds and inequality~(\ref{eq:noise_layer}) holds for every $2\leq i\leq d.$ Thus, let $\epsilon'=O\pa{\sqrt{\frac{p c^2d^2\log(md h_d/\delta)}{h_{\min}\min\limits_{2\leq i\leq d}\mu_i^2\icu^2 }}}$, we know with probability at least $1/2-\delta,$ $$\|f_\theta(x) - f_{\theta_1}(x)\| =\|x^d - \hat x^d_d\| \le {\epsilon}'\|f_{\theta}(x)\|.$$ \paragraph{Bounding $\|f_\theta(x) - f_{\theta_t}(x)\|$ for any fixed $t$:} The proof for a fixed network on the path is almost the same as the proof for the end point. Instead of considering $\hat{x}_i^j$, now we consider $\hat{x}^j_i(t)$, which is the vector before activation at layer $j$ if the weights $A_2,\dots,A_i$ are replaced by $A_2+t(\hat{A}_2-A_2),\dots,A_i+t(\hat{A}_i-A_i)$. We can still use Lemma~\ref{lem:dropout_layer} to bound the noise produced by replacing the weight matrix at a single layer because $$\n{U(A_i+t(\hat{A}_i-A_i)-A_i)x}=t\n{U(\hat{A}_i-A_i)x}\leq \n{U(\hat{A}_i-A_i)x}.$$ Thus, we can still use the above induction proof to show that for any fixed $0\leq t\leq 1,$ let $\epsilon'=O\pa{\sqrt{\frac{p c^2d^2\log(md h_d/\delta)}{h_{\min}\min\limits_{2\leq i\leq d}\mu_i^2\icu^2 }}}$, with probability at least $1/2-\delta,$ $$\|f_\theta(x) - f_{\theta_t}(x)\| \le {\epsilon}'\|f_{\theta}(x)\|.$$ \paragraph{Bounding $\|f_\theta(x) - f_{\theta_t}(x)\|$ for every $t$:} Finally, we show that $\|f_\theta(x) - f_{\theta_t}(x)\|$ is bounded for every point on the path via an ${\epsilon}'$-net argument. Similar to previous steps, letting $\epsilon'=O\pa{\sqrt{\frac{p c^2d^2\max_{x\in S}(\ns{f_{\theta}(x)})\log(md h_d/\delta)}{h_{\min}\min\limits_{2\leq i\leq d}(\mu_i^2\icu^2)}}}$, we know that with probability at least $1/2-\delta,$ $$\|f_\theta(x) - f_{\theta_1}(x)\| \le \epsilon'/2.$$ Next, we show that on the path, the network output is smooth in terms of the parameters. According to Algorithm~\ref{alg:dropout}, we know for any $2\leq i\leq d$, we have $\n{\hat{A}_i}\leq 4\n{A_i}$, so $\n{\hat A_i-A_i}\le 5\ve{A_i}$. For any $2\le i\le d$, let $A_{i,t}=A_i + t(\hat A_i - A_i)$. Note $\n{A_{i,t}}\leq (1-t)\n{\hat{A}_i}+t\n{A_i} \le 4\n{A_i}$. For any $t,t'$ and any $2\leq i\leq d$, let $\theta_{t,t'}^i$ be $\theta_{t}$ with the weight matrix at every layer $2\leq j\leq i$ replaced by $(A^j+t'(\hat{A}^j-A^j))$. For convenience, we also denote $\theta_t$ as $\theta_{t,t'}^1.$ Given $\tau<1/2,$ for any $\tau \leq t\leq 1-\tau$ and for any $-\tau \leq \kappa \leq \tau,$ we can bound $\n{f_{\theta_{t+\kappa}}(x)-f_{\theta_t}(x)}$ as follows: \begin{align*} \n{f_{\theta_{t+\kappa}}(x)-f_{\theta_t}(x)} &\leq \sum_{2\leq i\leq d}\n{f_{\theta^{i}_{t,t+\kappa}}(x)-f_{\theta_{t,t+\kappa}^{i-1}}(x)} \end{align*} The output of layer $i-1$ is the same for the two networks, of norm $\le \n{x}\prodo j{i-1} \n{A_{j,t+\kappa}}$. Hence the output of layer $i$ differs by at most $\kappa \n{x}\n{\hat A_i -A_i}\prodo j{i-1}\n{A_{j,t+\kappa}}$ and the output differs by $\kappa \n{x}\n{\hat A_i-A_i}\prodo j{i-1} \n{A_{j,t+\kappa}}\prod_{j=i+1}^d \n{A_{j,t}} \le 5^d\kappa\n{x} \prodo jd \n{A_j}$. Hence \begin{align*} \n{f_{\theta_{t+\alpha}}(x)-f_{\theta_t}(x)} &\leq \sum_{2\leq i\leq d}5^d\n{x}\kappa\prod_{1\leq j\leq d}\n{A_j}\\ &\leq 5^dd\kappa\n{x}\prod_{1\leq j\leq d}\n{A_i}. \end{align*} Thus, given $\tau\leq \frac{\epsilon'}{2\cdot 5^dd\max\limits_{x\in S}\n{x}\prod_{1\leq j\leq d}\n{A_j}},$ we know for any $\tau \leq t\leq 1-\tau$ and for any $-\tau \leq \alpha \leq \tau,$ \begin{equation} \n{f_{\theta_{t+\alpha}}(x)-f_{\theta}(x)}\leq \epsilon'/2.\label{eq:epsnet} \end{equation} There exists a set $Q=\{\theta_t\}$ with size $O(1/\tau)$ such that for any network on the path, the distance to the closest network in $Q$ is no more than $\tau.$ If we can prove for any $\theta_t\in Q$, $\|f_\theta(x) - f_{\theta_t}(x)\| \le \epsilon'/2$, we immediately know for any network $\theta_{t'}$ on the path $\|f_\theta(x) - f_{\theta_{t'}}(x)\| \le \epsilon'$ by inequality~(\ref{eq:epsnet}). By a union bound over $Q$, letting $\epsilon'=O\pa{\sqrt{\frac{p c^2d^2\max_{x\in S}(\ns{f_{\theta}(x)})\log\pf{md h_d}{\delta\tau}}{h_{\min}\min\limits_{2\leq i\leq d}(\mu_i^2\icu^2) }}}$, we know with probability at least $1/2-\delta,$ $$\|f_\theta(x) - f_{\theta_t}(x)\| \le \epsilon'/2,$$ for any $\theta_t\in Q$. Setting $\delta=1/4$, we know there exists $$\epsilon'=O\pa{\sqrt{\frac{pc^2d^3\max_{x\in S}(\ns{f_{\theta}(x)}) \log \pa{\frac{md h_d\max\limits_{x\in S}\n{x}\prod_{1\leq j\leq d}\n{A_j}}{ \epsilon'}}}{h_{\min}\min\limits_{2\leq i\leq d}(\mu_i^2\icu^2) }}}$$ such that with probability at least $1/4$, $$\|f_\theta(x) - f_{\theta_t}(x)\| \le \epsilon'$$ for any $x\in S$ and any $0\leq t\leq 1.$ Since the loss function is $\beta$-Lipschitz, we further know that for any $0\leq t\leq 1$: $$ L(f_{\theta_t}) \le L(f_{\theta})+\beta{\epsilon}'= L(f_{\theta})+ \widetilde{O}(\sqrt{p}\epsilon). $$ \end{proofof} Now, we are ready to prove the main theorem. \noisestableconnect* \begin{proofof}{Theorem~\ref{thm:noise_stable_connect}} Setting dropout probability $p= 3/4$, by Lemma~\ref{lem:dropout_layer} and Lemma~\ref{lem:dropout_crosslayer}, if $h_{\min}=\widetilde{\Omega}\pa{1}$, we know there exist $\theta^A_1$ and $\theta^B_1$ such that \begin{enumerate} \item in both networks, each weight matrix from layer $2$ to layer $d$ has at least half of columns as zero vectors; \item $L(f_{\theta^A_t})\leq L(f_{\theta^A})+\widetilde{O}(\epsilon)$ and $L(f_{\theta^B_t})\leq L(f_{\theta^B})+\widetilde{O}(\epsilon)$, for any $0\leq t\leq 1$, where $\theta^A_t=\theta^A+t(\theta^A_1-\theta^A)$ and $\theta^B_t=\theta^B+t(\theta^B_1-\theta^B)$. \end{enumerate} Since the dropout fraction in both $\theta^A_1$ and $\theta^B_1$ is at least half, we can connect $\theta^A_1$ and $\theta^B_1$ as we did in Lemma~\ref{lem:drop-connect}, while ensuring the loss doesn't exceed $\max \{L(f_{\theta^A}),L(f_{\theta^B})\}+\widetilde{O}(\epsilon)$. Connecting $\theta^A$ to $\theta^A_1$ and connecting $\theta_B$ to $\theta^B_1$ each take one line segment. By the construction in Lemma~\ref{lem:drop-connect}, connecting two dropped-out networks $\theta^A_1$ and $\theta^B_1$ takes $8$ line segments. Thus, overall the path between $\theta^A$ and $\theta^B$ contains $10$ line segments. \end{proofof} Next, we show that if there exists a ``narrow'' neural network achiving small loss, we can get a lower energy barrier using a smaller dropout probability. \teacherstudent* \begin{proofof}{Theorem~\ref{cor:teacher_student}} Since $h_{\min}\cdot \max_{1\leq i\leq d-1}(h_i^*/h_i)\geq h_{\min}^* =\widetilde{\Omega}(1),$ we have $h_{min}=\widetilde{\Omega}\pf{1}{\max_{1\leq i\leq d-1}(h_i^*/h_i)}.$ By Lemma~\ref{lem:dropout_layer} and Lemma~\ref{lem:dropout_crosslayer}, there exist $\theta^A_1$ and $\theta^B_1$ such that \begin{enumerate} \item in both networks, each weight matrix from layer $2$ to layer $d$ has at least $h_i^*$ columns set to zero; \item $L(f_{\theta^A_t})\leq L(f_{\theta^A})+\widetilde{O}(\sqrt{p}\epsilon)$ and $L(f_{\theta^B_t})\leq L(f_{\theta^B})+\widetilde{O}(\sqrt{p}\epsilon)$, for any $0\leq t\leq 1$, where $\theta^A_t=\theta^A+t(\theta^A_1-\theta^A)$ and $\theta^B_t=\theta^B+t(\theta^B_1-\theta^B)$. \end{enumerate} From the fact that at least $h_i^*$ units in layer $i$ of both $\theta^A_1$ and $\theta^B_1$ have been set to zero for $1 \leq i < d$---meaning that the corresponding rows of $A_i$ and columns of $A_{i+1}$ are zero---it follows from Lemma~\ref{lem:drop-connect} that we can connect $\theta^A_1$ to an arbitrary permutation of $\theta^*$ using $8$ segments while keeping the loss on the path no more than $\max\{L(f_{\theta^A_1}),L(f_{\theta^*})\}.$ By choosing this permutation so that the non-zero units of $\theta^*$ do not intersect with those of $\theta^B_1$, we can then connect $\theta^*$ to $\theta^B_1$ using just $3$ segments as done in the first step of our path construction in Lemma~\ref{lem:drop-connect} seeing as there is no need to permute $\theta^*$ a second time. Combining these paths together with the paths that interpolate between the original parameters $\theta^A$ and $\theta^B$ and their dropout versions $\theta^A_1$ and $\theta^B_1$, we obtain a path in parameter space $\pi : [0,1] \to \Theta$ between $\theta^A$ and $\theta^B$ with $13$ line segments such that $L(f_{\pi(t)}) \leq \max \{L(f_{\theta^A})+\widetilde{O}(\sqrt{p}\epsilon),L(f_{\theta^B})+\widetilde{O}(\sqrt{p}\epsilon), L(f_{\theta^*})\}$ for $0 \leq t \leq 1$. \end{proofof} \section{Connectivity via noise stability}\label{sec:noise_stable} In this section, we relate mode connectivity to another notion of robustness for neural networks---noise stability. It has been observed \citep{morcos2018importance} that neural networks often perform as well even if a small amount of noise is injected into the hidden layers. This was formalized in \citep{arora2018stronger}, where the authors showed that noise-stable networks tend to generalize well. In this section we use a very similar notion of noise stability, and show that all noise-stable solutions can be connected as long as the network is sufficiently overparametrized. We begin in Section~\ref{sec:noise_stable_model} by restating the definitions of noise stability in \citep{arora2018stronger} and also highlighting the key differences. In Section~\ref{sec:experiments} we verify these assumptions in practice. In Section~\ref{sec:noise_stability_drop_out}, we first prove that noise stability implies dropout stability (so Theorem~\ref{thm:connect_via_dropout} applies) and then show that it is in fact possible to connect noise stable neural networks via even simpler paths. \subsection{Noise stability}\label{sec:noise_stable_model} First we will introduce some additional notations and assumptions. In this section, we consider a finite and fixed training set $S$. For a network parameter $\theta$, the empirical loss function is $L(\theta) = \frac{1}{|S|}\sum_{(x,y)\in S} l(y,f(x))$. Here the loss function $l(y,\hat{y})$ is assumed to be $\beta$-Lipschitz in $\hat{y}$: for any $\hat{y},\hat{y}'\in {\mathbb{R}}^{h_d}$ and any $y\in{\mathbb{R}}^{h_d},$ we have $|l(y,\hat{y})-l(y,\hat{y}')|\leq \beta\n{\hat{y}-\hat{y}'}.$ The standard cross entropy loss over the softmax function is $\sqrt{2}$-Lipschitz. For any two layers $i\leq j$, let $M^{i,j}$ be the operator for composition of these layers, such that $x^j = M^{i,j}(x^i)$. Let $J^{i,j}_{x^i}$ be the Jacobian of operator $M^{i,j}$ at input $x^i$. Since the activation functions are ReLU's, we know $M^{i,j}(x^i) =J^{i,j}_{x^i} x^i$. \citet{arora2018stronger} used several quantities to define the noise stability. We list the definitions of these quantities below. \begin{definition}[Noise Stability Quantities] \label{def:allnoise}\label{def:layercushion} Given sample set $S$, the \vocab{layer cushion} of layer $i$ is defined as $\mu_i:=\min_{x\in S}\frac{\|A_i \phi(x^{i-1})\|}{\|A_i\|_F\|\phi(x^{i-1})\|}.$ \label{def:interlayercushion} For any two layers $i\leq j$, the \vocab{interlayer cushion} $\mu_{i,j}$ is defined as $\mu_{i,j}=\min_{x\in S} \frac{\|J^{i,j}_{x^i}x^i\|}{\|J^{i,j}_{x^i}\|\|x^i\| }. $ Furthermore, for any layer $i$ the \vocab{minimal interlayer cushion} is defined as\footnote{Note that $J_{x^i}^{i,i} = I_{h_i}$ and $\mu_{i,i} = 1$.} $\icu = \min_{i\leq j\leq d} \mu_{i,j}.$ \label{def:activationcontraction} The \vocab{activation contraction} $c$ is defined as $c= \max_{x\in S,\ 1\leq i\leq d-1} \frac{\|x^i\|}{\|\phi(x^i)\|}.$ \end{definition} Intuitively, these quantities measures the stability of the network for both a single layer and multiple layers. Note that this definition of the {\em interlayer cushion} is slightly different from the original definition in~\citep{arora2018stronger}. Specifically, in the denominator of the definition, we replace the Frobenius norm of $J^{i,j}_{x^i}$ by its spectral norm. In the original definition, the interlayer cushion is at most $1/\sqrt{h_i},$ simply because $J_{x^i}^{i,i} = I_{h_i}$ and $\mu_{i,i} = 1/\sqrt{h_i}.$ With this new definition, the interlayer cushion need not depend on the layer width $h_i$. The final quantity of interest is interlayer smoothness, which measures how close the network is to its linear approximation for specific type of noise. In this work we focus on the noise generated by the dropout procedure (Algorithm~\ref{alg:dropout}). Let $\theta = \{A_1, A_2, ...,A_d\}$ be weights of the original network, and let $\theta^i = \{A_1, \hat{A}_2,\ldots,\hat{A}_i,A_{i+1},\ldots,A_d\}$ be the result of applying Algorithm~\ref{alg:dropout} to weight matrices from layer $2$ to layer $i$.\footnote{Note that $A_1$ is excluded because dropping out columns in $\hat A_2$ already drops out the neurons in layer 1; dropping out columns in $A_1$ would drop out input coordinates, which is not necessary.} For any input $x$, let $\hat{x}^i_i(t)$ and $\hat{x}^i_{i-1}(t)$ be the vector before activation at layer $i$ using parameters $\theta t + \theta^i (1-t)$ and $\theta t + \theta^{i-1} (1-t)$ respectively. \begin{definition}[Interlayer Smoothness]\label{def:interlayersmoothness} Given the scenario above, define \vocab{interlayer smoothness} $\rho$ to be the smallest number such that with probability at least $1/2$ over the randomness in Algorithm~\ref{alg:dropout} for any two layers $i,j$ satisfying for every $2\leq i\leq j\leq d$, $x\in S$, and $0\le t\le 1$ \begin{align*} &\|M^{i,j}(\hat{x}^i_i(t))-J_{x^i}^{i,j}(\hat{x}^i_i(t))\| \leq \frac{\|\hat{x}^i_i(t)-x^i\|\|x^{j}\|}{\rho \|x^{i}\|},\\ &\|M^{i,j}(\hat{x}^i_{i-1}(t))-J_{x^i}^{i,j}(\hat{x}^i_{i-1}(t))\| \leq \frac{\|\hat{x}^i_{i-1}(t)-x^i\|\|x^{j}\|}{\rho \|x^{i}\|}. \end{align*} \end{definition} If the network is smooth (has Lipschitz gradient), then interlayer smoothness holds as long as $\|\hat{x}^i_i(t)-x^i\|,\|\hat{x}^i_{i-1}(t)-x^i\|$ is small. The assumption here asks the network to behave smoothly in the random directions generated by randomly dropping out columns of the matrices. Similar to \citep{arora2018stronger}, we have defined multiple quantities measuring the noise stability of a network, these quantities are indeed small constants as we verify experimentally in Section~\ref{sec:experiments}. Finally we combine all these quantities to define a single number that measures the noise stability of a network. \begin{definition}[Noise Stability] For a network $\theta$ with layer cushion $\mu_i$, minimal interlayer cushion $\icu$, activation contraction $c$ and interlayer smoothness $\rho$, if the minimum width layer $h_{min}$ is at least $\widetilde{\Omega}(1)$ wide, $\rho \ge 3d$ and $\n{\phi(\hat{x}^i_i(t))}_\infty=O(1/\sqrt{h_i})\n{\phi(\hat{x}^i_i(t))}$ for $1\leq i\leq d-1, 0\leq t\leq 1$, we say the network $\theta$ is $\epsilon$-noise stable for $$\epsilon= \frac{\beta cd^{3/2}\max_{x\in S}(\n{f_{\theta}(x)})}{h_{\min}^{1/2}\min_{2\leq i\leq d}(\mu_i\icu)}.$$ \end{definition} The network is more robust if $\epsilon$ is small. Note that the quantity $\epsilon$ is small as long as the hidden layer width $h_{\min}$ is large compared to the noise stable parameters. Intuitively, we can think of this $\epsilon$ value as a single parameter that measures the noise stability of the network. \subsection{Noise stability implies dropout stability}\label{sec:noise_stability_drop_out} We now show that noise stable local minimizers must also be dropout stable, from which it follows that noise stable local minimizers are connected. We first define the dropout procedure we will be using in Algorithm~\ref{alg:dropout}. \begin{algorithm} \caption{Dropout ($A_i, p$)} \begin{algorithmic}[1] \REQUIRE Layer matrix $A_i\in {\mathbb{R}}^{h_i\times h_{i-1}}$, dropout probability $0<p<1$. \ENSURE Returns $\hat{A}_i\in {\mathbb{R}}^{h_i\times h_{i-1}}$. \STATE For each $j\in[h_{i-1}],$ let $\delta_j$ be an i.i.d. Bernoulli random variable which takes the value $0$ with probability $p$ and takes the value $\frac{1}{1-p}$ with probability $(1-p)$. \STATE For each $j\in[h_{i-1}],$ let $[\hat{A}_i]_j$ be $\delta_j [A_i]_j$, where $[\hat{A}_i]_j$ and $[A_i]_j$ are the $j$-th column of $\hat{A}_i$ and $A_i$ respectively. \end{algorithmic} \label{alg:dropout} \end{algorithm} The main theorem that we prove in this section is: \begin{restatable}{theorem}{noisestableconnect} \label{thm:noise_stable_connect} Let $\theta^A$ and $\theta^B$ be two fully connected networks that are both $\epsilon$-noise stable, there exists a path with $10$ line segments in parameter space $\pi : [0,1] \to \Theta$ between $\theta^A$ and $\theta^B$ such that\footnote{Here $\widetilde{O}(\cdot )$ hides log factors on relevant factors including $|S|, d, \n{x}, 1/\epsilon$ and $h_i \n{A_i}$ for layers $i\in[d]$.} $L(f_{\pi(t)}) \leq \max \{L(f_{\theta^A}),L(f_{\theta^B})\} + \widetilde{O}(\epsilon)$ for $0 \leq t \leq 1$. \end{restatable} To prove the theorem, we will first show that the networks $\theta^A$ and $\theta^B$ are $\widetilde{O}(\epsilon)$-dropout stable. This is captured in the following main lemma: \begin{restatable}{lemma}{dropoutcrosslayer} \label{lem:dropout_crosslayer} Let $\theta$ be an $\epsilon$-noise stable network, and let $\theta_1$ be the network with weight matrices from layer $2$ to layer $d$ dropped out by Algorithm~\ref{alg:dropout} with dropout probability $\widetilde{\Omega}(1/h_{min})<p\le \fc 34$. For any $2\leq i\leq d$, assume $\n{[A_i]_j}=O(\sqrt{p})\n{A_i}_F$ for $1\leq j\leq h_{i-1}.$ For any $0\leq t\leq 1$, define the network on the segment from $\theta$ to $\theta_1$ as $\theta_t:=\theta+t(\theta_1-\theta)$. Then, with probability at least $1/4$ over the weights generated by Algorithm~\ref{alg:dropout}, $L(f_{\theta_t}) \le L(f_{\theta})+\widetilde{O}(\sqrt{p}\epsilon)$, for any $0\leq t\leq 1$. \end{restatable} The main difference between Lemma~\ref{lem:dropout_crosslayer} and Lemma~\ref{lem:original_sparse} is that we can now directly interpolate between the original network and its dropout version, which reduces the number of segments required. This is mainly because in the noise stable setting, we can prove that after dropping out the neurons, not only does the output remains stable, {\em every} intermediate layer also remains stable. From Lemma~\ref{lem:dropout_crosslayer}, the proof of Theorem~\ref{thm:noise_stable_connect} is very similar to the proof of Theorem~\ref{thm:connect_via_dropout}. The detailed proof is given in Section~\ref{sec:noise_stability_proof}. The additional power of Lemma~\ref{lem:dropout_crosslayer} also allows us to consider a smaller dropout probability. The theorem below allows us to trade dropout fraction with the energy barrier $\epsilon$ that we can prove---if the network is highly overparametrized, one can choose a small dropout probability $p$ which allow the energy barrier $\epsilon$ to be smaller. \begin{restatable}{theorem}{teacherstudent}\label{cor:teacher_student} Suppose there exists a network $\theta^*$ with layer width $h_{i}^*$ for each layer $i$ that achieves loss $L(f_{\theta^*})$, and minimum hidden layer width $h^*_{min} = \widetilde{\Omega}(1)$. Let $\theta^A$ and $\theta^B$ be two $\epsilon$-noise stable networks. For any dropout probability $1.5\max_{1\leq i\leq d-1}(h_i^*/h_i)\leq p\leq 3/4$, if for any $2\leq i\leq d$, $1\leq j\leq h_{i-1},$ $\n{[A_i]_j}=O(\sqrt{p})\n{A_i}_F$ then there exists a path with $13$ line segments in parameter space $\pi : [0,1] \to \Theta$ between $\theta^A$ and $\theta^B$ such that $L(f_{\pi(t)}) \leq \max \{L(f_{\theta^A})+\widetilde{O}(\sqrt{p}\epsilon),L(f_{\theta^B})+\widetilde{O}(\sqrt{p}\epsilon), L(f_{\theta^*})\}$ for $0 \leq t \leq 1$. \end{restatable} Intuitively, we prove this theorem by connecting $\theta^A$ and $\theta^B$ via the neural network $\theta^*$ with narrow hidden layers. The detailed proof is given in Section~\ref{sec:noise_stability_proof}. \section{Preliminaries} \paragraph{Notations} For a vector $v$, we use $\|v\|$ to denote its $\ell_2$ norm. For a matrix $A$, we use $\|A\|$ to denote its operator norm, and $\|A\|_F$ to denote its Frobenius norm. We use $[n]$ to denote the set $\{1,2,\ldots,n\}$. We use $I_n$ to denote the identity matrix in ${\mathbb{R}}^{n\times n}$. We use $O(\cdot), \Omega(\cdot)$ to hide constants and use $\widetilde{O}(\cdot),\widetilde{\Omega}(\cdot)$ to hide poly-logarithmic factors. \paragraph{Neural network} In most of the paper, we consider fully connected neural networks with ReLU activations. Note however that our results can also be extended to convolutional neural networks (in particular, see Remark~\ref{rmk:channelwise} and the experiments in Section~\ref{sec:experiments}). Suppose the network has $d$ layers. Let the vector before activation at layer $i$ be $x^i$, $i\in[d],$ where $x^d$ is just the output. For convenience, we also denote the input $x$ as $x^0$. Let $A_i$ be the weight matrix at $i$-th layer, so that we have $x^{i} = A_{i} \phi(x^{i-1})$ for $2\leq i\leq d$ and $x^1=A_1x^0$. For any layer $i,\ 1\leq i\leq d,$ let the width of the layer be $h_i$. We use $[A_i]_j$ to denote the $j$-th column of $A_i.$ Let the maximum width of the hidden layers be $h_{\max}:=\max\{h_1, h_2, \ldots, h_{d-1}\}$ and the minimum width of the hidden layers be $h_{\min}:=\min\{h_1, h_2, \ldots, h_{d-1}\}$. We use $\Theta$ to denote the set of parameters of neural network, and in our specific model, $\Theta = {\mathbb{R}}^{h_1\times h_0} \times{\mathbb{R}}^{h_2\times h_1}\times \cdots \times {\mathbb{R}}^{h_d\times h_{d-1}}$ which consists of all the weight matrices $\{A_i\}$'s. Throughout the paper, we use $f_\theta$, $\theta\in \Theta$ to denote the function that is computed by the neural network. For a data set $(x,y)\sim \mathcal{D}$, the loss is defined as $L_\mathcal{D}(f_\theta): = {\mathbb{E}}_{(x,y)\sim \mathcal{D}}[l(y,f_\theta(x))]$ where $l$ is a loss function. The loss function $l(y, \hat{y})$ is convex in the second parameter. We omit the distribution $\mathcal{D}$ when it is clear from the context. \paragraph{Mode connectivity and spurious valleys} Fixing a neural network architecture, a data set $\mathcal{D}$ and a loss function, we say two sets of parameters/solutions $\theta^A$ and $\theta^B$ are \vocab{$\epsilon$-connected} if there is a path $\pi(t): {\mathbb{R}} \to \Theta$ that is continuous with respect to $t$ and satisfies: 1. $\pi(0) = \theta^A$; 2. $\pi(1) = \theta^B$ and 3. for any $t\in [0,1]$, $L(f_{\pi(t)}) \le \max\{L(f_{\theta^A}), L(f_{\theta^B})\}+\epsilon$. If $\epsilon = 0$, we omit $\epsilon$ and just say they are connected. If all the local minimizers are connected, then we say that the loss function has the \vocab{mode connectivity property}. However, as we later show in Section~\ref{sec:example:main}, this property is very strong and is not true even for overparametrized two-layer nets. Therefore we restrict our attention to classes of low-cost solutions that can be found by the gradient-based algorithms (in particular in Section~\ref{sec:dropout} we focus on solutions that are dropout stable, and in Section~\ref{sec:noise_stable} we focus on solutions that are noise stable). We say the loss function has $\epsilon$-\vocab{mode connectivity property} with respect to a class of low-cost solutions $\mathcal{C}$, if any two minimizers in $\mathcal{C}$ are $\epsilon$-connected. Mode connectivity is closely related to the notion of spurious valleys and connected sublevel sets \citep{venturi2018spurious}. If a loss function has all its sublevel sets ($\{\theta:L(f_\theta)\le \lambda\}$) connected, then it has the mode connectivity property. When the network only has the mode connectivity property with respect to a class of solutions $\mathcal{C}$, as long as the class $\mathcal{C}$ contains a global minimizer, we know there are no spurious valleys in $\mathcal{C}$. However, we emphasize that neither mode connectivity or lack of spurious valleys implies any local search algorithm can efficiently find the global minimizer. These notions only suggest that it is unlikely for local search algorithms to get completely stuck. \section{Tools} We use matrix concentration bounds to bound the noise produced by dropping out one single layer (Lemma~\ref{lem:dropout_layer}). \begin{lemma}[Matrix Bernstein; Theorem 1.6 in \citep{tropp2012user}]\label{lm:bernstein_original} Consider a finite sequence $\{Z_k\}$ of independent, random matrices with dimension $d_1\times d_2$. Assume that each random matrix satisfies $${\mathbb{E}}[Z_k]=0\ and \ \n{Z_k}\leq R \ almost \ surely. $$ Define $$\sigma^2:= \max\Big\{\big\lVert\sum_k {\mathbb{E}}[Z_k Z_k^*]\big\rVert, \big\lVert \sum_k {\mathbb{E}}[Z_k^* Z_k]\big\rVert \Big\}.$$ Then, for all $t\geq 0$, $$\Pr\Big\{\big\lVert\sum_k Z_k\big\rVert\geq t \Big\}\leq (d_1+d_2) \exp\Big(\frac{-t^2/2}{\sigma^2+Rt/3}\Big).$$ \end{lemma} As a corollary, we have: \begin{lemma}[Bernstein Inequality: Vector Case]\label{lm:vectorBernstein} Consider a finite sequence $\{v_k\}$ of independent, random vectors with dimension $d$. Assume that each random vector satisfies $$\n{v_k-{\mathbb{E}}[v_k]}\leq R\ almost\ surely.$$ Define $$\sigma^2 := \sum_{k}{\mathbb{E}}\big[\ns{v_k-{\mathbb{E}}[v_k]}\big].$$ Then, for all $t\geq 0$, $$\Pr\Big\{\n{\sum_{k}(v_k-{\mathbb{E}}[v_k])}\geq t\Big\}\leq (d+1)\cdot \exp\Big(\frac{-t^2/2}{\sigma^2+Rt/3}\Big).$$ \end{lemma}
{'timestamp': '2019-06-17T02:15:56', 'yymm': '1906', 'arxiv_id': '1906.06247', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06247'}
arxiv
\section{Introduction} \label{sec:intro} Distributed optimization~\cite{bertsekas1989parallel} aims to optimize a global objective formed by a sum of functions: \begin{align} \label{eq:goal} f(x) = \tfrac{1}{m}\sum_{i=1}^{m} f_i(x) \qquad f,f_i : \mathbb{R}^d \rightarrow \mathbb{R}, \end{align} where $m$ is the number of computational nodes and each $f_i$ is called a local loss function. Each $f_i$ may possibly be derived from the $i^\text{th}$ batch of data, and hence may differ for each node $i$. Optimization of~(\ref{eq:goal}) usually consists of two phases: local optimization like gradient descent and inter-node communication like model averaging. Conventional distributed optimization algorithms, such as the ``Parameter-Server'' model ~\cite{li2014scaling,ho2013more,li2014communication}, usually require immediate inter-node communication after performing local gradient descent to simulate centralized learning and guarantee convergence for the overall model. In practice, the rapid expanding size of machine learning models, some with tens of millions of trainable parameters, often renders the communication step an increasingly significant bottleneck. This issue is further compounded by concerns on privacy and security, bandwidth requirement, power consumption and information delay~\cite{duchi2012dual,agarwal2011distributed}, where it is favorable to reduce the communication cost and only exchange information when necessary. Among the possible solutions to alleviate the communication overhead, one practical method is using compressed models or gradients in communication. For example, studies on quantized gradients~\cite{seide20141,alistarh2017qsgd,wangni2018gradient} and sparsified models~\cite{aji2017sparse,lin2017deep,dryden2016communication,li2018optimal} allow each node to pass low bit gradients or models to the server instead of the raw data. However, extra noise is introduced in quantization or sparsification and communication is still required at every iteration. Another possible approach~\cite{smith2018cocoa,ma2017distributed} in reducing the communication cost is to update the local models by performing $T_i > 1$ iterations of local GD before sending the model to the server. Two fundamental questions in this scenario are: \begin{center} \begin{itemize} \item \textbf{Question 1}: \emph{Does the algorithm still converge with an arbitrary choice of $T_i$?} \item \textbf{Question 2}: \emph{Does more local updating $T_i$ definitely lead to less communication?} \end{itemize} \end{center} From a general distributed optimization perspective, the answers are negative. Conventional studies \cite{zhang2012communication,zhang2016parallel,zhou2017convergence,stich2018local,yu2018parallel} show that although it may not be necessary to communicate after each local GD, frequent communication after $T_i$ steps is still needed. Moreover, to ensure convergence a decaying learning rate is required or alternatively, the loss bound has a finite term that may grow with increasing $T_i$~\cite{stich2018local,yu2018parallel}. More importantly, these prior results also indicate that in general, a bigger $T_i$ leads to poorer optimization performance and may not necessarily reduce the communication cost to obtain the same overall precision. However, in this paper, we draw completely different conclusions from the previous results and show the answers can be positive in certain scenarios. We provide a series of theoretical analysis for convex cases and show that convergence holds for an arbitrary choice of $T_i$, and even for $T_i = \infty$ where each node updates its local model to optimality. Moreover, our results also provide answers for the second question by showing that more local updating can reduce the overall need for communication. Beyond convex cases, we show that similar conclusions may still hold by providing theoretical analysis on simple non-convex settings whose optimal sets are affine subspaces and also provide a series of experimental evidences for deep learning. These different conclusions rest upon the following intersection assumption we make throughout the paper: \begin{Assumption} \label{Ass:intersection} Denoting $S_i := \{ x \in \mathbb{R}^d : f_i(x) \leq f_i(y) \ \text{holds for}\ \forall y\in\mathbb{R}^d \}$ as the optimal set of $f_i$, the set $S := \cap_{i=1}^m S_i$ is non-empty. \end{Assumption} This assumption is inspired by both the new phenomenon in modern machine learning named ``over-parameterization''~\cite{zhang2016understanding,arora2018optimization} and a classical mathematical problem named ``convex feasibility problem''~\cite{von1949rings}. Modern machine learning models, especially deep learning models, often consist of huge amounts of parameters that far exceed the instance numbers~\cite{ma2017power,bassily2018exponential,oymak2018overparameterized,allen2018convergence}. This over-parameterization phenomenon leads significant communication \emph{challenges} to distributed optimization as it requires enormous bandwidth to transport local models. But in this paper, we show that this phenomenon also brings new \emph{hopes} that allow each node to \emph{reduce the communication frequency} arbitrarily by updating its local model to (sub)optimality before sending information to server. The underlying reason is that the training loss for over-parameterized models can often easily approach 0 due to the degeneracy of the over-parameterized functions~\cite{zhang2016understanding,du2018gradient,allen2018convergence}, indicating that there exists a common $x^*$ such that all local losses $f_i(x^*)$ are all 0 when data are distributed to multiple nodes and the above intersection assumption holds naturally. Our work also bridges connections of the over-parameterized machine learning models with the classical convex feasibility problem~\cite{von1949rings} in mathematics, which assumes the intersection of $m$ convex closed subsets $S_i$ of a Hilbert space is non-empty and uses sequential projections~\cite{bauschke1996projection,aharoni1989block,censor2016implicit} to find a feasible point $x^* \in \cap_{i=1}^m S_i$. This non-empty intersection assumption resembles Assumption~\ref{Ass:intersection}, but the classical approach of direct projections in convex feasible problem can often be challenging for most machine learning tasks since we cannot easily characterize local feasible sets. In this paper, we show that this projection step can be replaced by continuous local GD and convergence can still be obtained. \textit{Notation}: \ \ Throughout this paper, we denote by $\|\cdot\|$ the Euclidean norm. If the argument is a matrix, it is the induced $2$-norm. For a closed convex set $S$, we denote by $P_S(x)$ the projection of $x$ onto $S$. The shortest distance between a point $x$ and a set $S$ is denoted by $\dS{x}$. \section{Convex Cases} \label{sec:convex} To start, we first focus on the convex scenarios. Each function $f_i$ in~(\ref{eq:goal}) is assumed to be convex and $L_i$-smooth (i.e. $\nabla f_i$ is Lipschitz with constant $L_i$), and therefore the overall loss function $f$ is also convex and $L$-smooth, with $L=\tfrac{1}{m}\sum_{i=1}^{m} L_i$. We consider the classical algorithm as seen in Alg~\ref{alg}, where each node $i$ is allowed to update $T_i$ local GD steps with step size $\eta_i$ before interacting with the server. Denoting the point after the $n$-th communication as $x_n$, the following lemma establishes a useful bound on the evolution of the distance between $x_n$ and the common optimal set $S$. \begin{restatable}{Lemma}{lemmaone} \label{lm:mother_equation} Consider algorithm in Alg~\ref{alg} and assume each $f_i$ is convex and $L_i$-smooth. Then, \begin{equation*} \label{eq:mother_equation} \dS{x_{n+1}}^2 \leq \dS{x_{n}}^2 - \tfrac{1}{m}\sum_{i=1}^{m} \sum_{t=0}^{T_i - 1} \alpha_i \| \nabla f_i (x_n^{i,t}) \|^2, \end{equation*} where $\alpha_i = \eta_i (\tfrac{2}{L_i} - \eta_i)$. \end{restatable} \begin{Proof} For any point $x^* \in S$, \begin{align} \label{eq:xn+1} \begin{split} \| x_{n+1} - x^* \|^2 = \| \tfrac{1}{m} \sum_{i=1}^{m} x_n^{i,T_i} - x^* \|^2 &\leq \tfrac{1}{m} \sum_{i=1}^{m} \| x_n^{i,T_i} - x^* \|^2 \end{split} \end{align} For each node, we have \begin{align*} & \| x_n^{i,t+1} - x^* \|^2 \\ =& \| x_n^{i,t} - x^* - \eta_i \nabla f_i (x_n^{i,t}) \|^2 \\ =& \| x_n^{i,t} - x^* \|^2 - 2 \eta_i \langle x_n^{i,t} - x^*, \nabla f_i (x_n^{i,t}) \rangle +(\eta_i)^2 \| \nabla f_i (x_n^{i,t}) \|^2 \\ \leq& \| x_n^{i,t} - x^* \|^2 - \alpha_i \| \nabla f_i (x_n^{i,t}) \|^2, \end{align*} where in the last step we used the co-coercivity of convex and $L_i$-smooth functions and the fact that $x^*$ is also in each $S_i$ due to Assumption~\ref{Ass:intersection}. Summing the above from $t=0$ to $t=T_i-1$ and noticing $x_n^{i,0} = x_n$, we have \begin{align*} \| x_n^{i,T_i} - x^* \|^2 \leq \| x_n - x^* \|^2 - \alpha_i \sum_{t=0}^{T_i - 1} \| \nabla f_i (x_n^{i,t}) \|^2. \end{align*} Combining this with Eq.~\eqref{eq:xn+1}, we obtain \begin{equation*} \| x_{n+1} - x^* \|^2 \leq \| x_{n} - x^* \|^2 - \tfrac{1}{m}\sum_{i=1}^{m} \sum_{t=0}^{T_i - 1} \alpha_i \| \nabla f_i (x_n^{i,t}) \|^2. \end{equation*} Setting $x^* = P_S(x_n)$ and noticing that $\dS{x_{n+1}} \leq d(x_{n+1},x^*)$, we conclude the proof. \end{Proof} \begin{algorithm}[!t] \caption{Model Averaging for Distributed Optimization} \label{alg} \begin{algorithmic}[1] \item[\textbf{\underline{Worker $i=1,\cdots,m$:}}] \STATE{pull $x_n$ from server and initialize $x_n^{i,0} = x_n$} \FOR{$t=0,\cdots,T_i - 1$} \STATE{update $x_n^{i,t+1} = x_n^{i,t} - \eta_i \nabla f_i(x_n^{i,t}) $} \ENDFOR \STATE{push $x_n^{i,T_i}$ to server} \end{algorithmic} \begin{algorithmic}[1] \item[\textbf{\underline{Server:}}] \STATE{average model: $x_{n+1} = \frac{1}{m}\sum_{i=1}^m x_n^{i,T_i}$} \end{algorithmic} \end{algorithm} \paragraph{Remark:} For the general convex cases, Lemma~\ref{lm:mother_equation} already provides answers to these two questions raised in Sec~\ref{sec:intro}. (1) To see the gradient norm converges for arbitrary $T_i$, we first notice $\{\dS{x_n}^2\}$ is a positive non-increasing sequence for $\alpha_i>0$. Therefore, for any $\delta$, there exists a sufficiently large $n$ such that \begin{equation*} \frac{1}{m}\sum_{i=1}^{m} \sum_{t=0}^{T_i - 1} \alpha^i \Vert \nabla f_i (x_n^{i,t}) \Vert^2 \leq \dS{x_n}^2 - \dS{x_{n+1}}^2 \leq \delta. \end{equation*} The above inequality implies there exists a constant C such that $\Vert \nabla f_i (x_n^{i,t}) \Vert^2 \leq C\delta$ holds for all $i \in [1,\cdots,m]$ and $t\in [0,\cdots,T_i]$. Selecting $t=0$ and noticing $x_n^{i,0} = x_n$, we obtain \begin{equation*} \Vert \nabla f(x_n) \Vert^2 = \Vert\frac{1}{m}\sum_{i=1}^{m} \nabla f_i(x_n)\Vert^2 \leq \frac{1}{m}\sum_{i=1}^{m} \Vert\nabla f_i(x_n) \Vert^2 \leq C\delta. \end{equation*} Since $C\delta$ can be arbitrarily small, we conclude the gradient residuals $\Vert \nabla f(x_n) \Vert^2$ vanish regardless of the choice of $T_i$. (2) To answer question 2, we notice larger $T_i$ decreases $d(x_{n},S)$ more aggressively in Lemma~\ref{lm:mother_equation}. Namely, more local updating $T_i$ lead to less communication round $n$ to reach the same distance. (3) The above analysis does not rely on a specific choice of learning rate $\eta_i$. Specifically, a constant learning rate $\eta_i$ can be used in local GD, and this is in contrast to studies like \cite{zhou2017convergence,stich2018local,yu2018parallel} where algorithm relies on a diminishing stepsize to obtain convergence. With a constant learning stepsize, the local learning on each node $i$ can be potentially faster, especially for the restricted strongly convex cases considered in Sec~\ref{sec:linear_conv_sc}. The above analysis provides qualitatively answers for the questions in Sec 1, and we shall restate these results with more concrete theorems in the following result. \subsection{Sublinear Convergence Rate for General Convex Case} \begin{restatable}{Theorem}{theoremtwo} \label{th:convergeceGuarantee} Suppose $f_i$ is convex and $L_i$-smooth, $\alpha_i > 0$, and $1\leq T_i \leq \infty$ for all $i=1,\dots,m$. Then, \begin{enumerate} \item[(i)] $\liminf_{n\rightarrow\infty} n \| \nabla f (x_n) \|^2 = 0$, \item[(ii)] $\liminf_{n\rightarrow\infty} n^{\tfrac{1}{2}} [ f (x_n) - \min_{y\in\mathbb{R}^d} f(y) ] = 0$. \end{enumerate} \end{restatable} \begin{Proof} Eq.~\eqref{eq:mother_equation} implies the sequence $\{ \dS{x_n}^2 : n\geq0 \}$ is non-increasing, and its limit exists. Define $z_n := \tfrac{1}{m}\sum_{i=1}^{m} \sum_{t=0}^{T_i - 1} \alpha_i \| \nabla f_i (x_n^{i,t}) \|^2 \geq 0$. Summing Eq.~\eqref{eq:mother_equation} and taking limit, we get \begin{align*} \lim_{n\rightarrow\infty} \sum_{k=0}^{n-1} z_k \leq \dS{x_0}^2 - \lim_{n\rightarrow\infty} \dS{x_n}^2 < \infty, \end{align*} which then implies $\liminf_{n\rightarrow\infty} n z_n \rightarrow 0$. Since $T_i\geq 1$, we have $$z_n \geq \tfrac{\min_i \alpha_i}{m}\sum_{i=1}^{m} \| \nabla f(x^{i,0}_n) \|^2 \geq \min_i \alpha_i\| \nabla f(x_n) \|^2.$$ Hence $\liminf_{n\rightarrow\infty} n \| \nabla f (x_n) \|^2 \rightarrow 0.$ This proves $(i)$. To show $(ii)$, observe that for any $x^* \in S$, by convexity we have \begin{align*} f(x^*) \geq f(x_n) + \langle \nabla f(x_n), x^* - x_n \rangle, \end{align*} and so $ f(x_n) - f(x^*) \leq \| \nabla f(x_n) \| \dS{x_0}$ and $(ii)$ follows. \end{Proof} \paragraph{Remark:} (1) Theorem~\ref{th:convergeceGuarantee} shows that if we are working with convex functions with Lipschitz gradients, then the intersection assumption~\ref{Ass:intersection} is enough to guarantee the convergence of Alg \ref{alg} as the overall gradient norms $\| \nabla f (x_n) \|^2$ vanish, and moreover that a subsequence does so at a rate $\mathcal{O}(1/n)$; If further that the gradient norms form a monotone sequence, then this rate holds for the whole sequence. (2) Theorem~\ref{th:convergeceGuarantee} indicates that the algorithm converges for arbitrary choices of the number of local updates, including $T_i = \infty$, which represents the idealized situation where the local gradient descent problem is solved to completion before each communication step. This is attractive in practice, as it allows for each node to perform computation independently from other nodes for long times before having to exchange information. \vspace{0.1in} \subsection{Linear Convergence Rate for Restricted Strongly Convex Case} \label{sec:linear_conv_sc} The convergence rate bound in Theorem~\ref{th:convergeceGuarantee} is far from fast. In the following, we show that if some additional assumptions are adopted, then convergence can be shown to be linear in the number of communication steps. \begin{Assumption} \label{Ass:restricted_sc} Each $f_i$ satisfies restricted strong convexity, i.e. there exists constants $\mu_i > 0$ such that $$ \| \nabla f_i (x) \| \geq \mu_i \dSi{x},$$ \end{Assumption} \begin{Assumption} \label{Ass:separation} The optimum sets $\{ S_i \}$ satisfy a separation property: there exists a constant $c>1$ such that $$\dS{x} \leq c \cdot \tfrac{1}{m} \sum_{i=1}^{m} \dSi{x}.$$ \end{Assumption} Assumption~\ref{Ass:restricted_sc} is a relaxed version of strong convexity, and coincides with it if $S_i$ is a singleton. Basically, this says that outside of the minimum set, the functions $f_i$ behave like strongly convex functions lower-bounded by some quadratic function. Assumption~\ref{Ass:separation} is an interesting geometric property, which roughly translates to the statement that that the ``angle of separation'' between the optimal sets is bounded from below. The fact that convergence properties depend on geometric properties of minimum sets also highlights the difference with classical distributed optimization. \begin{restatable}{Theorem}{theoremthree} \label{th:restricted_sc_linear_conv} Let assumptions~\ref{Ass:restricted_sc} and~\ref{Ass:separation} be satisfied. Then, for any $1\leq T_i \leq \infty$ we have \begin{equation*} \dS{x_n} \leq \rho^n \dS{x_0}, \end{equation*} where $\rho = \sqrt{1 - c^{-1} \min_i\{ \alpha_i\mu_i^2 \} }$ and $\alpha_i$ is such that $\alpha_i \mu_i^{2} \leq 1$. \end{restatable} \begin{Proof} From Eq.~\eqref{eq:mother_equation} and assumptions~\ref{Ass:restricted_sc} and~\ref{Ass:separation}, we have for any $T_i\geq 1$ \begin{align*} \dS{x_{n+1}}^2 \leq& \dS{x_n}^2 - \tfrac{1}{m}\sum_{i=1}^{m} \alpha_i \| \nabla f_i (x_n) \|^2 \\ \leq& \dS{x_n}^2 - \tfrac{1}{m}\sum_{i=1}^{m} \alpha_i \mu_i^2 \dSi{x_n}^2 \\ \leq& \dS{x_n}^2 - \min_i\{ \alpha_i\mu_i^2 \} \tfrac{1}{m} \sum_{i=1}^{m} \dSi{x_n}^2 \\ \leq& [1 - c^{-1} \min_i\{ \alpha_i\mu_i^2 \} ] \dS{x_n}^2, \end{align*} where $c>1$. Now, observe that $\alpha_i \leq 1/L_i^2$ and $\mu_i \leq L_i$, and so $\kappa^{-1}:=\min_i(\alpha_i\mu_i^2) \in (0,1]$. In fact, $\kappa$ can be understood as an effective condition number for $f$. Thus $\rho = \sqrt{1-(c\kappa)^{-1}} \in (0,1)$ and the claim follows. \end{Proof} Theorem \ref{th:restricted_sc_linear_conv} shows that if each local function $f_i$ satisfies the restricted strong convexity assumption and the geometric assumption also holds, a linear convergence rate can be obtained. Similar to Theorem~\ref{th:convergeceGuarantee}, any $T_i$ including infinity guarantees convergence, which does not hold for scenarios without the intersection assumption. \subsection{Convex Experiments} \label{sec:convex_exp} \subsubsection{General Convex Case} We first validate the general convex cases where Theorem~\ref{th:convergeceGuarantee} implies the gradient residuals $\| \nabla f (x_n) \|^2$ vanish with a speed approximately of order $1/n$. The example we consider is an synthetic case from~\cite{beck2003convergence}, as the $x_n$ can approach the optimal point $x^*$ with an arbitrary slow speed. Specifically, the loss functions on two nodes are defined as $f_1(x,y) = \max^2 \left( \sqrt{x^2 + (y-1)^2}-1,0 \right)$ and $f_2(x,y) = \max^2 \left( y, 0 \right)$ so that the feasible set $S_1$ only intersects with $S_2$ at the point $(0,0)$. Heuristically, consider a point $x$ around the boundary of $S_1$ so that $d(x,S_1) \approx 0$. In this case, \begin{align*} \frac{d(x,S)}{\frac{1}{m} \sum_{i=1}^{m} d(x,S_i)} &\approx \frac{d(x,S)}{\frac{1}{2} d(x,S_2)} = \frac{2}{\sin\theta}. \end{align*} If $\theta \rightarrow 0$, the left hand side goes to infinity and therefore the separation condition~\ref{Ass:separation} does not hold for this case. \begin{figure}[!h] \centering \includegraphics[width=0.35\linewidth]{Crop2.jpg} \caption{Synthetic experiment. The separation condition is not satisfied.} \label{fig:syn} \end{figure} A start point $x_0$ is randomly selected and each node performs $T_i=10$ gradient descent steps independently before combining the parameters. Fig~\ref{ConvexA} reports how the gradient residuals $\| \nabla f (x_n) \|^2$ and the function values $f(x_n)$ vanish after each combination. To enhance visualization, we plot an auxiliary function $\hat{f}$ with a specified gradient vanishing speed $\Vert \nabla \hat{f} \Vert^2_2 =C/n$ as a reference (black line). The similar trend of the gradient residuals $\| \nabla f (x_n) \|^2$ to our reference line validates our previous conclusion in Theorem~\ref{th:convergeceGuarantee} that the gradient residuals $\| \nabla f (x_n) \|^2$ vanish with an approximate speed of $\mathcal{O}(1/n)$. \begin{figure*}[!t] \centering \hspace*{\fill} \subfigure[Experimental results on synthetic dataset with $T_i = 10$. The black line is a reference function with $\Vert \nabla \hat{f} \Vert^2 =C/n$. Gradient residual $\| \nabla f (x_n) \|^2$ can be observed to vanish with a speed similar to $1/n$.] {\label{ConvexA} \includegraphics[width=.44\linewidth]{1_T_Convergence_Rate_Loss_GD_MSE} } \hfill \subfigure[Mean-square regression on Cancer dataset with various $T_i$. The threshold $\Vert \nabla f_i \Vert^2 \leq 10^{-8}$ is set to simulate $T_i = \infty$. Linear convergence rates can be observed for all $T_i$. ] {\label{ConvexB} \includegraphics[width=.44\linewidth]{log_T_1000_MSE_Convex_Cancer_GD.pdf} } \hspace*{\fill} \caption{Convex experiments. The x-axis on the left denotes $\log(n)$ and the x-axis on the right denotes $n$, and the y-axis represents the gradient residuals $\| \nabla f (x_n) \|^2$.} \label{fig:convex} \end{figure*} \subsubsection{Linear Convergence Case} To validate the linear convergence rate in Theorem~\ref{th:restricted_sc_linear_conv}, we perform mean-square regression on the colon-cancer dataset~\cite{alon1999broad} from LIBSVM data repository\footnote{\url{https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/}}, which consists of 62 tumor and normal colon tissue samples with 2000 features. Data are evenly distributed to $m=2$ nodes, and models on each node are all over-parameterized since feature numbers far exceed instance numbers. Similar to previous experiment, each node is required to perform $T_i$ rounds of GD before communication. The infinity case $T_i = \infty$ is simulated by performing continuous GD until the local gradient norm is sufficiently small $\Vert \nabla f_i \Vert^2 \leq 10^{-8}$. The restricted strong convex assumption and separation assumption are all satisfied in this case, and the experimental results in Fig~\ref{ConvexB} are consistent with conclusions derived in Theorem~\ref{th:restricted_sc_linear_conv}: (1) all $T_i$ leads to linear convergence rates, including the infinity case; (2) more local updating $T_i$ decreases the overall gradient residuals $\| \nabla f (x_n) \|^2$ faster, indicating sufficient local updating can reduce the overall communication cost for over-parameterized cases. \vspace{0.2in} \section{Beyond Convexity} \label{sec:nonconvex} Having established some basic convergence properties in the convex case, a natural question is whether these results hold beyond the convexity assumption. Instead of the fully general case, we first consider the following simple extension out of the convex realm, under which some convergence results can be obtained. \subsection{Quasi-Convex Case} Among all the non-convex scenarios, we shall first focus on the analysis of quasi-convex cases with the following assumption: \begin{Assumption} \label{Ass:quasi_convex} Each $f_i$ is differentiable and quasi-convex, i.e. have convex sub-level-sets. Equivalently, for any $x,y\in\mathbb{R}^d$, $f_i(\lambda x + (1-\lambda) y ) \leq \max\{ f_i(x), f_i(y) \}$ for $\lambda \in [0,1]$. \end{Assumption} \begin{Assumption} \label{Ass:affine_opt_set} Each $S_i$ is an affine subspace, i.e. there exist $x^*_i \in \mathbb{R}^d$ and subspaces $U_i \subseteq \mathbb{R}^d$ such that \begin{align*} S_i = \{x^*_i\} + U_i \equiv \{ x^*_i + u: u\in U_i \}. \end{align*} \end{Assumption} Assumption~\ref{Ass:quasi_convex} is a relaxation of convexity; every convex function is quasi-convex, but the converse does not hold. For example, the sigmoid and tanh functions are quasi-convex, but not convex. Assumption~\ref{Ass:affine_opt_set} says that the optimal set of local functions are affine subspaces. This is quite a strong assumption, but it greatly simplifies the analysis. Although it is unlikely to hold in general situations, it does have some heuristic connections to neural networks, which we will subsequently discuss. \begin{restatable}{Lemma}{lemmafour} \label{lm:affine} Let $f_i:\mathbb{R}^d\rightarrow \mathbb{R}$ satisfy assumptions~\ref{Ass:quasi_convex} and~\ref{Ass:affine_opt_set} above. Then, for every $x\in\mathbb{R}^d$ we have \begin{align*} f_i(x + u) = f_i(x) \end{align*} for all $u\in U_i$. \end{restatable} \begin{Proof} Without loss of generality, we may assume $\min_y f_i(y) = 0$. Let $x\in \mathbb{R}^d$. If $f_i(x) = 0$ then we are done. Suppose instead that $f_i(x) = c > 0$, we first show that $f_i(x+u) \leq c$ for all $u \in U_i$. Suppose for the sake of contradiction that there exists $u\in U_i$ with $f_i(x+u) = c + \delta$, $\delta>0$. Then, by continuity there exists a $\lambda \in (0,1)$ such that $f_i(\lambda(x+u) + (1-\lambda) x_i^*) = c + \delta/2$. Set $y:=\lambda(x+u) + (1-\lambda) x_i^*$ and $z := (y - \lambda x) / (1-\lambda)$, then by quasi-convexity we have \begin{align*} f_i(y) \leq \max \{ f_i(x), f_i(z) \}. \end{align*} But, by construction, $z = x^*_i + \tfrac{\lambda}{1-\lambda} u \in S_i$, and thus $f_i(z) = 0$, and so the above gives \begin{align*} c < c + \delta / 2 = f_i(y) \leq \max \{ c, 0 \} = c \end{align*} which leads to a contradiction. Hence, we must have $f_i(x+u) \leq f_i(x)$ for all $u\in U_i$, but by replacing $u$ with $-u$ we also have the reverse inequality, and so we must have $f_i(x+u) = f_i(x)$ for all $u\in U_i$. \end{Proof} \begin{restatable}{Lemma}{lemmafive} \label{corr:gd_orthogonality} For every $x\in \mathbb{R}^d$, we have $\langle u, \nabla f_i(x) \rangle = 0$ for all $u\in U_i$. In particular, if $\{ x^{i,t} : t\geq 0, x^{i,0} = x\}$ is a sequence of convergent gradient descent iterates under loss $f_i$, then for each $t\in [0,\infty]$, $x - x^{i,t} \perp U_i$ and $x^{i,\infty} = P_{S_i}(x)$. \end{restatable} \begin{Proof} Since $f_i$ is differentiable, we have $\langle u, f_i(x)\rangle = \lim_{\epsilon\rightarrow 0} \tfrac{1}{\epsilon} [f_i(x+\epsilon u) - f_i(x)] = 0$. Now, take any $u\in U_i$. We have $\langle u, x^{i,t+1} - x^{i,t} \rangle = - \eta_i \langle u, \nabla f_i(x) \rangle = 0$. Summing, we have $\langle u, (x^{i,t} - x) \rangle = 0$. If gradient descent converges, we can take the limit $t\rightarrow\infty$ to obtain $\langle u, x^{i,\infty} - x \rangle = 0$. But $x^{i,\infty} \in S_i$ which is closed since $f_i$ is continuous, and so by uniqueness of orthogonal projection, $x^{i,\infty} = P_{S_i}(x)$. \end{Proof} \vspace{0.2in} Recall from Sec~\ref{sec:linear_conv_sc} that to ensure linear convergence, a geometrical assumption on the optimal sets were required. We show in the following result that in the current setting where optimal sets are affine subspaces, this separation condition is automatically satisfied. \begin{restatable}{Lemma}{lemmasix} \label{lm:affine_separation} Let $S_i$, $i=1,\dots,m$ be a collection of affine subspaces with non-empty intersection $S = \cap_{i=1}^{m} S_i$. Then, \begin{align*} \tfrac{1}{m} \sum_{i=1}^{m} \dSi{x} \leq \dS{x} \leq \tfrac{c}{m} \sum_{i=1}^{m} \dSi{x}, \quad x\in \mathbb{R}^d, \end{align*} for some constant $c \geq 1$ with equality if and only if $S_i = S$ for all $i$. \end{restatable} \begin{Proof} The lower bound is immediate since $S\subseteq S_i$ and so $\dSi{x} \leq \dS{x}$. We now prove the upper bound. By a translation we can consider without loss of generality that $S_1,\dots,S_m$ and $S$ are subspaces. Thus, for each $i$ there exists a matrix $A_i$ whose rows are a orthonormal basis for $S_i^\perp$ and $\ker(A_i) = S_i$. The projection operator onto $S_i$ is then $P_i = I - A_i^\dag A_i$ (where $\dag$ denotes the Moore-Penrose pseudo-inverse) and the projection onto $S_i^\perp$ is $P_i^\perp = A_i^\dag A_i$. In particular, for each $x\in \mathbb{R}^d$, we have $\dSi{x} = \| P_i^\perp x \| = \| A_i^\dag A_i x \|$. Now, we show that the projection $P$ onto $S$ is $P = I - Q^\dag Q$, where $Q = I - \tfrac{1}{m} \sum_{i=1}^{m} P_i = \tfrac{1}{m} \sum_{i=1}^{m} A_i^\dag A_i$, and consequently $P^\perp = Q^\dag Q$. To show this it is enough to show that $S = \ker(\tfrac{1}{m}\sum_{i=1}^m A_i^\dag A_i)$. The forward inclusion is trivial, and the reverse inclusion follows from the fact that for any $x\in \ker(\tfrac{1}{m}\sum_{i=1}^m A_i^\dag A_i)$, we have \begin{align*} \begin{split} \| x \| = \| \tfrac{1}{m} \sum_{i=1}^{m} P_i x \| \leq \tfrac{1}{m} \sum_{i=1}^{m} \| P_i x \| \leq \tfrac{1}{m} \sum_{i=1}^{m} \| x \| = \| x \|, \end{split} \end{align*} with equality if and only if $P_i x = x$ for all $i$, i.e. $x\in S$. Now, we have \begin{align*} \begin{split} \dS{x} =& \| P^\perp x \| = \| Q^\dag Q x \| \\ \leq& \| Q^\dag \| \| Q x \| \\ \leq& {\sigma_{\text{min}}(Q)}^{-1} \| \tfrac{1}{m} \sum_{i=1}^{m} A^\dag A x \| \\ \leq& {\sigma_{\text{min}}(Q)}^{-1} \tfrac{1}{m} \sum_{i=1}^{m} \| A^\dag A x \| \\ \leq& {\sigma_{\text{min}}(Q)}^{-1} \tfrac{1}{m} \sum_{i=1}^{m} \dSi{x}, \end{split} \end{align*} where $\sigma_{\text{min}}(Q)$ denotes the smallest (non-zero) singular value of $Q$. Note that since the rows of $A_i$ are orthonormal, $\sigma_{\text{min}}(Q) \leq \tfrac{1}{m}\sum_{i=1}^{m} \| A_i^\dag A_i \| = 1$ with equality if and only if all $A_i^\dag A$ are multiples of each other (hence identical, by the orthonormal constraint), which implies $S_i=S$ for all $i$. Moreover, if $\sigma_{\text{min}}(Q) = 0$, then $Q=0$ and since each $A_i^\dag A_i$ is positive semi-definite, then $A^i = 0$ and $S_i = \mathbb{R}^d$ for all $i$, in which case any $c>0$ suffices. Thus, we can assume $c < \infty$. \end{Proof} \vspace{0.2in} With the separation condition, we can now establish the convergence rate for the current setting. \begin{restatable}{Theorem}{theoremseven} \label{th:linear_conv_affine} Let Assumption~\ref{Ass:quasi_convex} and \ref{Ass:affine_opt_set} hold. Take $T_i=\infty$ for all $i$ and suppose that each local gradient descent converges. Then, \begin{align*} \dS{x_n} \leq {(1 - c^{-2})}^{\frac{n}{2}} \dS{x_0}. \end{align*}\end{restatable} \begin{Proof}{ Applying Lemma~\ref{lm:affine_separation}, we have \begin{align*} \dS{x_n}^2 \leq& \tfrac{c^2}{m} \sum_{i=1}^{m} \dSi{x_n}^2 = \tfrac{c^2}{m} \sum_{i=1}^{m} \| x_n - P_{S_i}(x_n) \|^2. \end{align*} By Corollary~\ref{corr:gd_orthogonality}, $x^{i,\infty}_n = P_{S_i}(x_n)$, thus \begin{align*} \| x_n - x^{i,T_i}_n \|^2 \leq& \| x_n - P_{S}(x_n) \|^2 - \| x^{i,T_i}_n - P_{S}(x_n) \|^2 \end{align*} and so, \begin{align*} \dS{x_n}^2 \leq& c^2 \dS{x_n}^2 - \tfrac{c^2}{m} \sum_{i=1}^{m} \| P_{S_i}(x_n) - P_{S}(x_n) \|^2 \\ \leq& c^2 \dS{x_n}^2 - c^2 \| \tfrac{1}{m} \sum_{i=1}^{m} P_{S_i}(x_n) - P_{S}(x_n) \|^2 \\ \leq& c^2 \dS{x_n}^2 - c^2 \dS{x_{n+1}}^2. \end{align*} Rearranging, we have \begin{align*} \dS{x_{n+1}} \leq \sqrt{1 - c^{-2}} \dS{x_{n}}. \end{align*}} \end{Proof} \paragraph{Remark:} Gradient descent for quasi-convex function can be arbitrary slow and therefore selecting a small $T_i$ may also lead to arbitrary slow convergence rate. In the above theorem, we set $T_i= \infty$ to make sure the local model get sufficient updates and hence the overall convergence is guaranteed. \clearpage \subsection{Deep Learning} As alluded to earlier, although Assumption~\ref{Ass:affine_opt_set} is quite restrictive, it represents an interesting class of problems where gradient descent and projections are intimately connected. Moreover, deep learning models typically consist of nested affine transformations and nonlinear activations. In the over-parameterized setting where hidden node numbers are large, the affine transformations create degeneracies exactly in the form of affine subspaces. Of course, in general the optimal sets of deep learning loss functions may be unions of affine subspaces, and furthermore the loss functions need not be quasi-convex, and hence the result above does not directly apply to deep neural networks. But we still get some \textbf{motivations} that in deep learning scenarios, the answers for these two questions in Sec~\ref{sec:intro} may be more similar to over-parameterized convex cases instead of the conventional distributed studies~\cite{li2014communication,stich2018local,yu2018parallel} that require $T_i$ to be sufficiently small to guarantee convergence. On the contrary, updating local models more precisely (with large or even infinite $T_i$) can indeed reduce the overall communication cost, as the optimal sets of these local models are likely to intersect. \textbf{\begin{figure*}[!t] \centering \subfigure[Gradient residual $\Vert \nabla f(x_n) \Vert^2$ for the Non-Intersected case.] {\label{nonInterA} \includegraphics[width=.42\linewidth]{NonOverlappingNetworkGradientComparison.pdf} } \subfigure[Loss for the Non-Intersected case.] {\label{nonInterB} \includegraphics[width=.42\linewidth]{NonOverlappingNetworkLossComparison.pdf} } \subfigure[Gradient residual $\Vert \nabla f(x_n) \Vert^2$ for the Intersected case.] {\label{InterA} \includegraphics[width=.42\linewidth]{OverlappingNetworkGradientComparison.pdf} } \subfigure[Loss for the Intersected case.] {\label{InterB} \includegraphics[width=.42\linewidth]{OverlappingNetworkLossComparison.pdf} } \caption{1 Layer Neural Network on MNIST dataset. $T_i =100$ for all cases.} \label{fig:1LayerNN} \end{figure*}} \subsubsection{Necessity of the Intersection Assumption} Before further numerical validation, we first highlight the necessity of the intersection assumption~\ref{Ass:intersection} that distinguishes our work from previous studies. We select the first 500 training samples from MNIST dataset~\cite{lecun1998gradient} and construct two 1-layer neural networks: (1) the first is to directly transform the $28 \cdot 28$ image into 10 categories by an affine transformation followed by softmax cross-entropy loss, which we name as the ``Intersected Case'' since the parameters exceed the instance numbers; (2) the second is to perform two continuous max-pooling twice with a $(2,2)$ window before the final prediction, which we name as the ``Non-Intersected Case'' since the total parameters number is 490 and the intersection assumption is not satisfied. Figure~\ref{fig:1LayerNN} shows the results of centralized training only on the server~(denoted as ``1 Node'') and distributed training on 10 nodes. Without the intersection condition being satisfied, the gradient residuals $\Vert \nabla f(x_n) \Vert^2$ may not even vanish on the ``Non-Intersected case'' in Fig~\ref{nonInterA} and the distributed training loss $f(x_n)$ can also be different from centralized learning in Fig~\ref{nonInterB}. On the contrary, both the gradient residuals and the loss on 10 learning nodes perform in a similar way to centralized learning for the ``Intersected case'' in Fig~\ref{InterA} and ~\ref{InterB}. These different results validate the importance of the intersection assumption we made in the previous part. \subsubsection{LeNet and ResNet} In practice, most deep learning models are highly over-parameterized, and the intersection assumption is likely to hold. In these scenarios, we numerically test the performance of Alg \ref{alg} on non-convex objectives and explore whether large or even ``infinite'' $T_i$ leads to less communication requirement. To do so, we select two classical benchmarks for deep learning: LeNet~\cite{lecun1998gradient} on MNIST dataset and ResNet-18~\cite{he2016deep} on CIFAR-10 dataset~\cite{krizhevsky2009learning}. To accelerate experiments, we only select the first 1000 training samples from these two dataset (although we also provide experiments on the complete dataset in appendix), and evenly distribute these instances to multiple learning nodes. Similar to our previous convex experiments, each node is required to perform $T_i$ iterations of GD before sending models to server, and the $T_i = \infty$ is simulated by continuous gradient descents until local gradient residual $\Vert \nabla f_i \Vert^2$ is sufficiently small. Figure~\ref{fig:dl} shows the experimental results on these benchmarks. The result is consistent with our previous convex experiments that choices for $T_i$ is no longer limited as the conventional studies, and larger $T_i$ decreases the total loss more aggressively. In other words, updating local model more precisely can reduces communication cost for these two deep learning models. Note that for ResNet-18, we intentionally set the local gradient norm threshold to a relatively small number $10^{-2}$, and hence the ``Threshold'' method requires thousands of epochs to reach this borderline in the beginning but only need a few epochs after 40 iterations, which explains why it first outperforms $T_i=100$ but then is inferior to it. \begin{figure*}[!t] \centering \hspace*{\fill} \subfigure[LeNet for MNIST dataset. The threshold is set as $\Vert \nabla f_i \Vert_2^2 \leq 10^{-4}$.] {\label{LeNet} \includegraphics[width=.44\linewidth]{10Nodes_Loss.pdf} } \hfill \subfigure[ResNet for CIFAR 10 dataset. The threshold is set as $\Vert \nabla f_i \Vert_2^2 \leq 10^{-2}$.] {\label{ResNet} \includegraphics[width=.44\linewidth]{10Nodes_Loss.pdf} } \hspace*{\fill} \caption{Deep learning experiments. The x-axis denotes the communication round $n$ and the y-axis denotes the $\log(f)$. } \label{fig:dl} \end{figure*} \section{A Quantitative Analysis of the Trade-off between Communication and Optimization} \label{sec:tradeoff} In previous sections we have focused on convergence properties. Recall that we proved in the convex case, essentially any frequency of local updates is sufficient for convergence. This effect then brings into relevance the following important practical question: given a degenerate distributed optimization problem, can we decide how many steps $T_i$ to take locally before a combination, in order to optimize performance or minimize some notion of computational cost? Note that this question is not well-posed unless convergence is guaranteed for any (or at least a large range of) $T_i$, as we have established in Sec 3 by relying on the degeneracy assumption. Building on the results earlier, we now show that in our setting, this question can be answered quantitatively and this gives guidance to designing efficient distributed algorithms. From Lemma~\ref{lm:mother_equation}, it is clear that the decrement of $\dS{x_{n}}$ come from two sources, one from the frequency of applying the outer iteration in $n$ (communication), and the other from the size of $\sum_{t=0}^{T_i - 1} \alpha_i \| \nabla f_i (x_n^{i,t}) \|^2$, which relies on $T_i$ and also the rate of convergence of local gradient descent steps (optimization). It is well-known that for general smooth convex functions, the upper-bound for the decay of gradient norms is $\mathcal{O}(t^{-1})$. However, depending on the loss function at hand, different convergence rates can occur, ranging from linear convergence to sub-linear convergence in the form of power-laws. Therefore, to make headway one has to assume some decay rate of local gradient descent. To this end, let us assume that the local gradient descent decreases the gradient norm according to \begin{align} \label{eq:h_def} \| \nabla f_i(x_n^{i,t}) \|^2 \geq h_i(t) \| \nabla f_i(x_n^{i,0}) \|^2 \end{align} where $h_i(t)$ is a positive, monotone decreasing function with $h_i(0)=1$. Let $\epsilon>0$ be fixed and define \begin{align} \label{eq:n_star_def} n^* = \inf \{ k\geq 0, \|\nabla f(x_k)\|^2 \leq \epsilon \}. \end{align} From Lemma~\ref{lm:mother_equation} and Eq.~\eqref{eq:h_def} we have \begin{align*} \dS{x_{n+1}}^2 \leq \dS{x_{n}}^2 - \tfrac{1}{m}\sum_{i=1}^{m} \sum_{t=0}^{T_i - 1} \alpha_i h_i(t) \| \nabla f_i( x_n) \|^2. \end{align*} Assume for simplicity $T_i=T$ for all $i$. we have for each $n \leq n^* - 1$, \begin{align*} \dS{x_{n+1}}^2 \leq \dS{x_{n}}^2 - \sum_{t=0}^{T - 1} \alpha h(t) \epsilon, \end{align*} where $\alpha := \min_i \alpha_i$ and $h(t) := \min_i h_i(t)$. Hence, \begin{align} \label{eq:n_star_expr} n^* \leq \tfrac{\dS{x_0}^2}{ \alpha \epsilon \sum_{t=0}^{T-1} h(t)}. \end{align} This expression concretely links the number of steps required to reach an error tolerance to the local optimization steps. Now, we need to define some notion of cost in order to analyze how to pick $T$. In arbitrary units, suppose each communication step has associated cost $C_c$ per node and each local gradient descent step has cost $C_g$. Then, the total cost for first achieving $\|\nabla f(x_n) \|^2 \leq \epsilon $ is \begin{align*} \begin{split} C_{total} &= (C_c m + C_g m T) n^* \\ &= C_c m ( 1 + r T ) n^* \\ &\leq C_c m \dS{x_{0}}^2 {(\alpha\epsilon)}^{-1} \tfrac{( 1 + r T )}{ \sum_{t=0}^{T-1} h(t)}, \end{split} \end{align*} where we have defined $r := C_g / C_c$. We are mostly interested in the regime where $r$ is small, i.e. communication cost dominates gradient descent cost. The key question we would like to answer is: for a fixed and small cost ratio $r$, how many gradient descent steps should we take for every communication and combination step in order to minimize the total cost? It is clear that the answer to this question depend on the behavior of the sum $\sum_{t=0}^{T-1} h(t)$ as $T$ varies. Below, let us consider two representative forms of $h(t)$, which gives very different optimal solutions. \paragraph{Linearly Convergent Case.} We first consider the linearly convergent case where $h(t) = \beta^T$ and $\beta \in (0,1)$. This is the situation if for example, each $f_i$ is strongly convex (in the restricted sense, see Assumption~\ref{Ass:restricted_sc}). Then, we have \begin{align*} \sum_{t=0}^{T-1} h(t) = \tfrac{1 - \beta^T}{1 - \beta}, \end{align*} and so $ C_{total} \leq C_c m \dS{x_0}^2 (1 - \beta) {(\alpha\epsilon)}^{-1} \tfrac{1 + r T}{1 - \beta^T}. $ The upper bound is minimized at $T=T^*$, with \begin{align*} T^* = \tfrac{1}{\log \beta} \left[ 1 + W^-(-e^{-1} \beta^{\tfrac{1}{r}}) \right] - \tfrac{1}{r}, \end{align*} where $W^-$ is the negative real branch of the Lambert's $W$ function, i.e. $W^{-}(x e^x) = x$ for $x \in [-1/e, 0)$. For small $x$, $W^-$ has the asymptotic form $W^- = \log (-x) + \log (- \log (-x) ) + o(1)$. Hence, for $r\ll 1$ we have \begin{align*} T^* = \log \left( 1 + \tfrac{\log (\beta^{-1})}{ r } \right) + o(1). \end{align*} \paragraph{Sub-linearly Convergent Case.} Let us suppose instead that $h(t) = 1 / (1+ a t)^\beta$ for some $a>0,\beta >1$. This is a case with sub-linear (power-law) convergence rate, and is often seen when the local objectives are not strongly convex, e.g. $x^{2l}$ where $l$ is a positive integer greater than 1. For instance, in this case one can show that for small learning rates, $h(t)$ is approximately of this form with $a=2l - 2$ and $\beta = (2l - 1) / (2l-2)$ By integral comparison estimates we have \begin{align*} \int_{0}^{T} h(s) ds \leq \sum_{t=0}^{T-1} h(t) \leq 1 + \int_{0}^{T-1} h(s) ds. \end{align*} Therefore, \begin{align*} \tfrac{1 - {(1+a T)}^{1-\beta}}{a(\beta-1)} \leq \sum_{t=0}^{T-1} h(t) \leq 1 + \tfrac{1 - {(1+a (T-1))}^{1-\beta}}{a(\beta-1)}. \end{align*} Thus, we have \begin{align*} C_{total} \leq C_c m \dS{x_0}^2 a (\beta - 1) {(\alpha\epsilon)}^{-1} \tfrac{1 + r T}{1 - {(1 + a T)}^{1-\beta}}. \end{align*} The minimizing $T^*$ is the unique positive solution of the algebraic equation \begin{align} r \left((1 + a T^*)^{\beta }-1\right)-a (\beta +\beta r T^*-1) = 0, \end{align} whose asymptotic form for $r\ll 1$ is \begin{align*} T^* = \tfrac{1}{a} \left( \left[ \tfrac{a(\beta-1)}{r} \right]^{\tfrac{1}{\beta}} - 1 \right) + o(r^{-\tfrac{1}{\beta}}). \end{align*} From the explicit calculations above, we can see that the number of local gradient descent steps that minimizes the upper-bound total cost depends in a non-trivial manner on the speed of local gradient descent. If the latter is fast (linear convergence case), then the number of local steps to take is small $T^*\sim \log(1/r)$, whereas if local gradient descent is slow (sub-linear convergence case), one should take more local steps and $T^*\sim 1/r^{1/\beta}$. Besides theoretical interest, these estimates can be used in practice to tune the number of local descent steps: one may detect the order of local convergence on the fly, then use these estimates as a guideline to adjust $T$. This gives a principled way to balance optimization and communication, and is potentially useful for solving practical large-scale problems. \paragraph{Experiment.} \begin{figure} \centering \includegraphics[width=0.45\linewidth]{log_T_1000_Quartic_Convex_Cancer_GD.pdf} \caption{Cancer dataset with quartic loss function. The threshold is set as $\Vert \nabla f_i \Vert_2^2 \leq 10^{-8}$.} \label{fig:quartic} \end{figure} For comparison, we replace the quadratic loss in Fig \ref{ConvexB} with quartic loss and obtain Fig \ref{fig:quartic}. Gradient for quadratic loss starts with a large initial value but vanishes exponentially, and $T_i=100$ already coincide with threshold case in \ref{ConvexB}. Or equivalently, each node only need to maintain a relatively small $T_i$ and then refill gradient through combination. In contrary, gradient for quartic loss begins with a smaller value and decreases as a sub-linear case. Therefore, a sufficient large $T_i$ is required to reduce total communication rounds. \section{Conclusion} \label{sec:conclusion} In this paper, we analyzed the dynamics of distributed gradient descent on degenerate loss functions where the optimal sets of local functions intersect. The motivation for this assumption comes from over-parameterized learning that is becoming increasingly relevant in modern machine learning. We showed that under convexity and Lipschitz assumptions, distributed gradient descent converges for arbitrary number of local updates before combination. Moreover, we show that the convergence rate can be linear under the restricted convexity assumption, and that the convexity conditions can be relaxed if the optimal sets are affine subspaces -- an assumption connected in spirit to the degeneracies that arises in deep learning. Lastly, we analyzed quantitatively the trade-off between optimization and communication, and obtained practical guidelines for balancing the two in a principled manner. \bibliographystyle{unsrt}
{'timestamp': '2019-06-17T02:14:19', 'yymm': '1906', 'arxiv_id': '1906.06205', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06205'}
arxiv
\section{Introduction} \label{sec:intro} The collection of network data and the application of data analytics (including machine learning) allow the development of technologies to automate network management. Network management is best characterized using the FCAPS model from the ITU: \begin{itemize} \item \textbf{F}ault detection and correction \item \textbf{C}onfiguration and operation \item \textbf{A}ccounting and billing \item \textbf{P}erformance assessment and optimization \item \textbf{S}ecurity assurance and protection \end{itemize} In this work we seek to advance the automation of network fault detection. Specifically for network soft-failures that result in diminished performance. The symptoms of soft-failures are subtle and are therefore difficult to diagnose manually: increased bit errors, occasional packet loss, unnecessarily long paths through the network, or congestion control mechanisms unnecessarily reducing throughput. In this work, we utilize a suite of data analytics (e.g., clustering and outlier detection) to detect the occurrence of network soft-failures: bit errors, packet loss. The end result of these data analytics is an outlier score for each network link called the Network Link Outlier Factor (NLOF). The NLOF score is an indicator of how likely a link is experiencing a network soft-failure. \subsection{Related work} A survey~\cite{DS0516} of recent fault localization techniques expands on the taxonomy presented in \cite{SS0704}. The taxonomy presented consists of three categories of fault localization: Artificial Intelligence, Model Traversing, and Graph-theoretic. Much of the related work implements active probing techniques \cite{MMHTOM0515, D1206, CW1016}. These techniques use probe messages to infer the state of links and require optimal probe placement~\cite{NSL0308, CQMQB0310, NS1107} to trade off measurement with resource consumption. More recent work~\cite{MTG0818} uses passive data (e.g., number of: flows, lost packets, average packet delay) and compares the performance of several machine learning techniques (e.g., random forests and multi-layer perceptrons) to localize faults. Their results are compared to the active probing technique in \cite{CW1016}. Other recent work in the domain of optical networking uses passively collected physical layer data and machine learning to detect and/or localize faults~\cite{VSRCCLPCCYV0118, SMCT0318}. Some related work uses a hybrid-approach~\cite{TAB0505, TAB0308} that mixes active probing with passive data collection. In \cite{TAB0505} the authors present a fault localization framework named Active Integrated fault Reasoning (AIR). AIR uses passive monitoring to compile a set of observed symptoms. The framework then generates sets of faults that may be causing the symptoms. Each of these fault sets is tested to validate if any of them are credible. If none are credible then there is likely to be a symptom that was not observed by the passive monitoring. To identify if the likely symptom is present active probes are used. Afterward, the sets of faults go through the credibility test again. Software Defined Networks~\cite{AAK0914, SSCPD1011} including OpenFlow~\cite{MABPPRST0408} along with advances in machine learning are sparking a resurgence in network fault localization. Software Defined Networking allows for a broader view of the network, providing a simpler way to obtain network topology information~\cite{PPTI0316} for fault localization. As far as we know, our work is the first to use passive NetFlow and topology data to detect/localize network faults. \subsection{Outline} In Section \ref{sec:NLOF} we describe our suite of data analytics resulting in the NLOF score for each network link. In Section \ref{sec:experiments} we describe our NS-3 experiments to evaluate the failure detection performance of NLOF and in Section \ref{sec:results} we present and discuss the results of those experiments. Finally, we discuss our conclusions and outline paths for future work in Section \ref{sec:conclusion}. \section{Detecting Network Link Soft Failures} \label{sec:NLOF} We propose a method to detect network link soft-failures using NetFlow data. Specifically, we use the average throughput of flows from their collected NetFlow records. If the collected data consists of flows traversing the full span of the network, we believe it will allow us to detect any soft-failures in the full topology. We propose using flow throughput outlier detection to assist with the detection of network link soft-failures. Using topology and routing information we can correlate flows with the network links they traverse. We hypothesize that a network link experiencing a soft-failure will cause the flows traversing that link to exhibit abnormal throughput. Therefore, a network link carrying many flows that are throughput outliers is one that is experiencing a soft-failure. Using outlier detection directly on the average throughput of all flows requires the assumption that a majority of flows do not have abnormal throughput. Since this may not be a reasonable assumption, we first cluster the throughput of flows into the set of clusters we believe will naturally exist in a network and then identify the outliers within those throughput clusters. Our full technique to detect network link soft-failures consists of: 1) flow throughput clustering, 2) flow throughput outlier detection using an outlier score, 3) tracing flows on the network topology using routing information, and 4) network link outlier score computation from flow outlier scores. Figure \ref{fig:pipeline} illustrates this 4-stage analytics pipeline for detecting network link soft-failures. \begin{figure*}[!ht] \centering \includegraphics[scale = 0.39]{Figures/DataPipeline.pdf} \caption{Data analytics pipeline to compute Network Link Outlier Factor (NLOF)} \label{fig:pipeline} \end{figure*} \subsection{Flow Throughput Clustering (DBSCAN and TPCluster)} Network link soft-failures could cause a majority of flows to exhibit reduced throughput. As a result, we cannot immediately apply outlier detection techniques to the average flow throughput values. We propose to first organize average flow throughput into clusters. Network topologies will generally employ several network link transmission rates and the average flow throughput values will be limited by those values. In isolation, the average throughput of a flow will be limited by the bottleneck network link that it traverses. Let $\alpha$ be either the original generated throughput (or bitrate) of the flow or the bitrate at which the flow enters the network of interest, $\Gamma(i)$ be the network link rate of the $i$th network link a flow traverses in the network of interest. Then, in isolation, the average throughput of that flow will be: \begin{equation} \min \left\{\alpha, \min_{\forall_i} \left\{\Gamma(i)\right\}\right\} \end{equation} Flows will often share network links with other flows. Let $n(i)$ be the number of flows sharing the $i$th network link a flow traverses. Let's assume that flows share network links equally. Then, while sharing network links with other flows, the average throughput of that flow will be: \begin{equation} \min \left\{\alpha, \min_{\forall_i} \left\{\frac{\Gamma(i)}{n(i)}\right\}\right\} \mbox{.} \end{equation} Suppose we had a network topology with two different link rates, 1 Gbps and 100 Mbps and a network link was never shared by more than 4 flows at a time. In this case we would have 8 different values for average flow throughput in descending order (1 Gbps, 500 Mbps, 333 Mbps, 250 Mbps, 100 Mbps, 50 Mbps, 33.3 Mbps, and 25 Mbps). Network links experiencing soft-failures will reduce these average flow throughput values for flows traversing those links. Therefore, any average flow throughput values deviating significantly from these 8 discrete values are likely affected by a network soft-failure. Since we generally do not know the set of network link transmission rates nor the number of flows sharing network links, we let unsupervised machine learning (specifically, clustering) find these values for us. We select Density-Based Spatial Clustering of Applications with Noise (DBSCAN)\cite{EKSX0896} as our first stage of clustering since it naturally finds dense and potentially non-convex clusters without knowing the number of clusters a-priori. DBSCAN produces a number of clusters as well as a set of data points labeled as ``noise'' that do not fit into any of the clusters. A second stage of clustering is performed since the flows affected by soft-failures may begin to form their own dense cluster. In this second stage that we call TPCluster, we want to combine adjacent clusters if they are within a proximity to each other that suggests one may be a performance degraded set of the other. TPCluster provides a dynamic range based on the throughput context of the DBSCAN clusters. TPCluster uses two parameters, throughput ratio (\textit{tpr}) and throughput deviation (\textit{tpdev}). \textit{tpr} should be set to the maximum reasonable performance degradation of a throughput class and \textit{tpdev} should be set to the deviation that you might expect to see from a throughput class, to help cluster the flows labeled as ``noise'' into the appropriate cluster. Algorithm \ref{Alg:TPCluster} shows how TPClusters are formed. \begin{algorithm}[!ht] \label{Alg:TPCluster} \SetAlgoLined \KwData{Set of DBSCAN Clusters and the DBSCAN Noise Cluster} \Parameters{TPRatio (tpr), Throughput Deviation (tpdev)} \KwResult{Set of TPClusters} Sort DBSCAN Clusters In Descending Throughput Order\; j = 0\; \For{cluster[i] in DBSCAN clusters}{ \If{cluster[i] has not been combined}{ TPCluster[j] = aggregation of DBSCAN Clusters within range of ((1 - tpr)*$cluster[i]_{max}$, $cluster[i]_{max}$)\; j++\; } } \For{flow[j] in the DBSCAN noise cluster}{ k = 0\; \For{$cluster[i]$ in TPClusters} { dist = $cluster[i]_{max} - flow[j]_{TP}$\; \If{$dist \geq -tpdev * TPCluster[i]_{max}$} { $candidate[j][k]_{dist}$ = dist\; $candidate[j][k]_{cluster}$ = $cluster[i]$\; k++\; } \eIf{$k > 0$}{ ind = $\underset{k}{\operatorname*{argmin}} \{candidate[j][k]_{dist} \}$\; Add $flow[j]$ to $candidate[j][ind]_{cluster}$\; }{ Add $flow[j]$ to TPCluster with largest throughput\; } } } \caption{TPCluster} \end{algorithm} \subsection{Flow Outlier Factor (FOF)} Now that TPClusters have been defined we must now choose a point in each cluster to be the representative "normal" point ($Cluster_{normal}$) i.e. the point with a reasonable desirable performance. A method is to just use the point in the cluster with the highest performance however, we propose to use k-means clustering to use the cluster center as the representative point and as k increases the more aggressive the representative point will be. Algorithm \ref{Alg:FOF} shows how the Flow Outlier Factor (FOF) of each flow is computed. \begin{algorithm}[!ht] \label{Alg:FOF} \SetAlgoLined \KwData{Set of TPClusters and their constituent flows} \KwResult{FOF Scores for each flow} \For{cluster[i] in TPClusters}{ Separate cluster[i] into k clusters using K-Means\; $cluster[i]_{normal}$ = mean of K-Means cluster with the highest throughput\; \For{flow[i][j] in cluster[i]}{ $flow[i][j]_{FOF}$ = $\frac{cluster[i]_{normal} - flow[i][j]_{TP}}{cluster[i]_{normal}}$ } } \caption{Compute FOF} \end{algorithm} \subsection{Topology Flow Tracing} In this step we associate network links with the flows that traverse them. To make this association, flows are traced on the network topology using routing information. We use the NetworkX Python package to trace flows on the topology of a network assuming shortest path routing. \subsection{Network Link Outlier Factor (NLOF)} In this final step, we compute the outlier score for each network link (i.e., the NLOF). The flow outlier scores (i.e., FOFs) are used to compute the NLOF for the network links the flows traverse. Outlier flows are determined by a threshold on their FOF and the NLOF is computed to be the ratio of outlier flows to total flows traversing the network link. The NLOF is computed using Algorithm \ref{Alg:NLOF}. \begin{algorithm}[!ht] \label{Alg:NLOF} \SetAlgoLined \KwData{Set of Links with their associated flows} \Parameters{Outlier threshold} \KwResult{NLOF score for each Link} \For{$Link[i]$ in Links}{ outlierFlows = 0\; \For{Each $flow[i][j]$ in $Link[i]$}{ \If{$flow[i][j]_{FOF} >$ Threshold}{ outlierFlows++\; } } $Link[i]_{NLOF}$ = $\frac{outlierFlows}{Flows \ in \ Link[i]}$ } \caption{NLOF Computation} \end{algorithm} \section{Experiments} \label{sec:experiments} To evaluate the performance of NLOF, we utilize NS-3 simulation experiments. Figure \ref{fig:Topologies} show the two topologies we simulated. For each topology 3 experiments were run, for a total of 6 experiments. For each experiment all links were set to have a data rate of 10 Mbps. US1, US2, US3, UKS and BS are all OpenFlow switches implemented with the OpenFlow 1.3 module. The nodes and routers populate their routing tables using Routing Information Protocol (RIP). During each simulation 5000 On/Off flows were produced at a rate of either 1Mbps or 1Kbps between two randomly selected hosts in the network, the only exception is test 6, it had 2 additional throughput classes which are 10 Kbps and 2 Mbps for a total of 4. To collect the data from the simulation the built-in flow monitor model library was used. The probes were installed on all nodes to capture all the traffic in the network. Table \ref{Tab:Parameters} shows the configuration of the simulation for each test. The flow monitor library outputs the files in XML format, we then parsed the XML file to construct a pandas DataFrame to resemble flow records. The produced DataFrame will be in an acceptable format for SciKitLearn's DBSCAN clustering method. The DBSCAN clustering was done using the parameters eps = 100 and min\_samples = 50 which produced clusters that could then be combined to form TPClusters. TPClusters were formed using Algorithm \ref{Alg:TPCluster} with parameter values of tpr = 0.3, tpdev = 0.1 and k = 2. The flows were traced to put each flow into every network link that it traversed, assuming that the flow will take the shortest path which can be obtained using the NetworkX shortest path function. Finally the NLOF for each object was calculated using Algorithm \ref{Alg:NLOF} with an FOF threshold value of 0.1. \begin{table}[!ht] \centering \caption{Test Parameters} \label{Tab:Parameters} \resizebox{\columnwidth}{!}{ \begin{tabular}{|c|c|c|c|c|} \hline \textbf{Test} & \textbf{Links with Errors} & \textbf{Error Rate} & \textbf{Topology} & \textbf{Throughput Classes} \\ \hline 1 & None & 0 & 1 & 100 Kbps, 1Mbps \\ \hline 2 & (’129.108.40.2’, ’US1’) & 0.1 & 1 & 100 Kbps, 1Mbps \\ \hline 3 & \begin{tabular}[c]{@{}c@{}}(’129.108.42.4’, ’US3’)\\ (’129.108.41.3’, ’US2’)\\ (’129.108.40.2’, ’US1’)\end{tabular} & \begin{tabular}[c]{@{}c@{}}0.1\\ 0.1\\ 0.1\end{tabular} & 1 & 100 Kbps, 1Mbps \\ \hline 4 & None & 0 & 2 & 100 Kbps, 1Mbps \\ \hline 5 & (’BS’, ’R4’) & 0.1 & 2 & 100 Kbps, 1Mbps \\ \hline 6 & \begin{tabular}[c]{@{}c@{}}(’129.108.40.2’, ’US1’)\\ (’128.163.217.2’, ’UKS’)\\ (’129.108.42.4’, ’US3’)\end{tabular} & \begin{tabular}[c]{@{}c@{}}0.05\\ 0.03\\ 0.01\end{tabular} & 2 & \begin{tabular}[c]{@{}c@{}}10 Kbps, 100 Kbps, \\ 1 Mbps, 2Mbps\end{tabular} \\ \hline \end{tabular} } \end{table} \begin{figure*}[!t] \centering \begin{tabular}{cc} \includegraphics[width= 0.47\textwidth]{Figures/topology1.pdf}& \includegraphics[width= 0.47\textwidth]{Figures/topology2.pdf}\\ a) Topology 1& b) Topology 2\\ \end{tabular} \caption{NS-3 Topologies} \label{fig:Topologies} \end{figure*} \section{Results} \label{sec:results} Figures \ref{fig:ClustT1} and \ref{fig:ClustT2} show the flow throughput distribution (left-side sub-plot) and the corresponding TPClusters in a violin plot (right-side sub-plot) for tests 1 and 6 respectively. Figures \ref{fig:TP1} and \ref{fig:TP2} show the flow throughput distributions of each TPCluster for tests 1 and 6 respectively. As shown in Figures \ref{fig:ClustT1} and \ref{fig:ClustT2}, the TPClusters formed as expected i.e. one cluster for every throughput class. For test 1 we have the two throughput classes 100 Kbps and 1 Mbps with 2 corresponding clusters. For test 6 we have 4 TPClusters one for each of the throughput classes. More importantly the points labeled as noise by DBSCAN are moved into their appropriate TPCluster. For test 1 the cluster distributions have a small range that clearly indicates none of the flows have poor throughput performance within the context of their cluster. Figure \ref{fig:TP2} shows more interesting flow throughput distributions, this time there are four separate clusters, which all have flows farther away from the $Cluster_{normal}$ which can be seen visually by the larger range of each cluster. $Cluster_{normal}$ in this case is located in the upper half of the cluster distribution. The large range of the clusters indicates that there are flows with poor throughput performance belonging to these clusters. Our two-step clustering organizes the flows to properly identify those experiencing poor throughput performance. \begin{figure*}[!t] \centering \begin{tabular}{cc} \includegraphics[width= 0.7\columnwidth]{Figures/InputData_test1.pdf}& \includegraphics[width= 0.7\columnwidth]{Figures/test1.pdf}\\ a) Input Data Distribution& b) Violin Plot of TPClusters\\ \end{tabular} \caption{Input data and corresponding TPClusters for test 1} \label{fig:ClustT1} \end{figure*} \begin{figure*}[!t] \centering \begin{tabular}{cc} \includegraphics[width= 0.7\columnwidth]{Figures/InputData_test6.pdf}& \includegraphics[width= 0.7\columnwidth]{Figures/test6.pdf}\\ a) Input Data Distribution& b) Violin Plot of TPClusters\\ \end{tabular} \caption{Input data and corresponding TPClusters for test 6} \label{fig:ClustT2} \end{figure*} \begin{figure*}[!t] \centering \begin{tabular}{cc} \includegraphics[width= 0.6\columnwidth]{Figures/Cluster_1_test1.pdf}& \includegraphics[width= 0.6\columnwidth]{Figures/Cluster_2_test1.pdf}\\ a) Cluster 1 Distribution& b) Cluster 2 Distribution\\ \end{tabular} \caption{Distribution of test 1 clusters} \label{fig:TP1} \end{figure*} \begin{figure*}[!t] \centering \begin{tabular}{cccc} \includegraphics[width= 0.23\textwidth]{Figures/Cluster_1_test6.pdf}& \includegraphics[width= 0.23\textwidth]{Figures/Cluster_2_test6.pdf}& \includegraphics[width= 0.23\textwidth]{Figures/Cluster_3_test6.pdf}& \includegraphics[width= 0.23\textwidth]{Figures/Cluster_4_test6.pdf}\\ a) Cluster 1 Distribution& b) Cluster 2 Distribution& c) Cluster 3 Distribution& d) Cluster 4 Distribution\\ \end{tabular} \caption{Distribution of test 6 clusters} \label{fig:TP2} \end{figure*} Tables \ref{Tab:Topo1Results} and \ref{Tab:Topo2Results} show the results obtained for each test for topology 1 and 2 respectively. The links and NLOF scores that are in bold are the links that were set to have errors in the simulation, which correspond to Table \ref{Tab:Parameters}. The tables show that for Tests 1 and 4, both of which have no poor performing links, there is a NLOF score of 0 for all links. Test 2 has one link with a packet error rate of 0.1, that link has the highest NLOF score by a wide margin. Test 5 also has one link with a packet error rate of 0.1. However, this time it is a link connected between two nodes with high centrality rather than a link near the edge of the network. A large portion of the network traffic will go through this errored link, which explains the much higher NLOF scores in general compared to Test 2. Something interesting to note in Test 5 is that the link with a non-zero error rate does not have the highest NLOF score. This is likely caused by the fact that all the traffic to or from node "200.17.30.4" must go through the link with a non-zero error rate if communicating with a node not connected to the "BS" switch. One last thing to note about Test 5 is that the edges (BS,R4) and (R1,R4) have an identical NLOF score, which is easily explained since all the traffic that goes through one of those links must go through the other. Test 3 shows a different scenario now with 3 separate links all having a packet error rate of 0.1. Due to the fact that there are more links with non-zero error rates the NLOF scores will have larger values since there will be more poor performing traffic. Even in this scenario the NLOF score gives an idea as to which links are the ones with non-zero error rates, as the 3 of the top 4 NLOF scores are the links we are looking for as shown in bold in Table \ref{Tab:Topo1Results}. For Test 6 the packet error rates were lowered by a significant amount and the 3 links with non-zero errors are all different. Test 6 also had the added change of 2 extra throughput classes. The results are as expected, the 3 links with the highest NLOF scores are the 3 errored links. \begin{table*}[!ht] \centering \caption{Topology 1 Experiment Results} \label{Tab:Topo1Results} \begin{tabular}{@{}cc | cc | cc@{}} \toprule \multicolumn{2}{c}{\textbf{Test 1}} & \multicolumn{2}{c}{\textbf{Test 2}} & \multicolumn{2}{c}{\textbf{Test 3}} \\ \midrule {\ul \textbf{Link}} & {\ul \textbf{NLOF}} & {\ul \textbf{Link}} & {\ul \textbf{NLOF}} & {\ul \textbf{Link}} & {\ul \textbf{NLOF}} \\ ('128.163.217.2', 'UKS') & 0 & \textbf{('129.108.40.2', 'US1')} & \textbf{0.084057971} & \textbf{('129.108.42.4', 'US3')} & \textbf{0.462962963} \\ ('128.163.217.3', 'UKS') & 0 & ('US1', 'Router') & 0.014066496 & \textbf{('129.108.41.3', 'US2')} & \textbf{0.324675325} \\ ('128.163.217.4', 'UKS') & 0 & ('129.108.40.4', 'US1') & 0.005957447 & ('US3', 'Router') & 0.293251534 \\ ('129.108.40.2', 'US1') & 0 & ('200.17.30.4', 'BS') & 0.005957447 & \textbf{('129.108.40.2', 'US1')} & \textbf{0.259668508} \\ ('129.108.40.3', 'US1') & 0 & ('129.108.42.4', 'US3') & 0.005076142 & ('129.108.40.3', 'US1') & 0.12716763 \\ \bottomrule \end{tabular} \end{table*} \begin{table*}[] \centering \caption{Toplogy 2 Experiment Results} \label{Tab:Topo2Results} \begin{tabular}{@{}cc | cc | cc@{}} \toprule \multicolumn{2}{c}{\textbf{Test 4}} & \multicolumn{2}{c}{\textbf{Test 5}} & \multicolumn{2}{c}{\textbf{Test 6}} \\ \midrule {\ul \textbf{Link}} & {\ul \textbf{NLOF}} & {\ul \textbf{Link}} & {\ul \textbf{NLOF}} & {\ul \textbf{Link}} & {\ul \textbf{NLOF}} \\ ('128.163.217.2', 'UKS') & 0 & ('200.17.30.4', 'BS') & 0.383966245 & \textbf{('128.163.217.2', 'UKS')} & \textbf{0.108504399} \\ ('128.163.217.3', 'UKS') & 0 & \textbf{('BS', 'R4')} & 0.330143541 & \textbf{('129.108.40.2', 'US1')} & \textbf{0.084057971} \\ ('128.163.217.4', 'UKS') & 0 & ('R1', 'R4') & 0.330143541 & \textbf{('129.108.42.4', 'US3')} & \textbf{0.043147208} \\ ('129.108.40.2', 'US1') & 0 & ('R1', 'R2') & 0.179347826 & ('US3', 'R2') & 0.032704403 \\ ('129.108.40.3', 'US1') & 0 & ('129.108.40.3', 'US1') & 0.147058824 & ('UKS', 'R3') & 0.024746193 \\ \bottomrule \end{tabular} \end{table*} \section{Conclusion} \label{sec:conclusion} By using multiple simulations in the NS-3 environment we have shown that it is possible to detect and localize soft-failures in a network using the Network Link Outlier Factor (NLOF). The results in Tables \ref{Tab:Topo1Results} and \ref{Tab:Topo2Results} show that the links with failures have the highest NLOF score which indicates where a fault in the network likely is. Using a new clustering technique, named TPCluster, we are able to provide a context for the performance of each individual flow. Our simulation experiments show that TPCluster yields meaningful clusters for identifying faults using outlier detection techniques. For future work we plan on studying the thresholds on NLOF scores for declaring a link failure. We also plan to expand the types of soft-failures we can detect. \section{Acknowledgements} This material is based upon work supported by both the U.S. Army Research Laboratory (USARL) under Cooperative Agreement W911NF-18-2-0287 and the National Science Foundation under Grant No. OAC-1450997. \bibliographystyle{IEEEtran}
{'timestamp': '2019-06-18T02:03:22', 'yymm': '1906', 'arxiv_id': '1906.06433', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06433'}
arxiv
\subsubsection{\@startsection{subsubsection}{3}% \z@{.5\linespacing\@plus.7\linespacing}{.1\linespacing}% {\normalfont\itshape}} \makeatother \settopmatter{printacmref=false} \renewcommand\footnotetextcopyrightpermission[1]{} \usepackage{url} \usepackage{listings} \renewcommand{\ttdefault}{pcr} \lstset{language=[90]Fortran, basicstyle=\ttfamily\lst@ifdisplaystyle\scriptsize\fi, keywordstyle=\bfseries, comment=[l]{!\ }, escapechar=@, tabsize=3, } \newcommand{\SRC}[1]{% \lstinline[gobble=0]{#1}\xspace } \newcommand{\CMD}[1]{\SRC{#1}} \usepackage{xspace} \newcommand{\systemshape}{\sffamily} \newcommand{{\systemshape LIBXSMM}\xspace}{{\systemshape LIBXSMM}\xspace} \usepackage{placeins} \newcommand{{i.\,e.}\xspace}{{i.\,e.}\xspace} \newcommand{{e.\,g.}\xspace}{{e.\,g.}\xspace} \hyphenation{op-tical net-works semi-conduc-tor} \hyphenation{per-for-mance} \usepackage{algorithm} \usepackage[noend]{algpseudocode} \algnewcommand{\LineComment}[1]{\State \emph{\textcolor{blue}{\(\triangleright\) #1}}} \algrenewcommand\algorithmicindent{1em}% \makeatletter \makeatother \newcommand{\mathrel{+}=}{\mathrel{+}=} \usepackage{graphicx} \usepackage{caption} \usepackage{subcaption} \usepackage{tabularx} \usepackage{enumitem} \makeatletter \makeatother \usepackage{color, soul} \soulregister\emph7 \newcommand{\fix}[1]{\textbf{\textcolor{red}{#1}}} \begin{abstract} Deep learning (DL) is one of the most prominent branches of machine learning. Due to the immense computational cost of DL workloads, industry and academia have developed DL libraries with highly-specialized kernels for each workload/architecture, leading to numerous, complex code-bases that strive for performance, yet they are hard to maintain and do not generalize. In this work, we introduce the \emph{batch-reduce GEMM kernel} and show how the most popular DL algorithms can be formulated with this kernel as the basic building-block. Consequently, the DL library-development degenerates to mere (potentially automatic) tuning of loops around this sole optimized kernel. By exploiting our new kernel we implement Recurrent Neural Networks, Convolution Neural Networks and Multilayer Perceptron training and inference primitives in just 3K lines of high-level code. Our primitives outperform vendor-optimized libraries on multi-node CPU clusters, and we also provide proof-of-concept CNN kernels targeting GPUs. Finally, we demonstrate that the batch-reduce GEMM kernel within a tensor compiler yields high-performance CNN primitives, further amplifying the viability of our approach. \end{abstract} \begin{document} \title{High-Performance Deep Learning via a Single Building Block} \author{Evangelos Georganas, Kunal Banerjee, Dhiraj Kalamkar, Sasikanth Avancha, Anand Venkat, Michael Anderson, Greg Henry, Hans Pabst, Alexander Heinecke} \affiliation{\institution{Intel Corporation}} \renewcommand{\shortauthors}{E. Georganas et al.} \maketitle \section{Introduction} In the past decade, machine learning has experienced an academic and industrial renaissance where deep learning (DL) has been the main driving force. More specifically, deep neural networks have advanced the fields of computer vision, speech recognition, machine translation and search ranking, and naturally emerge in numerous applications and scientific domains~\cite{origalexnet,szegedy2015going,simonyan2014very,yu2013feature,wu2016google,cheng2016wide}. Three types of neural networks (NN) comprise the most prominent DL workloads by representing 95\% of the data-centers's demands~\cite{jouppi2017datacenter}: i) Recurrent Neural Networks (RNN)~\cite{graves2013speech} with the so-called Long Short-Term Memory (LSTM)~\cite{hochreiter1997long} networks being the most popular variation, ii) Convolution Neural Networks (CNN)~\cite{origalexnet}, and iii) Multi-Layer Perceptrons (MLP)~\cite{minsky2017perceptrons,hornik1989multilayer}. Additionally, the contemporary Transformer~\cite{transformer} and BERT~\cite{bert} workloads computationally involve fully-connected layers which also lie in the heart of MLP. All these neural networks can be further associated with two use-cases: \emph{training} of the underlying NN models (i.e.\ learning via back-propagation~\cite{lecun1988theoretical}), and \emph{inference} (i.e.\ yielding predictions) based on trained models. Due to the increase of the involved datasets' size and complexity in deep neural networks (DNN), the training and inference tasks require vast amount of computation. Therefore, academia and industry have invested into the development of DL libraries targeting all the aforementioned workloads on various architectures. The development of such DL libraries typically embraces one of the following strategies: (i) the specific workload kernel leverages coarse-grained, linear algebra library calls, e.g.\ LSTM cell via large GEneral Matrix Multiply (GEMM) calls in mkl-dnn~\cite{mkldnn}, convolutions via image-to-column tensor transformations and subsequent large GEMM calls~\cite{vasudevan2017parallel,anderson2017low}, or (ii) for each workload and use-case (training/inference) the kernel employs a specialized implementation that targets the specific algorithm/workload and architecture at hand, e.g.\ convolution kernels in mkl-dnn and cuDNN~\cite{chetlur2014cudnn}. The former approach of deploying coarse-grained, linear algebra library calls provides ease in the DL library development process since no special kernel development is involved. However it may result in suboptimal data reuse (e.g.\ redundant data movements to format underlying tensor/matrices in the required layout that enables GEMM calls), and also it is not flexible enough to allow efficient, fine-grained fusion of other operators. The latter approach of implementing specialized kernels for each DL workload/use-case and platform/architecture strives for performance but naturally results in numerous, complex code-bases that are hard to maintain and do not generalize. For example, the code-base \emph{only for convolutions on CPUs} within mkl-dnn consists of $\sim$36,000 lines of code. Figure~\ref{fig:motivation} shows the performance of various convolution kernel implementations on a Xeon Skylake-SP 8180 processor. The yellow and green lines represent implementations adopting strategy (i). More specifically, the green line shows the performance of convolutions that leverage small GEMM library calls, whereas the yellow line illustrates the performance of an implementation which uses image to column transformations and \emph{batched GEMM}~\cite{dongarra2017design} library calls. Both approaches perform far from the machine's peak with average efficiencies of 61\% and 49\% respectively. On the other hand, the orange line exhibits the performance of the vendor-optimized mkl-dnn library that follows strategy (ii) with ad hoc, specialized direct convolution kernels and achieves average efficiency of 81\%, being 1.33$\times$ and 1.64$\times$ faster than the aforementioned generic implementations. However, this performance comes at the cost of complex, specialized kernels that do not generalize to different workloads (e.g.\ RNN/LSTM/MLP) or different architectures (e.g.\ GPUs). \begin{figure}[t!] \centering \includegraphics[width=\columnwidth]{new_motivation.pdf} \caption{Performance of ResNet-50 forward convolutions} \label{fig:motivation} \end{figure} In this work, we introduce a new kernel called \emph{batch-reduce GEMM} and show how the most popular DL workloads and algorithms (RNN/LSTM, CNN and MLP) can be formulated with this new kernel as basic building block. The batch-reduce GEMM kernel essentially multiplies a sequence of input sub-tensor blocks (which form a \emph{batch}) and the partial multiplication results are \emph{reduced} into a single accumulator/output sub-tensor block. Our new kernel is flexible enough to accommodate coarse-grained and fine-grained operations that arise in DL workloads, whereas its semantics lend themselves to various optimizations (e.g.\ load/store optimizations of the result sub-tensor, prefetching of the sub-tensors to be multiplied). Also, since the kernel supports operations at fine granularity, fusion of subsequent operators on the output sub-blocks is inherently efficient. The blue line in Figure~\ref{fig:motivation} shows the performance of the convolution primitive that leverages our new \emph{batch-reduce GEMM} kernel achieving average efficiency of 83\%, and outperforms even the ad hoc, vendor-optimized kernel. Having a single kernel as basic building-block is transformative: by implementing and optimizing this single kernel for a given architecture, the development of DL primitives degenerates to mere loop tuning around this kernel. Essentially our approach with a \emph{single} kernel addresses the issue of combinatorial explosion of low-level optimization work that is required for each pair <architecture, DL primitive>. Instead, for each architecture we need to optimize at low-level \emph{only one kernel for all DL primitives}. Furthermore, having a single, highly efficient building-block enables efficient usage of tensor compiler frameworks. Such frameworks embrace tensors as first class citizens, and provide specific optimization techniques targeting tensor algebra programs. Since DL primitives are inherently tensor algebra programs, there is a large amount of ongoing research that leverages specialized tensor compilers for DL workload development (e.g.\ TVM~\cite{chen2018tvm}, GLOW~\cite{DBLP:journals/corr/abs-1805-00907}, PlaidML~\cite{plaidml}, MLIR~\cite{mlir}). However, compilers struggle to optimize small GEMM-flavored loop nests that arise in tensor programs~\cite{libxsmm}. Contemporary architectures become increasingly complex, and all the micro-architectural idiosyncrasies have to be considered in order to achieve close-to-peak performance. Our kernel is optimized for the nuances of the architecture at hand, and serves tensor compilers a robust building block that can be used during the polyhedral optimization phase of general loop nests~\cite{plaidml,poly}. To illustrate the viability and generality of our methodology with a single kernel, we develop DL primitives which target training and inference of RNN/LSTM, CNN and MLP workloads in $\sim$3,000 lines of high-level C code. Our primitives outperform vendor-optimized libraries on CPUs. We also provide proof-of-concept design with a tensor compiler framework by showcasing efficient CNN implementation in TVM that leverages our batch-reduce GEMM kernel. Additionally, our methodology provides a pathway for performance portability; we present exemplary, high-performance CNN kernels on integrated GPUs. Last but not least, we integrate our primitives in distributed DL frameworks (Tensorflow~\cite{tensorflow2015} and GxM~\cite{sc18}), and show performance results on two training workloads: Google's Neural Machine Translation (GNMT)~\cite{wu2016google} and ResNet-50 training~\cite{he2016deep}. These results push the envelope of DL training performance on CPU clusters. The main contributions of this paper are: \begin{itemize} \item The introduction of the batch-reduce GEMM kernel along with its efficient implementation. \item The design and implementation of multi-threaded, high performance DL primitives covering RNN/LSTM, CNN and MLP inference and training algorithms with batch-reduce GEMM kernel being the basic building block. We need to optimize at low-level \emph{only this kernel for all DL primitives}. \item A detailed performance comparison of our DL primitives with state-of-the-art vendor-optimized libraries. \item Distributed memory results of LSTM and CNN training workloads that leverage our optimized DL kernels and outperform the best in class results on CPU clusters. \item CNN proof-of-concept results on integrated GPUs and CNN kernels within TVM that leverage the batch-reduce GEMM kernel. \end{itemize} \section{The Batch-Reduce GEMM kernel} \label{sec:br_gemm} \begin{figure}[t!] \centering \includegraphics[width=\columnwidth]{combined2.pdf} \caption{(a) The batch-reduce GEMM kernel (b) Outer product small GEMM microkernel} \label{fig:br_gemm} \end{figure} In this section, we describe the design and implementation of the new batch-reduce GEMM kernel which comprises the cornerstone of our deep learning primitives. Figure~\ref{fig:br_gemm} (a) illustrates the functionality of the new kernel which materializes the operation: \begin{equation*} C_j = \beta \cdot C_j + \alpha \sum_{i=0}^{N-1} A_i \cdot B_i \end{equation*} This kernel multiplies the specified blocks $A_i \in {\rm I\!R}^{m\times k}$ and $B_i \in {\rm I\!R}^{k\times n}$ and \emph{reduces} the partial results to a block $C_j\in {\rm I\!R}^{m\times n}$ of a tensor $C$. Tensors $A$ and $B$ can alias and also the blocks $A_i$ and $B_i$ can reside in any position in the input tensors $A$ and $B$. The batch-reduce GEMM kernel takes the following arguments: (i) \emph{two arrays of pointers} to the corresponding blocks $A_i$ and $B_i$ to be multiplied, (ii) a pointer to the output block $C_j$, (iii) the number $N$ of the blocks to be multiplied and (iv) the scaling parameters $\alpha$ and $\beta$. Our kernel differs from the recently introduced batched GEMM~\cite{dongarra2017design} and its variation strided-batch-gemm~\cite{stridedbatchgmemm} that materialize: \begin{equation*} C_i = \beta \cdot C_i + \alpha \cdot A_i \cdot B_i \end{equation*} These batched routines are missing the \emph{reduction} functionality and cannot optimize for the output matrix re-use. Also, the strided-batch-gemm kernel accesses the $A_i$ and $B_i$ subblocks based on fixed strides and therefore is more restrictive. \begin{algorithm}[t] \begin{algorithmic}[1] \Statex \algbackskip \textbf{Inputs}: $A_i \in {\rm I\!R}^{m\times k},B_i \in {\rm I\!R}^{k\times n}i = 0,...,N\text{-}1$,\ $C_j \in {\rm I\!R}^{m\times n}$ $\alpha, \beta \in {\rm I\!R}$ \Statex \algbackskip \textbf{Output}:$\ C_j = \beta \cdot C_j + \alpha \sum_{i=0}^{N-1} A_i \cdot B_i$ \For{$i_n=0 \dots n-1\ \textbf{with\ step\ }\mathbf{n_b}$} \For{$i_m=0 \dots m-1\ \textbf{with\ step\ }\mathbf{m_b}$} \State acc\_regs $\leftarrow$ load $m_b \times n_b$ $C_j$$\text{\ subblock}_{i_m,i_n}$ \For{$i=0 \dots N-1\ \textbf{with\ step\ } \mathbf{1}$} \For{$i_k=0 \dots k-1\ \textbf{with\ step\ } \mathbf{1}$} \LineComment{Outer product GEMM microkernel} \State acc\_regs $\mathrel{+}=$ $A_i\ \text{subcolumn}_{i_m,i_k}\times B_i\ \text{subrow}_{i_k,i_n} $ \EndFor \EndFor \State $C_j\ \text{subblock}_{i_m,i_n} \leftarrow$ acc\_regs \EndFor \EndFor \end{algorithmic} \caption{The batch-reduce GEMM kernel} \label{alg:br_kernel} \end{algorithm} The new batch-reduce GEMM kernel specification naturally lends itself to a handful of optimizations. First, this kernel minimizes the output data movement compared to GEMM or batched GEMM approaches since the specification dictates the use of a single output. Second, the input subblocks that are multiplied can reside in arbitrary locations within tensors, therefore the kernel obviates the need for tensor transformations/copy overheads that are otherwise required in order to obtain long accumulation chains (e.g.\ image to column transformations are required to implement convolutions via large GEMM calls). Such long accumulation chains are essential in order to achieve high performance. Additionally, being able to provide arbitrary sub-tensor blocks as inputs provides ease of integration with blocked/tiled tensor layouts. Last but not least, since the input $A_i$ and $B_i$ subblocks are part of the interface, the implementation can trivially prefetch them in order to hide the latency of data movement. In order to obtain a high performance implementation of the batch-reduce GEMM kernel we build upon and extend the open source LIBXSMM~\cite{libxsmm} library which leverages JIT techniques and generates small GEMMS achieving close to peak performance. Algorithm~\ref{alg:br_kernel} shows the pseudocode of the batch-reduce GEMM kernel. Lines 1-2 block the computation of the result $C_j$ in $m_b \times n_b$ subblocks. Once such a subblock is loaded into the accumulation registers (line 3), we loop over all pairs $A_i,\ B_i$ (line 4) and we accumulate into the loaded registers the products of the corresponding $m_b\times k$ subblocks of $A_i$ with the relevant $k\times n_b$ subblocks of $B_i$ (lines 5-7). In order to calculate a partial product of an $m_b\times k$ subblock of $A_i$ with a $k\times n_b$ subblock of $B_i$, we follow an outer product formulation. In particular, we multiply an $m_b\times 1$ column of $A_i$ with a $1\times n_b$ row of $B_i$ (line 7) and we repeat the analogous outer product computation for all $k$ columns/rows of the $A_i$/$B_i$ subblocks (line 5). Figure~\ref{fig:br_gemm}(b) depicts the outer product microkernel that multiplies an $m_b\times 1$ column of $A_i$ with a $1\times n_b$ row of $B_i$ (in this example $m_b=64$, $n_b=6$). For illustration purposes, we consider that the underlying architecture has 32 vector registers where each one can hold 16 tensor elements. In this example, accumulation registers 7-30 hold the partial $C_j$ result. First, we broadcast the row of $B_i$ into registers 1-6. Then, we load in register 0 the first 16 elements of the $A_i$ column and via 6 fused-multiply-add instructions (FMAs) with registers 1-6 we update the accumulators 7-12. We repeat the analogous process for the remaining 48 elements of the $A_i$ column and we update all the accumulation registers. We note here that this is just one of the methods that LIBXSMM adopts for the outer product microkernel; LIBXSMM leverages various strategies depending on the architecture at hand (i.e.\ vector length) and the $m_b$, $n_b$ values. Once the $m_b \times n_b$ subblock of $C_j$ is fully computed for all pairs of $A_i$ and $B_i$ matrices, the accumulators are stored in the proper location of $C_j$ (line 8). Finally, we further enhance the microkernel with software prefetches of $A_i$ and $B_i$ elements aiming to mitigate cache miss latency overheads. \section{Deep Learning Kernels} \label{sec:dl_algs} Here we describe the design and implementation of our DL primitives that exploit the batch-reduce GEMM kernel. In particular, we outline how to implement the required algorithms for LSTM~\cite{hochreiter1997long}, CNN~\cite{szegedy2015going} and MLP~\cite{hornik1989multilayer} workloads. We choose performance-optimal data layouts which might differ from classic layout specifications in today's vendor libraries. However, this is fully acceptable as modern DL frameworks anyways change tensor layouts during their graph optimization phase for operator fusion (e.g.\ Tensorflow's Grappler). Therefore, freedom of data layout choice is a fundamental cornerstone to enable high performance through tensor compilers. We highlight that the subsequent algorithmic descriptions are agnostic of the compute precision.The only prerequisite in order to get an implementation with the desired compute precision is to generate the corresponding batch-reduce GEMM kernel. The results we present in section~\ref{sec:results} are in single precision (FP32), however we already have implementations supporting the int8 and bfloat16 datatypes (via the new Intel VNNI and bfloat16 instructions respectively) which have been shown to sufficiently cover a range of DL training and inference workloads~\cite{vanhoucke2011improving,bfloat16_tf,de2018high} and are supported on up-coming CPU architectures. Also, the same algorithms are applicable for GPUs; in Section~\ref{sec:results} we showcase exemplary results of CNNs on integrated GPUs. \subsection{Long-Short Term Memory (LSTM)} \label{subsec:lstm} \begin{figure}[t!] \centering \includegraphics[width=\columnwidth]{lstm.pdf} \caption{Long-Short Term Memory data flow.} \label{fig:lstm} \end{figure} LSTM is a type of RNN which is well-suited for processing temporal data. Unlike traditional RNN, LSTM can handle exploding and vanishing gradient problems encountered during neural network training. LSTM has found applications in language translation, text generation, handwriting recognition and image captioning. In this subsection, we focus on the forward propagation to train an LSTM cell (the forward propagation pass is utilized also for the inference use-case). The backward by data and weight update kernels required for the entire training via the back-propagation algorithm~\cite{lecun1988theoretical} are implemented in an analogous way. \subsubsection{LSTM equations and prior art} \label{subsubsec:naive_lstm} Given the batch size $N$, the sequence length $T$, the state size $C$ and hidden state size $K$, the inputs of the forward propagation pass in the training process of the LSTM cell are: i) the weight tensors $W_i$, $W_c$, $W_f$, $W_o\in {\rm I\!R}^{K\times C}$, ii) the recurrent weights $R_i$, $R_c$, $R_f$, $R_o\in {\rm I\!R}^{K\times K}$, iii) the input sequence tensor $x \in {\rm I\!R}^{T\times C\times N}$, and iv) the bias tensors $b_i$, $b_c$, $b_f$, $b_o\in {\rm I\!R}^{K}$. These tensors are combined based on the Equations~1-6 and yield the output sequence $h \in {\rm I\!R}^{T\times K\times N}$ and tensor $s \in {\rm I\!R}^{T\times K\times N}$: \begin{eqnarray} i_t &=& \sigma(W_i\cdot x_t + R_i\cdot h_{t-1} + b_i)\\ c_t &=& \textrm{tanh}(W_c\cdot x_t + R_c\cdot h_{t-1} + b_c)\\ f_t &=& \sigma(W_f\cdot x_t + R_f\cdot h_{t-1} + b_f)\\ o_t &=& \sigma(W_o\cdot x_t + R_o\cdot h_{t-1} + b_o)\\ s_t &=& f_t \circ s_{t-1} + i_t \circ c_t\\ h_t &=& o_t \circ \textrm{tanh}(s_t) \end{eqnarray} In these equations, observe the \emph{recurrent} relationship between subtensors $i_t, c_t, f_t, o_t$ and $s_t$ of the current time-step $t$ and subtensors $h_{t-1}$, $s_{t-1}$ of the previous time-step $t-1$. Also, $\sigma()$ represents the standard logistic sigmoid function, $\tanh()$ is the hyperbolic tangent function and ``$\circ$" stands for element-wise multiplication of tensors. Figure~\ref{fig:lstm} visualizes the computations and the dependencies involved in the forward propagation pass of the LSTM network. Typical implementations of the LSTM cell (e.g.\ basic LSTM cell in Tensorflow) stack the $W_i$, $W_c$, $W_f$, $W_o$ matrices into $W\in{\rm I\!R}^{4K\times C}$ and the $R_i$, $R_c$, $R_f$, $R_o$ into $R\in {\rm I\!R}^{4K\times K}$ and then employ two large GEMMS $W\cdot x_t$ and $R\cdot h_{t-1}$ to calculate the relevant partial products in Equations 1-4. Moreover, these two large GEMMs can be further replaced with a single large GEMM call by stacking $W$, $R$ and $x_t$, $h_{t-1}$ and performing: $\begin{bmatrix} W\ R \end{bmatrix}\cdot \begin{bmatrix} x_t^T\ h_{t-1}^T\end{bmatrix}^T$. Then, such an implementation applies the element-wise operations (sigmoid/tanh) onto the GEMM results and concludes with the element-wise operations dictated by Equations 5-6. While such an approach is easy to implement by exploiting large vendor-optimized GEMM library calls, the data reuse of the underlying tensors relies on how GEMMs are parallelized and may be suboptimal for GEMM sizes stemming from small batch size $N$. Also, the element-wise operations are exposed as a bandwidth-bound kernel after the GEMM which is typically a compute-bound kernel; the outputs of the large GEMM are not hot in cache (due to limited cache capacity) and as such the involved tensors have to be re-read from memory for the element-wise operations. \begin{algorithm}[t] \begin{algorithmic}[1] \Statex \algbackskip \textbf{Inputs}: Weight tensors $W_*[K_b][C_b][b_c][b_k], R_*[K_b][K_b][b_k][b_k]$ \Statex \algbackskip Input sequence $x[T][N][C]$, Bias $b_*[K]$, blocking factors $b_k, b_c, b_n$ \Statex \algbackskip \textbf{Outputs}: Output sequence $h[T][N][K]$ and $s[T][N][K]$ \State $N_b \leftarrow N/b_n$ \State Based on $thread\_id$ calculate $K_b\_start$, $K_b\_end$, $N_b\_start$ and $N_b\_end$ to assign output work items \For{$t=0 \dots T-1$} \For{$ib_k=K_b\_start \dots K_b\_end$} \For{$ib_n=N_b\_start \dots N_b\_end$} \LineComment{Compute a block of $i_t = \sigma(W_i\cdot x_t + R_i\cdot h_{t-1} + b_i)$} \State $i_k \leftarrow ib_k \cdot b_k$\ ,\ $i_n \leftarrow ib_n \cdot b_n$ \State $i[t][i_n][i_k]\leftarrow b_i[i_k]$ \For{$ib_c=0 \dots C_b-1$} \State $A_{ptrs}[ib_c] = \&W_i[ib_k][ib_c][0][0]$ \State $B_{ptrs}[ib_c] = \&x[t][i_n][ib_c\cdot b_c]$ \EndFor \State $\mathbf{batchreduce\_gemm}(A_{ptrs}, B_{ptrs}, \&i[t][i_n][i_k], C_b)$ \For{$ib_c=0 \dots K_b-1$} \State $A_{ptrs}[ib_c] = \&R_i[ib_k][ib_c][0][0]$ \State $B_{ptrs}[ib_c] = \&h[t-1][i_n][ib_c\cdot b_k]$ \EndFor \State $\mathbf{batchreduce\_gemm}(A_{ptrs}, B_{ptrs}, \&i[t][i_n][i_k], K_b)$ \State $i[t][i_n][i_k] \leftarrow \sigma(i[t][i_n][i_k])$ \LineComment{Ditto for blocks of $c_t, f_t,o_t$ via Equations 2-4} \State $s[t][i_n][i_k] \leftarrow f[t][i_n][i_k] \circ s[t-1][i_n][i_k] +$ \State \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ $i[t][i_n][i_k] \circ c[t][i_n][i_k]$ \State {$h[t][i_n][i_k] \leftarrow o[t][i_n][i_k] \circ \tanh{(s[t][i_n][i_k])}$} \EndFor \EndFor \EndFor \end{algorithmic} \caption{Forward propagation pass of LSTM cell} \label{alg:lstm} \end{algorithm} \subsubsection{Optimized LSTM cell via the batch-reduce GEMM kernel} \label{subsubsec:lstm_opt} In order to ameliorate the inefficiencies of the large GEMM approach, we follow a \emph{data flow} methodology for our optimized LSTM cell, an approach which has been also explored in previous work~\cite{lstmdataflow}. More specifically, we implement a parallel blocked matrix GEMM in order to achieve load balance, maximize weight matrix reuse and fuse the element-wise operations after partial GEMM blocks are computed and while they are still hot in cache. Algorithm~\ref{alg:lstm} shows our data-flow implementation. In particular, the output and the intermediate GEMM results/tensors are divided into logical $b_n\times b_k$ blocks which constitute the work items. Then these work items are assigned onto the available threads (line 2) and subsequently each thread proceeds with its assigned computations. Lines 6-17 indicate how such a $b_n\times b_k$ block of $i_t$ is calculated by a specific thread. First (line 8), the corresponding $i_t$ block is initialized with the according bias tensor values from $b_i$. Then, lines 9-12 employ the batch-reduce GEMM kernel described in Section~\ref{sec:br_gemm} and calculate the contribution $W_i\cdot x_t$ to the current block of $i_t$. More specifically, lines 9-11 prepare the arguments of the batch-reduce GEMM call by calculating the pointers of the required $W_i$ and $x_t$ sub-blocks and storing them in auxiliary arrays $A_{ptrs}$ and $B_{ptrs}$. Then, line 12 calls the batch-reduce GEMM kernel which accumulates the partial products from the $W_i$ and $x_t$ sub-blocks onto the current $i_t$ block. We emphasize here that our batch-reduce GEMM allows small blocking values $b_n$ and $b_k$ to be used since: (a) the small GEMM microkernel runs close to peak even for small dimensions and (b) it avoids the redundant load/stores of the accumulators that arise from the batch-reduce operation and would cripple the overall performance; instead it keeps the accumulation chain in-registers for as long as possible (see Algorithm~\ref{alg:br_kernel}). In an analogous way, lines 13-16 calculate the contribution $R_i\cdot h_{t-1}$ to the current block of $i_t$ as shown in Equation 1. Subsequently, line 17 applies the element-wise operation (sigmoid in this case) onto the just-computed block of $i_t$. Since the block of $i_t$ is hot in cache, the application of the element-wise operation does not incur any data movement from memory. The same technique is used to calculate the corresponding sub-blocks of $c_t$, $f_t$ and $o_t$ (omitted in Algorithm~\ref{alg:lstm} for simplicity). It is noteworthy that the $c_t$, $f_t$ and $o_t$ computations reuse the same entries of $x_t$ and $h_{t-1}$ from cache since these tensor entries were also used for the computation of $i_t$. Finally, lines 19-21 conclude the computation of the corresponding blocks of the output tensors $h_t$ and $s_t$ based on the element-wise operations dictated by Equations 5-6. After all the work items assigned to the available threads for a given time-step are fully computed, all the threads synchronize and proceed to the next time-step (loop at line 3). Such a synchronization is necessitated because all the output entries $h_t$ of the current time-step are required in the next time-step iteration. We also note here that the way the work items are processed by the threads affects the data reuse of the weight tensors $W_*$ and $R_*$. In particular, since work items are processed by iterating the ``mini batch" dimension first (loop at line 5), the corresponding slices of the weight tensors $W_*$ and $R_*$ are reused $N_b\_end-N_b\_start-1$ times from cache (potentially from mid-level cache). Another optimization that is not shown in Algorithm~\ref{alg:lstm} for simplicity is further cache blocking of the batch-reduce loops at lines 9 and 13. In particular, if the weight tensors at hand have large state sizes $C$ and $K$, we block these dimensions in order to fit the corresponding weight tensors slices in cache. In such a case, the algorithm would have yet another loop just after the time-step loop (at line 3) which blocks the batch-reduce loops at lines 9 and 13. Last but not least, Algorithm~\ref{alg:lstm} carefully chooses the layouts of the corresponding tensors. The weight tensors $W_*$ and $R_*$ are conceptually 2 dimensional tensors, whereas our implementation employs a blocked layout (with $C_b=C/b_c$ and $K_b=K/b_k$) : \begin{eqnarray*} W_*[C][K] \rightarrow W_*[K_b][C_b][b_c][b_k],\ R_*[K][K] \rightarrow R_*[K_b][K_b][b_k][b_k] \end{eqnarray*} Such a blocked layout exposes better locality (i.e.\ the corresponding accesses of weight sub-blocks are \emph{non-strided} with such a layout) and more importantly avoids cumbersome conflict cache misses. Typically the $C$ and $K$ values are large powers of 2 resulting in strided accesses (in the case of the non-blocked format) which are known to cause conflict misses in contemporary associative cache designs. However, our blocked format bypasses this issue by laying out the weight tensors in a format allowing non-strided accesses in the GEMM microkernel. In regard to the activation tensors, we keep the original non-blocked three dimensional format $x[T][N][C]$, $h[T][N][K]$ and $s[T][N][K]$ since strided accesses are barely an issue for the ``B" matrix in the GEMM microkernel (we also confirmed this by experimenting with a blocked format for the activation tensors). Note that even though our LSTM cell internally uses a blocked layout for the weight tensors, this does not need to be exposed at the application level; instead, we can transform the weight tensors into the desired blocked layout in the beginning of the algorithm and such a transformation overhead is amortized among the multiple time-steps in the LSTM cell. Finally, we would like to briefly discuss the importance of a \emph{single}, architecture-specific optimized kernel. All the functionalities in the LSTM cell (forward propagation/backward by data/weight update pass) utilize as building block just our batch-reduce GEMM kernel. The development/parallelization/optimization of the LSTM cell then merely degenerates to tuning/calibrating the surrounding loops around this microkernel -- a process which can be automated to some extent or even implemented in different programming frameworks/tensor compilers like TVM~\cite{chen2018tvm} or PlaidML~\cite{plaidml}. \label{sec:cnn} \begin{figure}[t!] \centering \includegraphics[width=\columnwidth]{cnn.pdf} \caption{Convolution Neural Network (CNN) tensors} \label{fig:cnn} \end{figure} \subsection{Convolution Neural Networks (CNN)} Convolutional Neural networks (CNN) consist of layers with multiple neurons connected by weights, and have found applications in image recognition, semantic segmentation, autonomous driving and medical imaging. Similar to the LSTM cell, our CNN primitives implement all the kernels required for training via back-propagation. In this section, we describe only the forward propagation kernels which are used as-is for inference. The implementation of backward by data and gradient update kernels follows the same design principles as the forward propagation. \subsubsection{Direct convolution loops and prior art} The values assigned to a neuron are usually called activations. Both activations and weights are represented with multidimensional tensors as illustrated in Figure~\ref{fig:cnn}. The input activation tensors are convoluted with the weight tensors to yield the output activation tensors. The activation tensors conceptually consist of 4 dimensions: the minibatch size $N$, the number of feature maps $C$ and the spatial dimensions $H$ and $W$. We denote the input tensor dimensions with $N$, $C$, $H$ and $W$ while the corresponding output tensor dimensions are $N$, $K$ (output feature maps), $P$ and $Q$ (output spatial dimensions). The weight tensor is conceptually characterized also by 4 dimensions: the feature map dimensions $C$, $K$ and the spatial dimensions $R$ and $S$. \begin{algorithm}[t!] \algrenewcommand\algorithmicindent{0.60em}% \begin{algorithmic}[1] \State $C_b = C/b_c,\ K_b = K/b_k,\ Q_b = Q/b_q$ \For{$n=0 \dots N-1$} \For{$k_b=0 \dots K_b-1$} \For{$c_b=0 \dots C_b-1$} \For{$oj=0 \dots P-1$} \For{$oib=0 \dots Q_b-1$} \State $oi = oib\cdot b_q,\ ii = str\cdot oi,\ ij = str\cdot oj $ \For{$r=0 \dots R-1$} \For{$s=0 \dots S-1$} \LineComment{Small GEMM loops} \For{$k^\prime=0 \dots b_k-1$} \For{$oi^\prime=0 \dots b_q-1$} \For{$c^\prime=0 \dots b_c-1$} \State $oi^{\prime\prime}=oi+oi^\prime$ \State $ij^\prime = ij + r,\ ii^\prime=ii+str\cdot oi^\prime+s$ \State $\scriptsize{O[n][k_b][oj][oi^{\prime\prime}][k^\prime]\mathrel{+}=}$ \State $\scriptsize{W[k_b][c_b][r][s][c^\prime][k^\prime]\cdot I[n][c_b][ij^\prime][ii^\prime][c^\prime]}$ \EndFor \EndFor \EndFor \EndFor \EndFor \EndFor \EndFor \EndFor \EndFor \EndFor \end{algorithmic} \caption{CNN forward propagation loops} \label{alg:cnn_basic} \end{algorithm} Algorithm~\ref{alg:cnn_basic} shows a basic implementation of the forward propagation loops where the feature map loops (lines 3 and 4) are blocked by factors $b_k$ and $b_c$ respectively and the $Q$ loop (output tensor pixel dimension) is blocked by a factor $b_q$. The input tensor pixels can be also accessed in a strided fashion via a stride $str$. Additionally, the tensors employ a blocked layout format which has been shown to exhibit better locality properties for direct convolutions~\cite{sc18}: \begin{eqnarray*} Input\ tensor: & &I[N][C_b][H][W][b_c]\\ Weight\ tensor:& &W[K_b][C_b][R][S][b_c][b_k]\\ Output\ tensor: & &O[N][K_b][P][Q][b_k] \end{eqnarray*} By adopting such a blocked layout and given the loop ordering of Algorithm~\ref{alg:cnn_basic}, the three innermost loops (lines 11-17) form a small GEMM of a $b_k\times b_c$ weight sub-tensor with a $b_c\times b_q$ input sub-tensor yielding a $b_k\times b_q$ output subtensor (note that the leading dimension of the input sub-tensor is $str\cdot b_c$). The authors of previous work~\cite{sc18} identified this property; however, they implemented a specialized convolution kernel because: \begin{itemize} \item they optimize load/store of the output $O$ in case of $R, S > 1$ and in case the input feature map loop (line 4) is reordered as the innermost loop in order to maximize output reuse. \item they apply additional pixel blocking when $Q = b_q$ and this value is smaller than the FMA latency of the architecture at hand. \end{itemize} In the following subsection, we describe how we address these issues with our new batch-reduce GEMM kernel. \subsubsection{Optimized convolutions via the batch-reduce GEMM kernel} \label{subsubsec:cnn_opt} \begin{algorithm}[t] \begin{algorithmic}[1] \State $C_b = C/b_c,\ K_b = K/b_k,\ Q_b = Q/b_q$ \For{$n=0 \dots N-1$} \For{$k_b=0 \dots K_b-1$} \For{$c_b=0 \dots C_b-1\ \textbf{with\ step}\ B_c $} \For{$oj=0 \dots P-1$} \For{$oib=0 \dots Q_b-1$} \State $oi = oib\cdot b_q,\ ii = str\cdot oi,\ ij = str\cdot oj,\ i = 0$ \LineComment{Prepare batch-reduce GEMM arguments} \For{$r=0 \dots R-1$} \For{$s=0 \dots S-1$} \For{$c=0 \dots B_c-1$} \State $A_{ptrs}[i] = \&W[k_b][c_b+c][r][s][0][0]$ \State $B_{ptrs}[i\scriptsize{++}] = \& I[n][c_b+c][ij+r][ii+s][0]$ \EndFor \EndFor \EndFor \State $Out = \&O[n][k_b][oj][oi][0]$ \State $\mathbf{batchreduce\_gemm}(A_{ptrs}, B_{ptrs}, Out, R\cdot S\cdot B_c)$ \EndFor \EndFor \EndFor \EndFor \EndFor \end{algorithmic} \caption{CNN forward pass via batch-reduce GEMM} \label{alg:cnn_br_gemm} \end{algorithm} The introduction of the batch-reduce GEMM kernel obviates the need for a specialized convolution kernel. More specifically, the batch-reduce GEMM kernel inherently optimizes load/store of the output $O$ in case of $R, S > 1$ and in case the input feature map loop is reordered as the innermost loop. By properly selecting the sub-tensors of weights/inputs to be multiplied and reduced onto an $O$ sub-tensor, the accumulation takes place entirely in registers as described in Section~\ref{sec:br_gemm}. In order to tackle the second issue regarding the case with $Q = b_q$ and $b_q$ being smaller than the FMA latency, we make the following observation: the small GEMM microkernel utilizes $b_q\times (b_k/VLEN)$ accumulator registers where $VLEN$ is the vector length of the architecture at hand. Therefore, if $b_q$ is small then we accordingly increase $b_k$ such that $b_q\times (b_k/VLEN)$ is larger than the FMA latency. Algorithm~\ref{alg:cnn_br_gemm} shows how to implement the convolution loops using our new batch-reduce GEMM kernel. Note that the input feature map loop (line 4) is blocked by a factor $B_c$ and these $B_c$ iterations are brought into the batch-reduce call in order to further increase the output register reuse. The loops at lines 9-11 prepare the arguments of the batch-reduce GEMM call by calculating the pointers to the weight and input sub-tensors that need to be multiplied and reduced onto a sub-tensor in $O$. In this way, we optimize the output sub-tensor $O$ register reuse: without the batch-reduce kernel we would have to load/store the output registers $(R\times S\times B_c)-1$ additional times. Another optimization involves the case of convolutions with $R=S=1$ and unit stride (i.e.\ $str=1$). In such a case, the input spatial dimensions (loops 5 and 6) are accessed sequentially and as such one can consider that the spatial dimensions are collapsing into a single dimension allowing even more aggressive blocking parameter values $b_q$. In regard to the parallelization of Algorithm~\ref{alg:cnn_br_gemm}, we observe that the mini-batch dimension (line 2), the output feature map blocks (line 3) and the output pixels blocks (lines 5 and 6) define $N\times K_b\times P\times Q_b$ independent tasks. Typically we opt to divide work first based on the mini-batch dimension since the weight tensors could be reused by multiple threads from shared caches. If we don't have sufficient work just based on the mini-batch size, then we consider all $N\times K_b\times P\times Q_b$ tasks and they are assigned to the available threads in a block fashion. In case our convolution at hand involves large weights, it may be better to assign tasks by starting from the feature map dimension $K_b$. In this way, each thread will touch only a part of the large weight tensor which could be further blocked for a specific cache-level. We implemented all these parallelization strategies and use the most suitable one based on the convolution layer specifications and the available number of threads. Our backward by data/weight update kernels with batch-reduce GEMM leverage previous work~\cite{sc18}. The authors in~\cite{sc18} show that only slight modifications to the forward kernel are required in order to implement the back-propagation kernels, as they can be mapped through linear index transformations into the forward convolution loop nest (``dual convolutions"). The data reuse optimizations/parallelization tasks then simply translate to tuning the surrounding loops as shown in Algorithm~\ref{alg:cnn_br_gemm}. In Section~\ref{subsec:poc_cnn_results}, we show results of a proof-of-concept design where we develop CNN primitives within a tensor compiler framework via our batch-reduce GEMM kernel. We also show how the same design principles are applicable for integrated GPUs, yielding high performance convolution kernels. \subsection{Multilayer Perceptron (MLP)} \label{sec:mlp} \begin{figure}[t!] \centering \includegraphics[width=0.6\columnwidth]{mlp.pdf} \caption{A Mulitlayer Perceptron (MLP) topology} \label{fig:mlp} \end{figure} Multilayer perceptrons (MLP) comprise a class of feed-forward artificial neural networks that are widely used for classification tasks, brain modeling, time series prediction, character recognition and data compression. An MLP consists of (at least three) \emph{fully connected} layers of neurons as illustrated in Figure~\ref{fig:mlp}: the topology starts with an input layer, followed by a number of hidden layers which conclude to the output layer. Each neuron in the topology uses a non-linear activation function. For the rest of this section we consider the optimization of the \emph{fully connected} layers since they constitute the cornerstone of MLP. The fully-connected layers also lie in the heart of the modern Transformer~\cite{transformer} and BERT~\cite{bert} workloads. We dive into the details of the forward propagation algorithm of the MLP training process (also used for inference); we also implemented all the required kernels of the back-propagation training in an analogous fashion. \subsubsection{Fully Connected layers and prior art} \label{subsubsec:fc_coarse} The dashed box in Figure~\ref{fig:mlp} illustrates two fully connected layers consisting of $C$ and $K$ neurons respectively. A neuron $i$ from the first layer is connected to a neuron $j$ in the second layer with a weight $W_{ij}$. Mathematically, an input layer $x\in {\rm I\!R}^{C}$ is mapped to an output layer $y\in {\rm I\!R}^{K}$ via the relation $y=W\cdot x$, where $W\in {\rm I\!R}^{K\times C}$ is the weight tensor of the connections between the neurons. During the training process, $N$ multiple inputs ($N$ is the so-called mini-batch size) are grouped together yielding the equation $Y=W\cdot X$ with $W\in {\rm I\!R}^{K\times C}$, $X\in {\rm I\!R}^{C\times N}$ and $Y\in {\rm I\!R}^{K\times N}$. After the output tensor $Y$ is computed, a non-linear activation function $g()$ is applied on it. Observe that by increasing the mini-batch $N$, we fundamentally increase the weight tensor reuse. Typical implementations of Fully Connected layers leverage a large GEMM call and they apply the activation functions onto the GEMM outputs. Even though such an approach is straightforward to implement, its performance can be underwhelming for three reasons: i) typical high-performance GEMM library calls internally perform packing of sub-matrices to ameliorate TLB misses and cache conflict misses~\cite{goto2008anatomy}, ii) the multi-threaded implementation of GEMM with shapes arising from small mini-batch values $N$ may not fully exploit the available data reuse, and iii) in case of large matrices that do not fit in cache, the activation function application is exposed as a bandwidth-bound kernel which decays the overall performance. In the next subsection, we describe how our implementation of Fully Connected layers via the batch-reduce GEMM kernel addresses all these issues. \begin{algorithm}[t] \begin{algorithmic}[1] \Statex \algbackskip \textbf{Inputs}: Weight $W[K_b][C_b][b_c][b_k]$, Input $X[N_b][C_b][b_n][b_c]$ \Statex \algbackskip \textbf{Outputs}: Output $Y[N_b][K_b][b_n][b_k]$ \State Based on $thread\_id$ calculate $K_b\_start$, $K_b\_end$, $N_b\_start$ and $N_b\_end$ to assign output work items \For{$ib_n=N_b\_start \dots N_b\_end$} \For{$ib_k=K_b\_start \dots K_b\_end$} \LineComment{Prepare batch-reduce GEMM arguments} \For{$ib_c=0 \dots C_b-1$} \State $A_{ptrs}[ib_c] = \&W[ib_k][ib_c][0][0]$ \State $B_{ptrs}[ib_c] = \&X[ib_n][ib_c][0][0]$ \EndFor \State $Out = \&Y[ib_n][ib_k][0][0]$ \State $\mathbf{batchreduce\_gemm}(A_{ptrs}, B_{ptrs}, Out, C_b)$ \State $Y[ib_n][ib_k][0][0] \leftarrow g(Y[ib_n][ib_k][0][0])$ \EndFor \EndFor \end{algorithmic} \caption{Forward pass of Fully Connected Layer} \label{alg:mlp} \end{algorithm} \subsubsection{Fully Connected layers via the batch-reduce GEMM kernel} \label{subsubsec:fc_opt} Algorithm~\ref{alg:mlp} shows the implementation of the forward propagation in the training process of fully connected layers. First, we highlight the blocked tensor layout; all the 2 dimensional tensors are transformed into 4 dimensional ones by blocking the mini-batch dimension $N$ with a factor $b_n$ and the tensor dimensions $C$ and $K$ with blocking factors $b_c$ and $b_k$ respectively. Such a blocked layout addresses issue (i) mentioned in the previous subsection by exposing better locality and avoiding large, strided sub-tensor accesses which are known to cause TLB misses and cache conflict misses in case the leading dimensions are large powers of 2. Our algorithm first assigns the output sub-tensor blocks to the available threads (line 1) and every thread then for each assigned output $Y$ block calculates the addresses of the $W$ and $X$ sub-tensor blocks that need to be multiplied and reduced onto the current output $Y$ block (lines 5-7). Note that our JIT-ed kernel allows small values of blocking values $b_n$ to be used, and as such we can extract parallelism from the mini-batch dimension even for small values of $N$. By following the loop ordering of Algorithm~\ref{alg:mlp}, a weight sub-tensor is reused by each thread $N_b\_end-N_b\_start-1$ times, potentially from some level of cache. Also, multiple threads are able to read weights from shared caches when the assigned $Y$ blocks correspond to the same subspace of the $K$ dimension. Finally, in case a weight sub-tensor does not fit in the targeted/desired level of cache, we can further block loops at lines 3 and 5. These cache blocking techniques in combination with the flexible blocking factors $b_n$, $b_c$ and $b_k$ which yield high performance micro-kernels, address the data reuse issue (ii) mentioned in the previous subsection. Finally, once the arguments of the batch-reduce GEMM have been calculated, we perform the batch-reduce GEMM call (line 9) and while the output sub-tensor block $Y$ is still hot in cache we apply on it the relevant activation function (line 10). In this way, we ensure that the application of the activation function takes place when the data are still hot in cache and it does not incur any additional data movement from memory, addressing issue (iii) from the previous subsection. Once again, the development of the Fully Connected primitive follows the same recipe as the LSTM and CNN primitives. Therefore, the loops surrounding the batch-reduce GEMM kernel can be automatically optimized with a tensor compiler/infrastructure. \begin{figure*}[t!] \centering \includegraphics[width=2.0\columnwidth]{lstm_perf.pdf} \caption{Performance of LSTM cell: (Left) Forward propagation and (Right) backward by data and weight update pass.} \label{fig:lstm_cell} \end{figure*} \section{Performance results} \label{sec:results} In subsection~\ref{subsec:dl_perf}, we evaluate the performance of our DL kernels. Then, in subsection~\ref{subsec:distr_training}, we present distributed memory results on two state of the art workloads, namely Google's Neural Machine Translation (GNMT) which corresponds to LSTM training and ResNet-50 which is representative of CNN training. Finally, in subsection~\ref{subsec:poc_cnn_results}, we show a couple of proof-of-concept results that highlight the generalizability of our approach. More specifically, we show CNN kernel results on integrated GPUs and conclude with CNN kernel results that are generated by TVM, both leveraging batch-reduce GEMM kernel as their basic building block. \subsection{Performance evaluation of our DL kernels} \label{subsec:dl_perf} Since we use a JIT-ing methodology for the batch-reduce GEMM kernel, we can virtually run on every platform supporting SSE, AVX, AVX2 and AVX-512 instructions. All the experiments presented in this subsection are conducted on a Skylake-SP (SKX) 8180 processor with 28 cores, 96 GB\,DDR4 2666 main memory at 2.3\,GHz (AVX512) Turbo at 205W TDP. The stream triad of a single socket is 105\,GB/s. For the experiments we used all 28 cores with turbo disabled (i.e.\ AVX-512 base frequency at 1.7\,GHz) in order to get stable measurements. With such a setup, the peak of the machine is $\sim$3,050 GFLOPS (single precision). All the experiments were performed 400 times and we report the average timing; due to careful configuration of our platform (i.e.\ tick-less Linux kernel, core pinning, turbo disabled) the run-to-run variation is within 3\%. For our work we used the Intel compilers (version 18.0.0). For performance comparisons, we used the latest version of MKL-DNN (version 0.9) \subsubsection{Performance evaluation of LSTM cell} \begin{table}[!tb] \fontsize{8}{8}\selectfont \centering \begin{tabular}{|c|c|c|c|c|c|c|} \hline & \multicolumn{2}{c|}{{\textbf{batch-reduce GEMM }}} & \multicolumn{1}{c|}{{\textbf{Elementwise }}} & \multicolumn{1}{c|}{{\textbf{Tensor }}} \\ {\textbf{LSTM pass}} & \textbf{\% of total} & \textbf{GFLOPS} & \textbf{operations} & \textbf{reformatting }\\ \hline \hline \textbf{fwd} & 93.3\% & 2550 & 5.3\% & 1.4\% \\ \hline \textbf{bwd \& upd} & 91.2\% & 2350 & 5.3\% & 3.5\% \\ \hline \end{tabular} \caption{\label{tab:lstm_breakdown}Breakdown of LSTM cell performance ($\mathbf{C}$=$\mathbf{K}$=1024).} \end{table} Figure~\ref{fig:lstm_cell}~(Left) illustrates the performance of the forward propagation algorithm in the LSTM cell that is described in subsection~\ref{subsec:lstm}. In this experiment, we fix $N=168$ (mini-batch), $T=50$ (sequence length), and we vary the hidden state size $K$ which is equal to the input state size (i.e.\ $C=K$). The blue bars represent the performance in GFLOPS (see Left y-axis) of our kernels. We observe that even in the case of small $C$ and $K$, our LSTM cell runs at $\sim$60\% of peak (see Right y-axis), whereas for larger weight tensors the activation-tensor reuse is larger and consequently the kernels run at $\sim$70\% of peak. In Table~\ref{tab:lstm_breakdown} (row labeled ``fwd'') we provide more details regarding how the time is spent within the LSTM cell for the case with $C=K=1024$. During the forward pass, 93.3\% of the time is spent in the batch-reduce GEMM kernel which runs at 2550 GFLOPS or equivalently at 84\% of peak. Then, 5.3\% of the execution time is spent for the elementwise operations described in subsection~\ref{subsubsec:lstm_opt}. The rest 1.4\% is spent in reformatting the weight tensors to take advantage of the blocked format (see subsection~\ref{subsubsec:lstm_opt}). Figure~\ref{fig:lstm_cell}~(Right) exhibits the performance of the remaining two passes in the LSTM training process, namely backward propagation and weight update pass (henceforth called ``bwd'' and ``upd'' respectively). The performance follows the same trend as the forward propagation, i.e.\ with larger weight tensors, the overall efficiency is closer to peak due to more re-use of the activation tensors. Notably, the overall efficiency is diminished compared to the forward propagation; by inspecting the time breakdown at Table~\ref{tab:lstm_breakdown} (row labeled ``bwd \& upd'') we observe that larger fraction of the overall time is spent in tensor reformatting. This is expected because bwd and upd passes require algorithmically additional weight and activation tensor transposes~\cite{lecun1988theoretical}. Also, the batch-reduce GEMM runs at 2350 GFLOPS or equivalently at 77\% of peak, which is a bit lower than the efficiency of the one achieved in the forward pass. This is a result of different tensor shapes in the ``upd'' pass, where the reduction dimension of GEMM becomes the mini-batch dimension and typically it is smaller than $C$/$K$ which constitute the GEMM reduction dimensions in forward pass. In Figure~\ref{fig:lstm_cell}, we also provide performance comparison of our LSTM cell with the vendor-optimized LSTM cell within MKL-DNN (orange bars). For small to medium problem sizes, our LSTM cell is faster than the MKL-DNN cell in the range of $1.2$-$1.3\times$ for forward propagation and $1.1$-$1.7\times$ for the bwd/upd pass. This is a result of the adopted ``data-flow'' approach described in subsection~\ref{subsec:lstm} that leverages our batch-reduce GEMM kernel: the elementwise operations are naturally fused within the GEMM operations which run at high efficiency. For larger problem sizes, the overall cost of the GEMM operation dominates the entire computation and as such the elementwise operations are negligible. This is expected since the GEMM computation cost scales cubically compared to the quadratic scaling of the elmentwise operations. Therefore, for large problem sizes a coarse grained approach like the one described in subsection~\ref{subsubsec:naive_lstm} yields good performance. It is worth mentioning that in the following subsection~\ref{subsec:distr_training} where we present distributed memory GNMT training results, the involved LSTM corresponds to the case with $C$=$K$=1024 in Figure~\ref{fig:lstm_cell}, where our code is $1.26\times$ faster than MKL-DNN for all training passes (for $N$=168). \subsubsection{Performance evaluation of CNN kernels} \begin{figure*}[t!] \centering \includegraphics[width=2.0\columnwidth]{cnn_fwd_bwd_new.pdf} \caption{Performance of ResNet-50 convolutions: (Left) Forward propagation and (Right) backward by data pass.} \label{fig:cnn_fwdbwd} \end{figure*} \begin{figure}[t!] \centering \includegraphics[width=\columnwidth]{cnn_upd_perf.pdf} \caption{Performance of ResNet-50 weight update pass.} \label{fig:cnn_upd} \end{figure} \begin{table} \fontsize{6}{5}\selectfont \begin{tabularx}{\columnwidth}{|X| l | l |X|X|X|X| X || X| l | l |X|X|X|X| X |} \hline ID & C & K & H & W & R & S & str & ID & C & K & H & W & R & S & str \\ \hline \hline 1 & 3 & 64 & \fontsize{6}{4}\selectfont 224 &\fontsize{6}{4}\selectfont 224 & 7 & 7 & 2 & 11 & 512 & 1024 & 28 & 28 & 1 & 1 & 2 \\ \hline 2 & 64 & 256 & 56 & 56 & 1 & 1 & 1 & 12 & 512 & 256 & 28 & 28 & 1 & 1 & 2 \\ \hline 3 & 64 & 64 & 56 & 56 & 1 & 1 & 1 & 13 & 256 & 256 & 14 & 14 & 3 & 3 & 1 \\ \hline 4 & 64 & 64 & 56 & 56 & 3 & 3 & 1 & 14 & 256 & 1024 & 14 & 14 & 1 & 1 & 1 \\ \hline 5 & 256 & 64 & 56 & 56 & 1 & 1 & 1 & 15 & 1024 & 256 & 14 & 14 & 1 & 1 & 1 \\ \hline 6 & 256 & 512 & 56 & 56 & 1 & 1 & 2 & 16 & 1024 & 2048 & 14 & 14 & 1 & 1 & 2 \\ \hline 7 & 256 & 128 & 56 & 56 & 1 & 1 & 2 & 17 & 1024 & 512 & 14 & 14 & 1 & 1 & 2 \\ \hline 8 & 128 & 128 & 28 & 28 & 3 & 3 & 1 & 18 & 512 & 512 & 7 & 7 & 3 & 3 & 1 \\ \hline 9 & 128 & 512 & 28 & 28 & 1 & 1 & 1 & 19 & 512 & 2048 & 7 & 7 & 1 & 1 & 1 \\ \hline 10 & 512 & 128 & 28 & 28 & 1 & 1 & 1 & 20 & 2048 & 512 & 7 & 7 & 1 & 1 & 1 \\ \hline \end{tabularx} \caption{ResNet-50 layers specifications} \label{tab:resnet_layers} \end{table} We conducted experiments with the ResNet-50 topology which yields state of the art results in image recognition tasks~\cite{he2016deep}. The convolution layers within the ResNet-50 topology cover a wide variety of parameters/configurations (e.g.\ filter dimensionality and sizes, input sizes, strided convolutions) and can be seen at Table~\ref{tab:resnet_layers}. In this Table we assign to each convolution layer an ID that is used as identifier in the performance plots. Also, for the remaining of this paper we will use the term \emph{weighted efficiency} when presenting ResNet-50 results; each layer $i$ of Table~\ref{tab:resnet_layers} requires $F_i$ flops, takes $t_i$ seconds to be computed, and is represented $n_i$ times in the entire topology (which has 53 layers in total). The weighted efficiency of the entire topology is given by: $(\sum_{i=0}^{52}n_i\cdot F_i)/(\sum_{i=0}^{52}n_i\cdot t_i)$. Figures~\ref{fig:cnn_fwdbwd} and ~\ref{fig:cnn_upd} show the performance of the ResNet-50 convolutions with mini-batch size $N=28$. The blue bars in Figure~\ref{fig:cnn_fwdbwd} (Left) represent the achieved performance (in GFLOPS) of the forward (FWD) propagation algorithm described in subsection~\ref{subsubsec:cnn_opt} that leverages the batch-reduce GEMM kernel. The weighted efficiency of the FWD convolutions within the ResNet-50 topology is 83\% of peak. More specifically, the convolutions with large spatial filters (e.g.\ $R$=$S$=$3$ in convolutions with IDs 4, 8, 13, 18) run at $\sim$90\% of peak since they inherently have more input and output tensor reuse than the convolutions with $R$=$S$=$1$ which run at $\sim$80\% of peak. Notably, layer with ID 2 runs at 65\% of peak since it has large output spatial and feature map dimensions and as such its performance is bound by the write bandwidth of our system. By comparing the performance of our kernels to MKL-DNN (orange bars) we observe similar trends. The MKL-DNN library exhibits weighted efficiency of 81\% of peak for FWD convolutions and as such it is 2.5\% slower than our work. This result highlights the effectiveness of our approach with a single kernel as basic building block: our convolutions consist of just $\sim$1500 lines of code (for all training passes) whereas the convolution portion of the MKL-DNN library is $\sim$36000 lines of code since it leverages ad hoc, specialized kernels (e.g.\ ad hoc optimization of the direct convolution loops, different approaches/code generation for various $R$ and $S$ values). Figures~\ref{fig:cnn_fwdbwd} (Right) and ~\ref{fig:cnn_upd} exhibit the performance of the convolution kernels in the remaining training passes, namely backward by data (BWD) and weight update (UPD). Our kernels have weighted efficiency 80\% and 73.6\% for the BWD pass and the UPD pass respectively. Similarly to the convolutions in the FWD pass, the layers with large spatial weight dimensions show better performance than the ones with $1\times 1$ spatial dimensions since the former have better input and output tensor reuse properties. Also, we note that the efficiency of the UPD kernels is $\sim$10\% lower than the efficiency of FWD/BWD kernels. This is a consequence of the weight tensor reduction which is required in the weight update algorithm in order to maximize the input and output tensor data movement~\cite{sc18}. For comparison, the MKL-DNN BWD and UPD kernels illustrate weighted efficiencies of 78.9\% and 68.9\% respectively, and are 1\% and 7\% slower than our kernels. In subsection~\ref{subsec:distr_training} we integrate our kernels in the GxM distributed framework and improve the best in class performance of ResNet-50 training on CPUs. \subsubsection{Performance evaluation of Fully Connected Layers} \begin{figure*}[t!] \centering \includegraphics[width=2.0\columnwidth]{mlp_perf.pdf} \caption{Performance of Fully Connected Layers. Bars correspond to Left y-axis / efficiency corresponds to Right y-axis.} \label{fig:mlp_perf} \end{figure*} Figure~\ref{fig:mlp_perf} shows the performance of the Fully Connected layers which are the cornerstone of the MLP workload. In these experiments we fix the mini-batch size $N$=1344 and we vary the dimensions of the weight tensors. For each configuration, we show results for the forward propagation (FWD), backward by data pass (BWD) and weight update pass (UPD). We observe that our approach (blue bars) with the fine-grained batch-reduce GEMM kernel shows for the smaller configuration ($C$=$K$=256) efficiencies in the range 57\%-73\%, for the medium weight sizes ($C$=$K$=512) 55\%-94\% and for the larger configuration ($C$=$K$=1024) the efficiencies are 67\%-82\%. In all configurations, we observe that the BWD kernels's performance deteriorates compared to the equivalent FWD kernels. This is the case because the BWD kernels require a weight transpose~\cite{lecun1988theoretical}. The overhead of this weight transpose is more emphasized in the cases with small $C$/$K$ values while for the cases with large $C$/$K$ values the cost of the GEMM kernel dominates the overall runtime and as such the transpose cost in negligible (see case with $C$=$K$=1024). In regard to the UPD kernels, we also observe that for smaller weight tensors the performance is lower than the corresponding FWD kernels. This is due to the limited parallelism that is available in such cases. More precisely, the FWD pass employs parallelism in the $N$/$K$ dimensions (see Algorithm~\ref{alg:mlp}), the BWD pass in the $N$/$C$ dimensions while the UPD pass in the $C$/$K$ dimensions. Consequently it is more challenging to extract sufficient parallelism within the configurations with small $C$/$K$ values. Moreover, Figure~\ref{fig:mlp_perf} shows the performance of the Fully Connected layers within the MKL-DNN library (orange bars). These kernels use the coarse-grained approach (i.e.\ a single large GEMM call) as described in subsection~\ref{subsubsec:fc_coarse}. Considering the average efficiencies of all MKL-DNN kernels (FWD, BWD and UPD), the smallest configuration achieves 55\% of peak, the medium configuration runs at 56\% of peak and the largest test case attains 70\% of peak. In contrast, our approach with the batch-reduce GEMM kernel achieves 64\%, 76\%, and 76\% of peak respectively and is $1.16\times$, $1.36\times$, and $1.09\times$ faster than the corresponding coarse-grained approach. \subsection{Distributed memory training results} \label{subsec:distr_training} \begin{figure*}[t!] \centering \includegraphics[width=2.0\columnwidth]{from_zero_plot.pdf} \caption{Distributed memory training results: (a) 4-Layer GNMT model (LSTM kernels), (b) ResNet-50 model (CNN kernels) } \label{fig:strong_all} \end{figure*} Our experimental platform is a 32-node cluster (Intel Omnipath interconnect), each node having two Skylake-SP (SKX) 8180 processors. For these runs, we enable the turbo mode on the processors (i.e.\ clock frequency up to 2.3\,GHz). \subsubsection{Distributed memory GNMT training results} We conducted our experiments with the 4-layer GNMT~\cite{wu2016google} model. The framework of our choice is Tensorflow (TF)~\cite{tensorflow2015}, where we replaced the Tensorflow LSTM cell implementation with our optimized LSTM cell that leverages the batch-reduce GEMM kernel. Then, we utilized Uber's Horovod library~\cite{horovod} to enable efficient multi-node runs. In order to accelerate the communication performance of Horovod, we replaced its default MPI communication backend with Intel's MLSL library~\cite{mlsl} which optimizes communication primitives arising in deep learning. Moreover, we extend the partitioning logic of the inputs by grouping sequences with similar length together in order to achieve load balance; such a technique yields up to 1.5$\times$ speedup compared to classic input partitioning. For all the experiments in this section, we use 1 MPI rank per CPU socket. As a baseline for comparisons, we used the default LSTM cell for CPUs within TF which we configured to use the MKL library to materialize efficiently the large GEMM calls. In order to assess the benefits of our new kernels, we incorporated our LSTM cell and we further modified the TF code to support fused time-step operations as they are described in Algorithm~\ref{alg:lstm}. We verified correctness of the code changes by achieving state of the art BLEU score of 22.7 after 3 epochs with the German to English WMT16 dataset~\cite{wmt16}. Figure~\ref{fig:strong_all}~(a) illustrates the strong scaling of the distributed memory training with three different batch sizes; the usage of such large batch sizes (up to $\sim$ 5K) is enabled by the LEGW~\cite{you2019large} approach. The y-axis represents the achieved training performance in Kilo Words per Second (KWPS) while the x-axis shows the number of nodes. Both axes are in logarithmic scale. For the smaller batch size ($N$=1344), our approach (solid blue line) scales from 1 to 4 nodes with 84\% strong scaling efficiency, and when we keep scaling from 4 to 16 nodes the parallel efficiency further drops down to 38\%. The main reason for this efficiency drop involves the small mini-batch per socket as we strong scale (we use pure data parallelism to scale out). As a result, we get reduced efficiency within the LSTM cell computation. For example, with $N$=1344 and at the concurrency of 1 node (2 MPI ranks), the mini-batch per socket is 672 whereas at 16 nodes (32 MPI ranks), the mini-batch per socket is 42. Nevertheless, we are able to increase the performance all the way up to 16 nodes even for such a small batch size and we achieve 35.8 KWPS. For comparison, the reference LSTM cell + TF approach (orange line) achieves 15.36 KWPS, thus the approach with our kernels is 2.33$\times$ faster. As we increase the global batch size, the strong scaling efficiency is better because the local computation does not suffer from very small mini-batch. For example, with batch size $N$=2688 our strong scaling efficiency at 16 nodes is 58\% achieving 52.5 KWPS, and is 2.77$\times$ faster than the reference LSTM cell that achieves 18.9 KWPS. With the largest batch size ($N$=5376) the strong scaling efficiency at 16 nodes is 75.2\% achieving 65.9 KWPS. For the same setup, the reference LSTM cell achieves 32.32 KWPS, thus our approach is 2.04$\times$ faster. For the last two experimental setups, we start from 2 and 4 nodes respectively since those batch sizes are too large for the available memory of a single node. To the best of our knowledge, these achieved GNMT training results are the best in class on CPU platforms. For completeness, we mention here the performance of contemporary Nvidia V100 GPU systems on the 4-layer GNMT model in Tensorflow (FP32 precision): The achieved performance is 12.7 and 83.3 KWPS on 1 and 8 GPUs respectively~\cite{v100gnmt}. The FP32 peak performance of V100 GPU is 15.7 TF/s which is $\sim$2$\times$ larger than a single CPU node, and also the available bandwidth is 900 GB/s which is 3.6$\times$ larger than the bandwidth of our node. The scaling from 1 to 8 GPUs shows similar scaling efficiency to our distributed training results. \subsubsection{Distributed memory ResNet-50 training results} For ResNet-50 training, we integrated our new CNN kernels into the GxM framework which has been shown to scale efficiently on clusters of CPUs via the MLSL library~\cite{sc18,mlsl}. We verified correctness of our experiments by converging to the same state of the art accuracies, e.g.\ 75.7\% Top-1 accuracy. For Nvidia V100 performance, we use numbers from Nvidia~\cite{v100_fp16_resnet} and previous work~\cite{xu2018deep}. Figure~\ref{fig:strong_all}~(b) summarizes the obtained performance. For the single node CPU measurements, we use 28 cores per socket and the mini-batch is 56 (dual socket nodes). Our approach (red flat line) achieves 149 images/sec and is 1.45$\times$ faster than the configuration with MKL-DNN and Tensorflow (orange flat line) which attains 103 images/sec. If we increase the mini-batch to 224, MKL-DNN improves its efficiency and is able to obtain 129 images/sec. For completeness, we mention the achieved performance of one V100 GPU which is 371 images/sec in single precision (green flat line) and 870 images/sec in mixed FP16/FP32 precision (black flat line) -- the latter approach uses the available tensor cores~\cite{markidis2018nvidia}. In order to scale out with GxM, we dedicate 2 cores per node for communication via MLSL primitives and we use 54 cores for computations. In Figure~\ref{fig:strong_all}~(b), we illustrate with solid blue line the scaling of GxM with our new CNN kernels (both axes are in logarithmic scale). We scale up to 32 nodes with 95.3\% parallel efficiency, achieving at the concurrency of 32 nodes (1,792 cores) 4432 images/sec. To the best of our knowledge, these are the best reported distributed memory training results for CPUs (in terms of efficiency). Previous work, which also uses GxM~\cite{sc18}, obtained on the same platform 1696 images/sec at the concurrency of 16 nodes, while our CNN kernels within GxM achieve 2239 images/sec, improving the end-to-end training performance by 1.32$\times$. \subsection{CNN kernels on integrated GPU and TVM} \label{subsec:poc_cnn_results} \begin{figure*}[t!] \centering \includegraphics[width=2.0\columnwidth]{updated_cldnn.pdf} \caption{CNN forward propagation: (Left) integrated GPU Gen9, (Right) implementation with batch-reduce GEMM in TVM} \label{fig:poc_cnn} \end{figure*} In order to showcase the generalizability of our approach to diverse platforms, we developed the batch-reduce GEMM kernel in OpenCL. We implemented forward propagation CNN kernels (Algorithm~\ref{alg:cnn_br_gemm}) targeting Intel's integrated GPU Gen9 (Core i7 6770HQ) ~\cite{junkins2015compute} which has peak performance of 1152 GFLOPS. Figure~\ref{fig:poc_cnn}~(Left) illustrates the performance of our kernels (blue bars) and the vendor-optimized library Intel clDNN~\cite{cldnn} (orange bars). For the clDNN experiments, we tried all the available tensor layouts and picked the one that yields the highest performance. For this experiment the mini-batch size is $N$=32. We conclude that our kernels with batch-reduce GEMM achieve similar performance to clDNN. When considering the weighted efficiency, our kernels run at 728.3 Gflops and the clDNN kernels at 753.5 Gflops, thus our approach is within 3\% of the vendor-optimized, ad hoc implementation. Once again, in this work, the specific algorithm/kernel development can be seen as loop tuning around batch-reduce GEMM, cf.\ section~\ref{sec:dl_algs}. Even though our DL kernels perform this tuning in a well-informed, manual fashion and are implemented in high-level C code, an alternative is to use a high-level tensor framework. Here we present results of such a proof-of-concept design, where we implement the forward convolutions within TVM~\cite{chen2018tvm}. More specifically, we provide to TVM the forward propagation loop recipes in high-level Python code, and at the innermost loop nest level we invoke our batch-reduce GEMM kernel. To assess the efficiency of our approach, we consider the \emph{inference} use-case of CNNs (i.e.\ only the forward propagation pass). One idiosyncrasy of inference compared to training is the very small mini-batch $N$=1 that is necessitated to meet the latency requirements of the application. Figure~\ref{fig:poc_cnn}~(Right) shows the performance of our TVM implementation (green bars) on ResNet-50 forward kernels (mini-batch $N$=1) on the SKX 8180 platform. In this plot we also show the performance of the following implementations: i) CNN kernels within AutoTVM developed by Amazon~\cite{liu2018optimizing} (yellow bars), which are \emph{auto-tuned} for inference, ii) MKL-DNN (orange bars), and iii) the CNN kernel performance of our high-level C code kernels (blue bars). First, we observe that our DL kernels are the most efficient, achieving overall weighted efficiency of 2492 GFLOPS. Our Python implementation within TVM that exploits the batch-reduce GEMM kernel runs at 2361 GFLOPS, and consequently is within 5.3\% of our C implementation. Our TVM implementation is 2\% faster than the Amazon-AutoTVM \emph{auto-tuned code} and 1.24$\times$ faster than the vendor optimized MKL-DNN library. These results show that high-performance DL kernels within high-level tensor frameworks are feasible if the proper building block is used. \section{Related Work} The status quo in the development of high-performance DL workloads entails vendor-optimized DL primitives within some high-level deep learning framework (e.g. Tensorflow~\cite{tensorflow2015}, Pytorch~\cite{paszke2017pytorch}, Caffe~\cite{jia2014caffe}). MKL-DNN~\cite{mkldnn} is the Intel optimized DL library that provides specialized primitives (e.g.\ convolutions, RNN/LSTM cell, fully connected layers) for Intel CPUs. Each one of these primitives is individually optimized at a low-level on a per-platform basis in order to maximize performance, leading to numerous, highly specialized code-bases that do not generalize to different architectures. In an analogous way, cuDNN~\cite{chetlur2014cudnn} is the vendor-optimized DL library targeting Nvidia GPUs. clDNN~\cite{cldnn} is an open source performance library for DL applications intended for acceleration of DL Inference on Intel GPUs. All these library approaches suffer from the combinatorial explosion of the low-level optimizations that have to be done for each pair <architecture, DL primitive>. On the other hand, our proposed batch-reduce GEMM kernel covers all major DL primitives and it is the sole building-block that has to be optimized at a low-level. An alternative methodology to implement DL primitives is to leverage vendor-optimized linear algebra library calls. For example, convolutions can be lowered to a matrix multiplication~\cite{chellapilla2006high}, but this lowering requires tensor transformations, and the obtained performance deteriorates~\cite{sc18,chetlur2014cudnn}. Aiming to accelerate the small matrix operations that pertain in DL, academia and industry have recently developed batched linear algebra routines ~\cite{dongarra2017design,stridedbatchgmemm,ng2017magmadnn}. The batched GEMM approaches in~\cite{stridedbatchgmemm,ng2017magmadnn} specifically target only Nvidia GPUs where the reduction across output subtensors is relatively cheap. Even though such approaches improve the performance of the DL primitives, they still perform worse than ad hoc implementations (cf.\ batched GEMM approach and mkl-dnn in Figure~\ref{fig:motivation}). Our work extends the batched GEMM routine, enables more optimizations (see Section~\ref{sec:br_gemm}), optimizes for locality and is therefore well suited for latency architectures such as CPUs. Also, the derived DL primitives match/exceed the performance of vendor-optimized ad hoc implementations as shown in Section~\ref{sec:results}. Tensor compilers comprise a promising research area for end-to-end DL workload optimization and performance portability (e.g.\ TVM~\cite{chen2018tvm}, GLOW~\cite{DBLP:journals/corr/abs-1805-00907}, PlaidML~\cite{plaidml}, MLIR~\cite{mlir}, Tensor Comprehensions~\cite{vasilache2018tensor}). Such frameworks treat tensors as first-class objects, and provide optimizations targeting tensor algebra programs (e.g.\ polyhedral optimizations for data movements). However, compilers struggle to optimize the GEMM-flavored loop nests for the nuances of the increasingly complex architectures. Our work can be seen as complementary to this effort, where the GEMM-flavored loops are abstracted into our batch-reduce GEMM call (which is independently optimized at a low-level). Then, the specific DL primitive optimization is reduced to mere loop tuning around a single kernel, and this task can be handed off to a tensor compiler. In Section~\ref{sec:results} we showcased a prototype for CNNs within TVM that uses our kernel. \section{Conclusions} In this work, we showed how the most popular DL algorithms (RNN/LSTM, CNN and MLP) can be formulated with batch-reduce GEMM as basic building block. We demonstrated that our methodology outperforms vendor-optimized, low-level DL primitives by factors up to 1.4$\times$. Moreover, we integrated our DL kernels into distributed frameworks, and optimized end-to-end workflows for GNMT and ResNet-50 training. In multi-node experiments we exceeded the performance of vendor-optimized implementations by up to 2.3$\times$. Additionally, we highlighted the architectural-agnostic aspect of our methodology by matching the CNN kernel performance of a vendor-provided library on integrated GPUs. Finally, we prototyped CNN kernels in a tensor compiler framework by harnessing our batch-reduce GEMM kernel, and matched the performance of \emph{auto-tuned} inference TVM primitives. As future work, we plan to extend our DL primitives for a wider set of architectures/workloads, and also we intend to experiment with Tensor compilers' automatic polyhedral optimization (e.g.~\cite{plaidml, poly}). \FloatBarrier \bibliographystyle{unsrt}
{'timestamp': '2019-06-19T02:08:25', 'yymm': '1906', 'arxiv_id': '1906.06440', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06440'}
arxiv
\section{Introduction} The subregular program in phonology seeks to define subclasses of the regular languages and finite-state functions that describe attested phonotactic constraints and phonological processes. These subclasses provide a natural framework for typological classification of linguistic phenomena while allowing for the development of precise theories of language learning and processing. The traditional view in subregular phonology is that most phonotactic dependencies are described by \textit{tier-based strictly local} languages (TSL, \citealp{heinzTierbasedStrictlyLocal2011,mcmullinLongDistancePhonotacticsTierBased2016,mcmullinTierBasedLocalityLongDistance2016}), while most phonological process are described by \textit{strictly local} functions \citep{chandleeStrictlyLocalPhonological2014,chandleeOutputStrictlyLocal2015,chandleeInputOutputStrictlyInprep}. These classes of languages and functions are defined by a principle known as \textit{locality}---that dependencies between symbols must occur over a bounded distance within the string. To account for longer-distance dependencies, \citet{heinzTierbasedStrictlyLocal2011} proposes a \textit{tier projection} mechanism that allows irrelevant intervening symbols to be exempt from the locality condition. Recent work in subregular phonology has identified a number of exceptions to the traditional view. On the language side, unbounded culminative stress systems \citep{baekComputationalRepresentationUnbounded2018}, Uyghur backness harmony \citep{mayerChallengeTierBasedStrict2018}, and Sanskrit n-retroflexion \citep{grafSanskritNRetroflexionInputOutput2018} have been shown to lie outside the class of TSL languages. These observations have led to an enhancement of \citeauthor{heinzTierbasedStrictlyLocal2011}'s (\citeyear{heinzTierbasedStrictlyLocal2011}) tier projection system. On the function side, a number of processes, including bidirectional harmony systems \citep{heinzVowelHarmonySubsequentiality2013} and certain tonal processes \citep{jardineComputationallyToneDifferent2016}, have been shown to be not subsequential, and therefore not strictly local. At least two proposals, both known as the \textit{weakly deterministic} functions, have been made in order to capture these processes \citep{heinzVowelHarmonySubsequentiality2013,mccollumExpressivitySegmentalPhonology2018}. This paper identifies \textit{rhythmic syncope} as an additional example of a phonological process that is not strictly local. In rhythmic syncope, every second vowel of an underlying form is deleted in the surface form, starting with either the first or the second vowel. While rhythmic syncope cannot be expressed as a local dependency between symbols, it can be viewed as a local dependency between \textit{actions} in the computation history of the minimal subsequential finite-state transducer (SFST). We formalize such dependencies by proposing the \textit{tier-based synchronized strictly local} functions (TSSL). See \citet{bowersHaoInformalSSLToAppear} for a discussion of TSSL functions oriented towards the phonological literature. This paper is structured as follows. Section \ref{sec:sec2} enumerates standard definitions and notation used throughout the paper, while Section \ref{sec:sec3} reviews existing work on strictly local functions. Section \ref{sec:sec4} introduces rhythmic syncope and shows that it is not strictly local. Section \ref{sec:sec5} presents two equivalent definitions of the TSSL functions---an algebraic definition and a definition in terms of a canonical SFST. Section \ref{sec:sec6} develops some formal properties of the TSSL functions, showing that they are incomparable to the full class strictly local functions. Section \ref{sec:sec7} compares our proposal to existing OT treatments of rhythmic syncope, and Section \ref{sec:sec8} concludes. \section{Preliminaries} \label{sec:sec2} As usual, $\mathbb{N}$ denotes the set of nonnegative integers. $\Sigma$ and $\Gamma$ denote finite alphabets not including the left and right word boundary symbols $\lb$ and $\rb$, respectively. The length of a string $x$ is denoted by $|x|$, and $\lambda$ denotes the empty string. Alphabet symbols are identified with strings of length $1$, and individual strings are identified with singleton sets of strings. For $k \in \mathbb{N}$, $\alpha^k$ denotes $\alpha$ concatenated with itself $k$-many times, $\alpha^{< k}$ denotes $\bigcup_{i = 0}^{k - 1} \alpha^i$, $\alpha^*$ denotes $\bigcup_{i = 0}^\infty \alpha^i$, and $\alpha^+$ denotes $\alpha\alpha^*$. The \textit{longest common prefix} of a set of strings $A$ is the longest string $\lcp(A)$ such that every string in $A$ begins with $\lcp(A)$. The \textit{$k$-suffix} of a string $x$, denoted $\suff^k(x)$, is the string consisting of the last $k$-many symbols of $\lb^k x$. A \textit{subsequential finite-state transducer} (SFST) is a 6-tuple $T = \langle Q, \Sigma, \Gamma, q_0, \mathalpha{\to}, \sigma \rangle$, where \begin{itemize} \item $Q$ is the set of \textit{states}, with $q_0 \in Q$ being the \textit{start state}; \item $\Sigma$ and $\Gamma$ are the \textit{input} and \textit{output alphabets}, respectively; \item $\mathalpha{\to}: Q \times \Sigma \to Q \times \Gamma^*$ is the \textit{transition function}; and \item $\sigma:Q \to \Gamma^*$ is the \textit{final output function}. \end{itemize} For $x \in \Sigma^*$; $y \in \Gamma^*$; and $q, r \in Q$, the notation $q \xrightarrow{x:y} r$ means that $T$ emits $y$ to the output stream and transitions to state $r$ if it reads $x$ in the input stream while it is in state $q$. Letting $f:\Sigma^* \to \Gamma^*$, we say that \textit{$T$ computes $f$} if for every $x \in \Sigma^*$, $f(x) = y\sigma(q)$, where $q_0 \xrightarrow{x:y} q$. A function is \textit{subsequential} if it is computed by an SFST. An SFST $T = \langle Q, \Sigma, \Gamma, q_0, \to, \sigma \rangle$ is \textit{onward} if for every state $q$ other than $q_0$, \[ \lcp\left(\left\lbrace y \middle|\exists x \exists r.q \xrightarrow{x:y} r \right\rbrace \cup \lbrace \sigma(q) \rbrace\right) = \lambda. \] Putting $T$ in onward form allows us to impose structure on the timing with which SFSTs produce output symbols. \begin{definition} Let $f:\Sigma^* \to \Gamma^*$. We define the function $f^\gets:\Sigma^* \to \Gamma^*$ by \[ f^\gets(x) := \lcp\left(\left\lbrace f(xy) \middle| y \in \Sigma^* \right\rbrace \right). \] For any $x, y \in \Sigma^*$, $f^\to_x(y)$ denotes the string such that $f(xy) = f^\gets(x)f^\to_x(y)$. We refer to $f^\to_x$ as the \textit{translation of $f$ by $x$} and to $f^\gets$ as \textit{$f$ top}.\footnote{This terminology follows \citet[pp. 692--693]{sakarovitchElementsAutomataTheory2009}. In the transducer inference literature, \citet{oncinaLearningSubsequentialTransducers1993} refer to $f_x^\to$ as the \textit{tails of $x$ in $f$}, and \citet{chandleeOutputStrictlyLocal2015} refer to $f^\gets$ as the \textit{prefix function associated to $f$}.} \end{definition} Suppose $T$ computes $f$. The following facts are apparent. \begin{itemize} \item Fix $w, x \in \Sigma^*$ and write $q_0 \xrightarrow{x:y} q$ and $q_0 \xrightarrow{x:z} r$. If $q = r$, then $f_w^\to = f_y^\to$. \item $T$ is onward if and only if for all $q \in Q \backslash \lbrace q_0 \rbrace$, if $q_0 \xrightarrow{x:y} q$, then $y = f^\gets(x)$. \end{itemize} These observations allow us to construct the \textit{minimal SFST for $f$} by identifying each state with a possible translation $f_x^\to$ \citep{raneySequentialFunctions1958}. Let $A$ and $B$ be alphabets that are possibly infinite. A function $h:A^* \to B^*$ is a \textit{homomorphism} if for every $x, y \in A^*$, $h(xy) = h(x)h(y)$. \section{Background} \label{sec:sec3} The \textit{strictly local functions} are classes of subsequential functions proposed by \citet{chandleeStrictlyLocalPhonological2014}, \citet{chandleeOutputStrictlyLocal2015}, and \citet{chandleeInputOutputStrictlyInprep} as transductive analogues of the strictly local languages \citep{mcnaughtonCounterFreeAutomata1971}. Whereas phonotactic dependencies can usually be described using \textit{tier-based strictly local} languages \citep{heinzTierbasedStrictlyLocal2011,mcmullinLongDistancePhonotacticsTierBased2016,mcmullinTierBasedLocalityLongDistance2016}, \citet{chandleeStrictlyLocalPhonological2014} has argued that local phonological processes can be modelled as strictly local functions when they are viewed as mappings between underlying representations and surface representations. A survey overview of the related literature can be found in \citet{heinzComputationalNaturePhonological2018}. Intuitively, strictly local functions are functions computed by SFSTs in which each state represents the $i - 1$ most recent symbols in the input stream and the $j - 1$ most recent symbols in the output stream along with the current input symbol, for some parameter values $i, j$ fixed. Such functions are ``local'' in the sense that the action performed on each input symbol depends only on information about symbols in the input and output streams within a bounded distance. In this paper, we augment strictly local functions with \textit{tier projection}, a mechanism introduced by \citet{heinzTierbasedStrictlyLocal2011} and elaborated by \citet{baekComputationalRepresentationUnbounded2018}, \citet{mayerChallengeTierBasedStrict2018}, and \citet{grafSanskritNRetroflexionInputOutput2018} that allows the locality constraint to bypass irrelevant alphabet symbols, extending the distance over which dependencies may be enforced. \begin{definition} For any alphabet $\Sigma$, a \textit{tier on $\Sigma$} is a homomorphism $\tau:\Sigma^* \to \Sigma^*$ such that for each $a \in \Sigma$, either $\tau(a) = a$ or $\tau(a) = \lambda$. In the former case, we say that $a$ is \textit{on $\tau$}; in the latter case, we say that $a$ is \textit{off $\tau$}. \end{definition} \citet{chandleeStrictlyLocalPhonological2014}, \citet{chandleeOutputStrictlyLocal2015}, and \citet{chandleeInputOutputStrictlyInprep} give two definitions of the strictly local functions. Firstly, they state the locality condition in terms of the algebraic representation of minimal SFSTs. \begin{definition} \label{defn:tioslalg} Fix $i, j > 0$ and let $\tau$ be a tier on $\Sigma \cup \Gamma$. A function $f:\Sigma^* \to \Gamma^*$ is \textit{$i, j$-input--output strictly local on tier $\tau$} ($i, j$-TIOSL) if for all $w, x \in \Sigma^*$, if \begin{itemize} \item $\suff^{i - 1}(\tau(w)) = \suff^{i - 1}(\tau(x))$ and \item $\suff^{j - 1}(\tau(f^\gets(w))) = \suff^{j - 1}(\tau(f^\gets(x)))$, \end{itemize} then $f^\to_w = f^\to_x$. A function is \textit{$i$-input strictly local on tier $\tau$} ($i$-TISL) if it is $i, 1$-TIOSL on tier $\tau$, and it is \textit{$j$-output strictly local on tier $\tau$} ($j$-TOSL) if it is $1, j$-TIOSL on tier $\tau$. \end{definition} Secondly, they define strictly local functions in terms of canonical SFSTs that directly encode $(i - 1)$-suffixes of the input stream and $(j - 1)$-suffixes of the output stream in their state names. \begin{definition} Fix $i, j > 0$ and let $\tau$ be a tier on $\Sigma \cup \Gamma$. An SFST $T = \langle Q, \Sigma, \Gamma, q_0, \to, \sigma \rangle$ is \textit{$i, j$-input--output strictly local on tier $\tau$} ($i, j$-TIOSL) if the following conditions hold. \begin{itemize} \item $Q = \left( \lbrace \lb \rbrace \cup \Sigma \right)^{i - 1} \times \left( \lbrace \lb \rbrace \cup \Gamma \right)^{j - 1}$ and $q_0 = \left\langle \lb^{i - 1}, \lb^{j - 1} \right\rangle$. \item If $\langle a, b \rangle \xrightarrow{x:y} \langle c, d \rangle$, then $c = \suff^{i - 1}(\tau(ax))$ and $d = \suff^{j - 1}(\tau(by))$. \end{itemize} An SFST is \textit{$i$-input strictly local on tier $\tau$} ($i$-TISL) if it is $i, 1$-TIOSL on tier $\tau$, and it is \textit{$j$-output strictly local on tier $\tau$} ($j$-TOSL) if it is $1, j$-TIOSL on tier $\tau$. \end{definition} These definitions turn out to be equivalent when the canonical SFSTs are required to be onward. \begin{theorem}[\citealp{chandleeStrictlyLocalPhonological2014,chandleeOutputStrictlyLocal2015,chandleeInputOutputStrictlyInprep}] A function is $i, j$-TIOSL on tier $\tau$ if and only if it is computed by an onward SFST that is $i, j$-TIOSL on tier $\tau$. \end{theorem} \begin{figure} \begin{center} \begin{tikzpicture}[>=stealth',shorten >=1pt,auto,node distance=2cm] \node [initial, state, accepting] (q2) {$\lb$}; \node [state, accepting] (q0) [right of=q2] {\textipa{@}}; \node [state, accepting] (q1) [right of=q0] {V}; \path [->] (q2) edge [loop above] node {$C:C$} (q2) (q2) edge node {$V:\text{\textipa{@}}$} (q0) (q0) edge [loop above] node {$C:C$} (q0) (q0) edge [bend left] node {$V:V$} (q1) (q1) edge [loop above] node {$C:C$} (q1) (q1) edge [bend left] node {$V:\text{\textipa{@}}$} (q0); \end{tikzpicture} \end{center} \caption{An SFST for rhythmic reduction.} \label{fig:fig1} \end{figure} \begin{example} \label{ex:osl} \textit{Rhythmic reduction} is a phonological process in which alternating vowels in a word undergo reduction. The examples in (\ref{ex:ojibwereduction}) show rhythmic reduction in the Odawa variety of Ojibwe circa 1912, as documented by Edward Sapir. In our representation of reduction, vowels are reduced to \textipa{@}, starting from the first vowel. There is no reason to believe that \textipa{@} appears in underlying forms. \begin{exe} \ex Rhythmic reduction in Ojibwe circa 1912 \citep{rhodesAlgonquianTradeLanguages2012} \label{ex:ojibwereduction} \begin{xlist} \ex /\textipa{m2kIzIn2n}/ $\leadsto$ [\textipa{m@kIz@n2n}] `shoes' \ex /\textipa{gUtIgUmIn2gIbIna:d}/ $\leadsto$ \\ \lbrack\textipa{g@tIg@mIn@gIb@na:d}\rbrack\ `if he rolls him' \end{xlist} \end{exe} \autoref{fig:fig1} shows an SFST that implements the rhythmic reduction pattern illustrated in (\ref{ex:ojibwereduction}). We represent the pattern using an alphabet of three symbols: $C$, representing consonants; $V$, representing vowels that have not been reduced; and \textipa{@}, representing vowels that have been reduced. Observe that this SFST is onward and $2$-TOSL, with $C$ off the tier: each state represents the most recent vowel in the ouput stream.\footnote{For clarity, we omit the $\langle \lambda, \cdot \rangle$ portions of the state names.} \end{example} \section{Rhythmic Syncope} \label{sec:sec4} \textit{Rhythmic syncope} is a phonological process in which every second vowel in a word is deleted. The examples of (\ref{ex:macushisyncope}) show rhythmic syncope in Macushi, in which deletion begins with the first vowel.\footnote{The synchronic status of rhythmic syncope is a matter of current discussion, as its development appears to push a phonological system into dramatic restructuring \citep{bowersNishnaabemwinRestructuringControversyToappear}.} \begin{exe} \ex Rhythmic syncope in Macushi \citep{hawkinsPatternsVowelLoss1950} \label{ex:macushisyncope} \begin{xlist} \ex /\textipa{piripi}/ $\leadsto$ [\textipa{pripi}] `spindle' \ex /\textipa{wanamari}/ $\leadsto$ [\textipa{wnamri}] `mirror' \end{xlist} \end{exe} In this section, we show that rhythmic syncope is not TIOSL. To see this, we formalize rhythmic syncope as a function over two alphabet symbols: $C$, representing consonants, and $V$, representing vowels. This idealization does not affect the argument that rhythmic syncope is not TIOSL, presented in Proposition \ref{prop:rsnottsl}. \begin{definition} The \textit{rhythmic syncope function} $\rs:\lbrace C, V \rbrace^* \to \lbrace C, V \rbrace^*$ is defined as follows. For $c_0, c_1, \dots, c_n \in C^*$, \[ \rs(c_0Vc_1Vc_2 \dots Vc_n) = c_0v_1c_1v_2c_2 \dots v_nc_n\text{,} \] where for each $i$, $v_i = V$ if $i$ is even and $v_i = \lambda$ if $i$ is odd.\footnote{While $\rs$ is defined on strings of phonemes with no prosodic symbols, phonological analyses often assume that the input is parsed into feet with iambic or trochaic stress. Such analyses are discussed in Section \ref{sec:sec7}.} \end{definition} The intuition underlying the argument below is that $(i - 1)$-suffixes of the input and $(j - 1)$-suffixes of the output do not contain information about whether vowels occupy even or odd positions within the input and output strings. Therefore, while an $i, j$-TIOSL SFST can record the most recent vowels read from the input stream and emitted to the output stream, this information is not sufficient for determining whether or not the SFST should delete a vowel. \begin{proposition} \label{prop:rsnottsl} The rhythmic syncope function is not $i, j$-TIOSL on tier $\tau$ for any $i, j > 0$ and any $\tau:\lbrace C, V \rbrace^* \to \lbrace C, V \rbrace^*$. \end{proposition} \begin{proof} Let $k > i$ be even. Consider the strings $w := V^k$ and $x := V^{k + 1}$. Observe that $\rs^\gets(w) = \rs^\gets(x) = V^{k / 2}$; thus $\suff^{j - 1}(\tau(\rho^\gets(w))) = \suff^{j - 1}(\tau(\rho^\gets(x)))$. Now, if $V$ is on $\tau$, then $\suff^{i - 1}(\tau(w)) = V^{i - 1} = \suff^{i - 1}(\tau(x))$, and if $V$ is off $\tau$, then $\suff^{i - 1}(\tau(w)) = \lb^{i - 1} = \suff^{i - 1}(\tau(x))$. Thus, if $\rs$ is $i, j$-TIOSL on tier $\tau$, then $\rs_{w}^\to = \rs_{x}^\to$. However, letting $y := V^{k/2}$, observe that \begin{align*} y &= \rs(wV) = \rs^\gets(w)\rs_{w}^\to(V) = y\rs_{w}^\to(V) \\ yV &= \rs(xV) = \rs^\gets(x)\rs_x^\to(V) = y \rs_x^\to(V). \end{align*} This means that $\rs_w^\to(V) = \lambda$ but $\rs_x^\to(V) = V$, so $\rs$ is not $i, j$-TIOSL on tier $\tau$. \end{proof} \section{Synchronized Strictly Local Functions} \label{sec:sec5} \begin{figure} \begin{center} \begin{tikzpicture}[>=stealth',shorten >=1pt,auto,node distance=2cm] \node [initial, state, accepting] (q2) {$\lb$}; \node [state, accepting] (q0) [right of=q2] {$V:\lambda$}; \node [state, accepting] (q1) [right of=q0] {$V:V$}; \path [->] (q2) edge [loop above] node {$C:C$} (q2) (q2) edge node {$V:\lambda$} (q0) (q0) edge [loop above] node {$C:C$} (q0) (q0) edge [bend left] node {$V:V$} (q1) (q1) edge [loop above] node {$C:C$} (q1) (q1) edge [bend left] node {$V:\lambda$} (q0); \end{tikzpicture} \end{center} \caption{An SFST for rhythmic syncope.} \label{fig:fig2} \end{figure} Proposition \ref{prop:rsnottsl} raises the question of how to characterize the kind of computation that effects rhythmic syncope. To investigate this question, \autoref{fig:fig2} shows a natural SFST implementation of rhythmic syncope. The states in this SFST record the most recent action performed by the SFST. If the most recent action was to delete a vowel ($V:\lambda$), then the next vowel the SFST encounters is not deleted ($V:V$); otherwise, the next vowel is deleted. This SFST is strikingly similar to the rhythmic reduction SFST in Figure 1. There, the special symbol \textipa{@}, which is not part of the input alphabet, indicates the location of a reduced vowel, effectively recording the previous action in the output. Since there is no way to mark the location of a deleted symbol, the SFST in \autoref{fig:fig2} explicitly records its previous action in its state names. Thus, the rhythmic syncope SFST may be seen as a generalization of the rhythmic reduction SFST. The goal of this section is to define a class of functions, known as the \textit{tier-based synchronized strictly local} (TSSL) functions, based on this intuition. Following Section \ref{sec:sec2}, we begin by defining the TSSL functions algebraically in terms of the minimal SFST, and then we define a canonical SFST format for the TSSL functions. Recall that at each time step, an SFST must read exactly one input symbol while producing an output string of any length. Since the minimal SFST for a function $f$ must produce $f^\gets(z)$ after reading the input string $z$, we can determine the possible actions of $f$ by comparing $f^\gets(z)$ with $f^\gets(zx)$ for arbitrary $z \in \Sigma^*$ and $x \in \Sigma$. \begin{definition} Let $f:\Sigma^* \to \Gamma^*$. The \textit{actions of $f$} are the alphabet $\A{f} \subseteq \Sigma \times \Gamma^*$ defined as follows. \[ \A{f} := \lbrace \langle x, y \rangle | \exists z \in \Sigma^*.f^\gets(zx) = f^\gets(z)y \rbrace \] We denote elements $\langle x, y \rangle$ of $\A{f}$ by $x:y$. \end{definition} Strings over $\A{f}$ represent computation histories of the minimal SFST for $f$. \begin{definition} Let $x \in \Sigma^*$ and let $f:\Sigma^* \to \Gamma^*$. The \textit{run of $f$ on input $x$} is the string $f^\Leftarrow(x) \in \A{f}^*$ defined as follows. \begin{itemize} \item If $|x| \leq 1$, then $f^\Leftarrow(x) := x:f^\gets(x)$. \item If $x = yz$, where $|y| \geq 1$ and $|z| = 1$, then $f^\Leftarrow(x) := f^\Leftarrow(y)(z:w)$, where $w$ is the unique string such that $f^\gets(x) = f^\gets(y)w$. \end{itemize} \end{definition} The notation $f^\Leftarrow$ allows us to define the TSSL functions in a straightforward manner, highlighting the analogy to the TIOSL functions. \begin{definition} Fix $k > 0$ and let $\tau$ be a tier on $\Sigma \times \Gamma^*$. A function $f:\Sigma^* \to \Gamma^*$ is \textit{$k$-synchronized strictly local on tier $\tau$} ($k$-TSSL) if for all $x, y \in \Sigma^*$, if $\suff^{k - 1}(\tau(f^\Leftarrow(x))) = \suff^{k - 1}(\tau(f^\Leftarrow(y)))$, then $f^\to_x = f^\to_y$. \end{definition} Now, let us define the canonical SFSTs for TSSL functions. We define the actions of an SFST to be its possible transition labels. \begin{definition} Let $T = \langle Q, \Sigma, \Gamma, q_0, \to, \sigma \rangle$ be an SFST. The \textit{actions of $T$} are the alphabet \[ \A{T} := \left\lbrace \langle x, y \rangle \middle| \exists q \exists r.\mathalpha{\to}(q, x) = \langle r, y \rangle \right\rbrace. \] We denote elements $\langle x, y \rangle$ of $\A{T}$ by $x:y$. \end{definition} Again, the definition of the TSSL SFSTs is directly analogous to that of the TIOSL SFSTs. \begin{definition} \label{defn:tsslsfst} Fix $k > 0$ and let $\tau$ be a tier on $\Sigma \times \Gamma^*$. An SFST $T = \langle Q, \Sigma, \Gamma, q_0, \to, \sigma \rangle$ is \textit{$k$-synchronized strictly local on tier $\tau$} ($k$-TSSL) if the following conditions hold. \begin{itemize} \item $Q = \left( \lbrace \lb \rbrace \cup \A{T} \right)^{k - 1}$ and $q_0 = \lb^{k - 1}$. \item For every $q \in Q$, if $\mathalpha{\to}(q, x) = \langle r, y \rangle$, then \[ r = \suff^{k - 1}\left( \tau\left( q(x:y) \right) \right). \] \end{itemize} \end{definition} As is the case with TIOSL SFSTs, TSSL SFSTs compute exactly the class of TSSL functions when they are required to be onward. \begin{theorem} Fix $k > 0$, and let $\tau$ be a tier on $\Sigma \times \Gamma^*$. A function is $k$-TSSL on tier $\tau$ if and only if it is computed by an onward SFST that is $k$-TSSL on tier $\tau$. \end{theorem} We leave the proof of this fact to Appendix \ref{sec:appendix}. \section{Properties of TSSL Functions} \label{sec:sec6} Having now defined the TSSL functions, this section investigates some of their formal properties. Subsection \ref{sec:sub61} compares the TSSL functions to the TISL, TOSL, and TIOSL functions. Subsection \ref{sec:sub62} observes that TSSL SFSTs compute a large class of functions when they are not required to be onward. \subsection{Relation to TIOSL Functions} \label{sec:sub61} A natural first question regarding the TSSL functions is that of how they relate to previously-proposed classes of subregular functions. We know from the discussion of rhythmic syncope that the TSSL functions are not a subset of the TIOSL functions: we have already seen that the rhythmic syncope function is $2$-TSSL but not $i, j$-TIOSL for any $i, j$. We will see in this subsection that the TIOSL functions are not a subset of the TSSL functions, though both function classes fully contain the TISL and TOSL functions. Therefore, the two function classes are incomparable, and offer two different ways to generalize the TISL and TOSL functions. The fact that the TSSL functions contain the TISL and TOSL functions follows from the observation that actions contain information about input and output symbols. Remembering the $i$ most recent actions automatically entails remembering the $i$ most recent input symbols, and the $j$ most recent output symbols can be extracted from the $j$ most recent actions if deletions are ignored. \begin{proposition} \label{prop:tisltosltssl} Fix $k > 0$. Every $k$-TISL function and every $k$-TOSL function is $k$-TSSL. \end{proposition} \begin{proof} Let $f:\Sigma^* \to \Gamma^*$, and let $\tau$ be a tier on $\Sigma \cup \Gamma$. First, suppose that $f$ is $k$-TISL on tier $\tau$. Let $\upsilon$ be a tier on $\Sigma \times \Gamma^*$ defined as follows: an action $x:y$ is on $\upsilon$ if and only if $x$ is on $\tau$. Now, suppose $w, x \in \Sigma^*$ are such that $\suff^{k - 1}(\upsilon(f^\Leftarrow(w))) = \suff^{k - 1}(\upsilon(f^\Leftarrow(x)))$. Write \begin{align*} \upsilon(f^\Leftarrow(w)) &= (w_1:y_1)(w_2:y_2) \dots (w_n:y_n) \\ \upsilon(f^\Leftarrow(x)) &= (x_1:z_1)(x_2:z_2) \dots (x_n:z_n). \end{align*} Then, we have $\tau(w) = w_1w_2 \dots w_n$ and $\tau(x) = x_1x_2 \dots x_n$. For all $i > n - k + 1$, $w_i:y_i = x_i:z_i$, and therefore $w_i = x_i$. But this means that $\suff^{k - 1}(\tau(w)) = \suff^{k - 1}(\tau(x))$, and since $f$ is $k$-TISL on tier $\tau$, $f_w^\gets = f_x^\gets$. We conclude that $f$ is $k$-TSSL on tier $\upsilon$. Next, suppose that $f$ is $k$-TOSL on tier $\tau$. Let $\varphi$ be a tier on $\Sigma \times \Gamma^*$ defined as follows: an action $x:y$ is on $\varphi$ if and only if $\tau(y) \neq \lambda$. Now, suppose $w, x \in \Sigma^*$ are such that $\suff^{k - 1}(\varphi(f^\Leftarrow(w))) = \suff^{k - 1}(\varphi(f^\Leftarrow(x)))$. Write \begin{align*} \varphi(f^\Leftarrow(w)) &= (w_1:y_1)(w_2:y_2) \dots (w_n:y_n) \\ \varphi(f^\Leftarrow(x)) &= (x_1:z_1)(x_2:z_2) \dots (x_n:z_n). \end{align*} Now, $\tau(f^\gets(w)) = y_1y_2 \dots y_n$ and $\tau(f^\gets(x)) = z_1z_2 \dots z_n$. Again, for all $i > n - k + 1$ we have $w_i:y_i = x_i:z_i$, so $y_i = z_i$. Observe that \begin{align*} &\mathrel{\phantom{=}} \suff^{k - 1}(\tau(f^\gets(w))) = \suff^{k - 1}(y_jy_{j + 1} \dots y_n) \\ &= \suff^{k - 1}(z_jz_{j + 1} \dots z_n) = \suff^{k - 1}(\tau(f^\gets(x)))\text{,} \end{align*} where $j = n - k + 2$. Since $f$ is $k$-TOSL on tier $\tau$, $f_w^\to = f_x^\to$, so $f$ is $k$-TSSL on tier $\varphi$. \end{proof} This intuition does not carry over to the TIOSL functions. In Proposition \ref{prop:tisltosltssl}, the proposed action tiers ignore symbols off the input and output tiers, thus ensuring that the relevant input and output symbols can always be recovered from the computation history. This approach encounters problems when an onward TIOSL SFST deletes symbols on the tier. Such SFSTs perform actions of the form $x:\lambda$, where $x$ is on the tier. These actions do not record any output symbols, but they must be kept on the tier in a TSSL implementation so that the input symbol $x$ can be recovered. If too many $(x:\lambda)$s are performed consecutively, they can overwhelm the memory of a TSSL SFST, causing it to forget the most recent output symbols. The following construction features exactly this kind of behavior. \begin{proposition} There exists a function that is $i, j$-TIOSL for some $i, j$ but not $k$-TSSL for any $k$. \end{proposition} \begin{figure} \begin{center} \begin{tikzpicture}[>=stealth',shorten >=1pt,auto,node distance=2cm] \node [initial, state, accepting] (q0) {$\lb, \lb$}; \node [state, accepting] (aa) [right of=q0, above of=q0, yshift=-.75cm] {$a, a$}; \node [state, accepting] (bb) [right of=q0, below of=q0, yshift=.75cm] {$b, b$}; \node [state, accepting] (ab) [right of=bb, xshift=.75cm] {$a, b$}; \node [state, accepting] (ba) [right of=aa, xshift=.75cm] {$b, a$}; \path [->] (q0) edge node {$a:a$} (aa) (q0) edge node [below left] {$b:b$} (bb) (aa) edge [loop above] node {$a:\lambda$} (aa) (ab) edge [loop below] node {$a:\lambda$} (ab) (ba) edge [loop above] node {$b:d$} (ba) (bb) edge [loop below] node {$b:c$} (bb) (aa) edge [bend left] node {$b:c$} (ba) (ba) edge [bend left] node {$a:\lambda$} (aa) (bb) edge [bend left] node {$a:\lambda$} (ab) (ab) edge [bend left] node {$b:d$} (bb); \end{tikzpicture} \end{center} \caption{An onward $2, 2$-TIOSL SFST computing a function that is not $k$-TSSL for any $k$.} \label{fig:fig3} \end{figure} \begin{proof} Let $T$ be the SFST shown in \autoref{fig:fig3}, and let $f:\lbrace a, b \rbrace^* \to \lbrace a, b, c, d \rbrace^*$ be the function computed by $T$.\footnote{The angle brackets are omitted from the state names.} Observe that $T$ is onward and $2, 2$-TIOSL on tier $\tau$, where $a$ and $b$ are on $\tau$ but $c$ and $d$ are not, so $f$ is $2, 2$-TIOSL on tier $\tau$. $T$ always copies the first symbol of its input to the output. Thereafter, $T$ behaves as follows: all $a$s are deleted; a $b$ is changed to a $c$ if the most recent input symbol is the same as the first input symbol; a $b$ is changed to a $d$ otherwise. For example, $f(baabb) = bdc$. Let $k > 0$, and let $\upsilon$ be a tier on $\lbrace a, b \rbrace \times \lbrace a, b, c, d \rbrace^*$. Suppose that either $k = 1$ or $a:\lambda$ is not on $\upsilon$, and consider the strings $w := ba$ and $x := b$. Observe that $f^\Leftarrow(w) = (b:b)(a:\lambda)$ and $f^\Leftarrow(x) = (b:b)$. Either $\suff^{k - 1}(\upsilon(f^\Leftarrow(x))) = \lb^{k - 2}(b:b) = \suff^{k - 1}(\upsilon(f^\Leftarrow(x)))$ if $k > 1$ and $b:b$ is on $\upsilon$, or $\suff^{k - 1}(\upsilon(f^\Leftarrow(x))) = \lb^{k - 1} = \suff^{k - 1}(\upsilon(f^\Leftarrow(x)))$ if $k = 1$ or $b:b$ is not on $\upsilon$. However, $f^\to_w(b) = d$ but $f^\to_x(b) = c$, so $f$ cannot be $k$-TSSL on tier $\upsilon$. Next, suppose that $k > 1$ and $a:\lambda$ is on $\upsilon$. Consider the input strings $w := a^{k + 1}$ and $x := ba^k$. Observe that $f^\Leftarrow(w) = (a:a)(a:\lambda)^k$ and $f^\Leftarrow(x) = (b:b)(a:\lambda)^k$, thus \begin{align*} \suff^{k - 1}(\upsilon(f^\Leftarrow(w))) &= (a:\lambda)^{k - 1} \\ &= \suff^{k - 1}(\upsilon(f^\Leftarrow(x))). \end{align*} However, $f_w^\to(b) = c$ but $f_x^\to(b) = d$, so $f$ is not $k$-TSSL on tier $\upsilon$. \end{proof} \subsection{Non-Onward TSSL SFSTs} \label{sec:sub62} \begin{figure*} \centering \begin{tikzpicture}[>=stealth',shorten >=1pt,auto,node distance=2cm] \node [initial, state, accepting] (q0) {$\lb$}; \node [state, accepting] (a-a) [below of=q0] {$a:a$}; \node (a-a1) [below of=a-a] {}; \node [state, accepting] (b-b) [below of=a-a1] {$b:b$}; \node [state, accepting] (b-) [right of=q0, xshift=2cm] {$b:\lambda$}; \node (b-1) [below of=b-] {}; \node (b-2) [below of=b-1] {}; \node [state, accepting] (a-aa) [below of=b-2] {$a:aa$}; \node (b-3) [right of=b-] {}; \node (b-4) [below of=b-3] {}; \node [state, accepting] (a-ba) [below of=b-4] {$a:ba$}; \node (b-5) [right of=b-3] {}; \node [state, accepting] (b-ab) [below of=b-5] {$b:ab$}; \node [state, accepting] (b-bb) [right of=b-5] {$b:bb$}; \node (b-bb1) [below of=b-bb] {}; \node (b-bb2) [below of=b-bb1] {}; \node [state, accepting] (a-) [below of=b-bb2] {$a:\lambda$}; \node (sigma-a-a) [left of=a-a] {$:a$}; \node (sigma-b-b) [left of=b-b] {$:a$}; \node (temp-sigma-b-) [below of=b-] {}; \node (sigma-b-) [left of=temp-sigma-b-] {$:bb$}; \node (sigma-b-bb) [right of=b-bb] {$:b$}; \node (sigma-b-ab) [right of=b-ab] {$:b$}; \node (sigma-a-ba) [left of=a-ba] {$:b$}; \node (sigma-a-aa) [left of=a-aa] {$:b$}; \node (sigma-a-) [right of=a-] {$:ab$}; \path [->] (q0) edge node {$a:a$} (a-a) (a-a) edge [bend left] node {$b:b$} (b-b) (b-b) edge [bend left] node {$a:a$} (a-a) (q0) edge node {$b:\lambda$} (b-) (b-) edge [bend left] node {$b:bb$} (b-bb) (b-) edge [bend left, below left] node {$a:ba$} (a-ba) (a-aa) edge [bend left, below] node {$a:\lambda$} (a-) (a-aa) edge [bend left] node {$b:\lambda$} (b-) (a-ba) edge [bend left, below left] node {$a:\lambda$} (a-) (a-ba) edge [bend left] node {$b:\lambda$} (b-) (b-ab) edge [left] node {$a:\lambda$} (a-) (b-ab) edge [above right] node {$b:\lambda$} (b-) (b-bb) edge [bend left] node {$a:\lambda$} (a-) (b-bb) edge [above] node {$b:\lambda$} (b-) (a-) edge node {$a:aa$} (a-aa) (a-) edge [bend right, above right] node {$b:ab$} (b-ab) (a-a) edge (sigma-a-a) (b-b) edge (sigma-b-b) (b-) edge (sigma-b-) (b-bb) edge (sigma-b-bb) (b-ab) edge (sigma-b-ab) (a-ba) edge (sigma-a-ba) (a-aa) edge (sigma-a-aa) (a-) edge (sigma-a-); \end{tikzpicture} \caption{A non-onward $2$-TSSL SFST computing a function that is not $k$-TSSL for any $k$.} \label{fig:fig4} \end{figure*} The equivalence between the two definitions of the TSSL functions presented in Section \ref{sec:sec5} crucially depends on the criterion that TSSL SFSTs be onward. In this subsection we show that without this criterion, TSSL SFSTs compute a rich class of subsequential functions. To illustrate how this is possible, let us consider an example that witnesses the separation between TSSL functions and TSSL SFSTs. \begin{proposition} \label{prop:tsslsfstnottsslfunction} There exists a $2$-TSSL SFST that computes a function that is not $k$-TSSL for any $k$. \end{proposition} \begin{proof} Consider the SFST in \autoref{fig:fig4}. This SFST is clearly $2$-TSSL on a tier containing all actions, and the function it computes is given by $f(xy) = xyx$, where $x \in \lbrace a, b \rbrace$ and $y \in \lbrace a, b \rbrace^*$. Observe that for any $z \in \lbrace a, b \rbrace^*$, $f^\gets(z) = z$. Therefore, writing $z = z_1z_2 \dots z_n$ with $|z_i| = 1$ for each $i$, \[ f^\Leftarrow(z) = (z_1:z_1)(z_2:z_2) \dots (z_n:z_n). \] We need to show that $f$ is not $k$-TSSL for any $k > 0$ and for any tier $\tau$ over $\lbrace a, b \rbrace \times \lbrace a, b \rbrace^*$. Fix $k$ and $\tau$. Suppose $a:a$ is on $\tau$, and consider the input strings $w = a^{k + 1}$ and $x = ba^k$. Observe that $f^\Leftarrow(w) = (a:a)^{k + 1}$ and $f^\Leftarrow(x) = (b:b)(a:a)^k$, so \begin{align*} \suff^{k - 1}(\tau(f^\Leftarrow(w))) &= (a:a)^{k - 1} \\ &= \suff^{k - 1}(\tau(f^\Leftarrow(x))). \end{align*} However, $f_w^\to(\lambda) = a$ but $f_x^\to(\lambda) = b$, so $f$ is not $k$-TSSL on tier $\tau$. Next, suppose $a:a$ is not on $\tau$, and consider the input strings $w = b$ and $x = ab$. We have $f^\Leftarrow(w) = b:b$ and $f^\Leftarrow(x) = (a:a)(b:b)$, so \begin{align*} \suff^{k - 1}(\tau(f^\Leftarrow(w))) &= \suff^{k - 1}(\tau(b:b)) \\ &= \suff^{k - 1}(\tau(a:a)\tau(b:b)) \\ &= \suff^{k - 1}(\tau((a:a)(b:b))) \\ &= \suff^{k - 1}(\tau(f^\Leftarrow(x))). \end{align*} However, $f_w^\to(\lambda) = b$ but $f_x^\to(\lambda) = a$, so $f$ is not $k$-TSSL on tier $\tau$. \end{proof} Let $f$ be the function described in Proposition \ref{prop:tsslsfstnottsslfunction}. As discussed in the proof, an onward SFST computing $f$ must copy the current input symbol to the output stream during each time step. At the end of the computation, the final output function is responsible for adding the first input symbol to the end of the output string. Any onward TSSL SFST that attempts to compute $f$ will eventually forget the identity of the first input symbol, so the final output function cannot determine what to add to the output. The SFST $T$ in \autoref{fig:fig4} avoids this problem by exploiting its non-onwardness. If the first symbol of its input is an $a$, then $T$ behaves in an onward manner, copying the current input symbol at each time step. This can be seen in the left column of the state diagram. If the first symbol of $T$'s input is a $b$, then $T$ alternates between producing no output and producing two symbols of output. Every time $T$ performs a non-deleting action $x:y$, $y$ contains both the symbol that the onward SFST would produce at the current time step and the symbol that the onward SFST would have produced at the previous time step. This way, $T$ encodes the identity of the first symbol of its input using the manner in which it produces output---if $T$ produces output at every time step, then the first symbol is an $a$, and if it produces output every two time steps, then the first symbol is a $b$. In general, this kind of encoding trick can be applied to a wide range of SFSTs, including all SFSTs $V$ that do not perform deletions. Informally, we enumerate the states of $V$ by $\lbrace q_0, q_1, \dots, q_n \rbrace$, and we construct a TSSL SFST $S$ that simulates $V$ by producing output at various frequencies. For each $i$, $S$ produces output every $i + 1$ time steps if $V$ is in state $q_i$. If $S$ remembers at least $2(n + 1)$-many actions, then it can always deduce $V$'s state at any point in the computation, allowing it to simulate $V$. \section{Rhythmic Syncope in Phonology} \label{sec:sec7} The view of rhythmic syncope we have presented here differs substantially in approach from existing treatments of rhythmic syncope in phonological theory. \citet{mccarthySerialInteractionStress2008} identifies two major approaches to rhythmic syncope in Optimality Theory. In the \textit{pseudo-deletion} approach (e.g., \citealp{kagerRhythmicVowelDeletion1997}), the locations of symbols deleted by syncope are marked with blank symbols. This essentially makes rhythmic syncope identical to rhythmic reduction, which we have seen is $2$-TOSL. \citeauthor{mccarthySerialInteractionStress2008} himself proposes a \textit{Harmonic Serialism} approach in which rhythmic syncope is implemented in multiple steps. Firstly, stress is assigned to every second vowel in the underlying form. Then, the unstressed vowels are deleted, resulting in syncope. This kind of derivation is illustrated in (\ref{ex:mccarthy}). \begin{exe} \ex Rhythmic syncope in Harmonic Serialism \citep{mccarthySerialInteractionStress2008}\footnote{The full derivation proposed by \citet{mccarthySerialInteractionStress2008} includes syllabification and footing steps, which are omitted here for simplicity.} \label{ex:mccarthy} \\ \begin{tabular}{l l} /\textipa{wanamari}/ & Underlying Form \\ \textipa{wan\'{a}mar\'{\i}}& Stress \\ \lbrack \textipa{wn\'{a}mr\'{\i}} \rbrack & Syncope \end{tabular} \end{exe} In both approaches, rhythmic syncope is decomposed into a $2$-TOSL function and a homomorphism. In the pseudo-deletion approach, the $2$-TOSL function is rhythmic reduction, and the homomorphism removes the \textipa{@}s. In (\ref{ex:mccarthy}), the rhythmic stress step is $2$-TOSL, while the syncope step is a homomorphism. In general, this kind of approach is extremely powerful. \begin{proposition} \label{prop:harmonicserialism} Every subsequential function $f$ can be written in the form $f = h \circ g$, where $g$ is $2$-TOSL and $h$ is a homomorphism. \end{proposition} \begin{proof} Let $T = \langle Q, \Sigma, \Gamma, q_0, \to, \sigma \rangle$ be the minimal SFST for $f$. Define $g$ as follows. Let $g(\lambda) := \langle \sigma, f(\lambda) \rangle$. For $x_1, x_2, \dots, x_n \in \Sigma$, write \[ q_0 \xrightarrow{x_1:y_1} q_1 \xrightarrow{x_2:y_2} q_2 \xrightarrow{x_3:y_3} \dots \xrightarrow{x_{n - 1}:y_{n - 1}} q_n. \] Then, $g(x_1x_2 \dots x_n) := \langle q_1, y_1 \rangle \allowbreak \langle q_2, y_2 \rangle \allowbreak \dots \allowbreak \langle q_n, \allowbreak y_n \rangle \langle \sigma, \sigma(q_n) \rangle$. Next, define $h$ so that for any $\langle q, y \rangle$, $h(\langle q, y \rangle) = y$. It is clear that $f(x) = h(g(x))$ for every $x$. We now show that $g$ is $2$-TOSL on a tier containing the full output alphabet. Fix $w, x \in \Sigma^*$. Observe that for all $z \in \Sigma^*$, $g^\gets(z) \in (Q \times \Gamma^*)^*$. Therefore, suppose that $\suff^1(g^\gets(w)) = \suff^1(g^\gets(x)) = \langle q, y \rangle$. This means that $q_0 \xrightarrow{w:u} q$ and $q_0 \xrightarrow{x:v} q$ for some $u, v \in \Gamma^*$, so $g^\to_u = g^\to_v$ by definition. \end{proof} In both pseudo-deletion and Harmonic Serialism, non-segmental phonological symbols are used to encode state information in the output, making rhythmic syncope $2$-TOSL. Proposition \ref{prop:harmonicserialism} shows that this technique can be applied to arbitrary SFSTs, and therefore results in massive overgeneration. By contrast, we have already seen that the TSSL functions are a proper subset of the subsequential functions, making action-sensitivity a more restrictive alternative to current approaches to rhythmic syncope. \section{Conclusion} \label{sec:sec8} The classic examples of TIOSL phenomena in phonology are local processes and unidirectional spreading processes \citep{chandleeStrictlyLocalPhonological2014}. Rhythmic syncope is qualitatively different from these phenomena in that it leaves no evidence that the process has occurred. As we have seen in Section \ref{sec:sec4}, the fact that rhythmic syncope is not TIOSL is a consequence of this property. In defining the TSSL functions, we have proposed that rhythmic syncope should be viewed as a dependency between incremental steps in a derivation, here formalized as the actions of the minimal SFST. A potential risk of such an analysis is that the notion of ``action'' is specific to the computational system used to implement rhythmic syncope, and therefore potentially subject to a broad range of interpretations. In this paper, we have used onwardness and the existence of the minimal SFST to formulate a notion of ``action-sensitivity'' that is both formalism-independent and implementation-independent. In Subsection \ref{sec:sub62}, we have seen that action-sensitivity can be made very powerful if we relax our assumptions about the nature of the computation. This means that if action-sensitivity is to be incorporated into phonological analyses of rhythmic syncope, then care should be taken to avoid loopholes like the one featured in Proposition \ref{prop:tsslsfstnottsslfunction}. Based on Proposition \ref{prop:harmonicserialism}, a similar warning can be made regarding the composition of phonological processes. When decomposing phonemena into several processes, as \citet{mccarthySerialInteractionStress2008} does in the Harmonic Serialism analysis, care should be taken to ensure that theoretical proposals do not allow for overgeneration. Outstanding formal questions regarding the TSSL functions include their closure properties and the complexity of learning TSSL functions. We leave such questions to future work.
{'timestamp': '2019-06-18T02:04:47', 'yymm': '1906', 'arxiv_id': '1906.06464', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06464'}
arxiv
\section{Introduction} Let $G=(V, E)$ be an undirected graph with a set of vertices $V(G)$ and a set of normal edges $E(G)$ (no loops or multiple edges). We discuss \textit{Ising models} which associate the following probability to each random $N\triangleq |V(G)|$-dimensional binary variable/spin configuration $X \in \{\pm 1 \}^{N}$: \begin{gather} \mathbb{P}(X) \triangleq \frac{\mathcal{W}(X)}{Z}, \label{eq:zfim} \end{gather} where \begin{gather} \mathcal{W}(X) \triangleq \exp\biggl( \sum_{v \in V(G)} \mu_v x_v + \sum_{ e = \{ v, w \} \in E(G)} J_e x_v x_w \biggr) \quad \text{and}\quad Z \triangleq \sum_{X \in \{ \pm 1 \}^N} \mathcal{W}(X). \label{eq:Z} \end{gather} Here, $\mu = (\mu_v, v \in V(G))$ is a vector of \textit{(magnetic) fields}, $J = (J_e, e \in E(G))$ is a vector of the \textit{(pairwise) spin interactions}, and the normalization constant $Z$, which is defined as a sum over $2^N$ spin configurations, is referred to as the \textit{partition function}. Given the model specification $\mathcal{I} = \langle G, \mu, J \rangle$, we address the tasks of finding the exact value of $Z$ (inference) and drawing exact samples with the probability (\ref{eq:zfim}). \textbf{Related work.} It has been known since the seminal contributions of Fisher \cite{fisher} and Kasteleyn \cite{kasteleyn} that computation of the partition function in the zero-field ($\mu = 0$) Ising model over a planar graph and sampling from the respective probability distribution are both tractable, that is, these are tasks of complexity polynomial in $N$. As shown by Barahona \cite{barahona}, even when $G$ is planar or when $\mu = 0$ (\textit{zero field}), the positive results are hard to generalize---both addition of the non-zero (magnetic) field and the extension beyond planar graphs make the computation of the partition function NP-hard. These results are also consistent with the statement from Jerrum and Sinclair \cite{jerrum-sinclair} that computation of the partition function of the zero-field Ising model is a \#P-complete problem, even in the ferromagnetic case when all components of $J$ are positive. Therefore, describing $\langle G, \mu, J \rangle$ families for which computations of the partition function and sampling are tractable remains an open question. The simplest tractable (i.e., inference and sampling are polynomial in $N$) example is one when $G$ is a tree, and the corresponding inference algorithm, known as \textit{dynamic programming} and/or \textit{belief propagation}, has a long history in physics \cite{bethe,peierls}, optimal control \cite{bellman}, information theory \cite{gallager}, and artificial intelligence \cite{pearl}. Extension to the case when $G$ is a tree of $(t + 1)$-sized cliques ``glued'' together, or more formally when $G$ is of a \textit{treewidth}~$t$, is known as the \textit{junction tree algorithm} \cite{jensen}, which has complexity of counting and sampling that grow exponentially with $t$. Another insight originates from the foundational statistical physics literature of the last century related to a zero-field version of (\ref{eq:zfim}) when $G$ is planar. Onsager \cite{onsager} found a closed-form solution of (\ref{eq:zfim}) in the case of a homogeneous Ising model over an infinite two-dimensional square grid. Kac and Ward \cite{kac-ward} reduced the inference of (\ref{eq:zfim}) over a finite square lattice to computing a determinant. Kasteleyn \cite{kasteleyn} generalized this result to an arbitrary planar graph. Kasteleyn's approach consists of expanding each vertex of $G$ into a gadget and reducing the Ising model inference to the problem of counting perfect matchings over the expanded graph. Kasteleyn's construction was simplified by Fisher in \cite{fisher}. The tightest running time estimate for Kasteleyn's method gives $O(N^\frac32)$. Kasteleyn conjectured, which was later proven in~\cite{gallucio}, that the approach extends to the case of the zero-field Ising model over graphs embedded in a surface of \textit{genus} $g$ with a multiplicative $O(4^g)$ penalty. A slightly different reduction to perfect matching counting \cite{barahona,bieche,schraudolph-kamenetsky} also allows one to implement $O(N^{\frac{3}{2}})$ sampling of planar zero-field Ising models using Wilson's algorithm \cite{k33,wilson}. A $K_{33}$ (Figure \ref{fig:k5}(a)) minor-free extension of planar zero-field inference and sampling was constructed in \cite{k33}. An upper-bound approximation to a general class of inference problems can be built by utilizing the family of tractable spanning Ising submodels---either trees \cite{wainwright} or planar topologies \cite{globerson}. \textbf{Contribution.} In this manuscript, we first describe a new family of zero-field Ising models on graphs that are more general than planar. Given a tree decomposition of such graphs into planar and ``small'' ($O(1)$-sized) components ``glued'' together along sets of at most three vertices, inference and sampling over the new family of models is of polynomial time. We further show that all the $K_5$-minor-free graphs are included in this family and, moreover, their aforementioned tree decomposition can be constructed with $O(N)$ efforts. (See Figure \ref{fig:k5}(a) for an illustration.) This allows us to prove an $O(N^\frac32)$ upper bound on run time complexity of inference and sampling of the $K_5$-free zero-field Ising models. Planar graphs are included in the set of $K_5$-free graphs, which are neither genus- nor treewidth-bounded in general. Second, we show how the newly introduced tractable family of zero-field Ising models allows extension of the approach of \cite{globerson} to an upper-bound log-partition function of arbitrary Ising models. Instead of using planar spanning subgraphs as in \cite{globerson}, we utilize more general (nonplanar) basic tractable elements. Using the methodology of \cite{globerson}, we illustrate the approach through experiments with a nonzero-field Ising model on a square grid for which inference is NP-hard \cite{barahona}. \textbf{Relation to other algorithms.} The result presented in this manuscript is similar to the approach used to count perfect matchings in $K_5$-free graphs \cite{curticapean,straub}. However, we do not use a transition to perfect matching counting as it is typically done in studies of zero-field Ising models over planar graphs~\cite{fisher,kasteleyn,thomas-middleton1}. Presumably, a direct transition to perfect matching counting can be done via a construction of an expanded graph in the fashion of \cite{fisher,kasteleyn}. However, this results in a size increase and, what's more important, there is no direct correspondence between spin configurations and perfect matchings, so sampling is not supported. Our approach can also be viewed as extending results reported in \cite{k33} on the inference and sampling in the $K_{33}$-free zero-field Ising models. In \cite{k33}, $K_{33}$-free graphs are decomposed into planar and $K_5$ components along pairs of vertices, and the whole construction relies on the underlying planar perfect matching model. In this manuscript, we reformulate the $K_{33}$-free construction of \cite{k33} directly in terms of the Ising model bypassing mapping to perfect matchings. Moreover, an extension of the decomposition to gluing over triplets of vertices generalizes the construction, in particular, yielding novel results for efficient inference and learning for the zero-field Ising models over $K_5$-free graphs. \textbf{Structure.} Section \ref{sec:main} formally introduces the concept of the so-called $c$-nice decomposition of graphs and formulates and proves tractability of $c$-nice decomposable zero-field Ising models. Section \ref{sec:dec} introduces basic notations used later in the manuscript. Section \ref{sec:cond} describes a useful technical instrument, called conditioning, which is then used in Section \ref{sec:inf} and Section \ref{sec:samp} to describe algorithms for efficient inference and learning, respectively, of the zero-field Ising models over graphs, which allows for a $c$-nice decomposition, where $c$ is a positive integer. Section \ref{sec:k5} describes an application of the algorithm to the example of the $K_5$-free zero-field Ising models. Section \ref{sec:emp} presents an empirical application of the newly introduced family of tractable models to an upper-bounding log-partition function of a broader family of intractable graphical models (planar nonzero-field Ising models). Section \ref{sec:concl} is reserved for conclusions. \section{Algorithm} \label{sec:main} We commence by introducing the concept of $c$-nice decomposition of a graph and stating the main result on the tractability of the new family of Ising models in subsection \ref{sec:dec}. We introduce a helpful ``conditioning'' machinery in subsection \ref{sec:cond} and then describe the efficient inference (subsection \ref{sec:inf}) and sampling (subsection \ref{sec:samp}) algorithms which constructively prove the statement. \subsection{Decomposition tree and the main result} \label{sec:dec} Throughout the text, we use common graph-theoretic notations and definitions \cite{diestel} and also restate the most important concepts briefly. We mainly follow \cite{curticapean,reed} in the definition of the decomposition tree and its properties sufficient for our goals. Again, we point out that we only consider graphs without loops or multiple edges. The graph is \textit{planar} when it can be drawn on a plane without edge intersections. Graph $G'$ is a \textit{subgraph} of $G$ whenever $V(G') \subseteq V(G)$ and $E(G') \subseteq E(G)$. For two subgraphs $G'$ and $G''$ of $G$, let $G' \cup G'' = (V(G') \cup V(G''), E(G') \cup E(G''))$ (graph \textit{union}). Consider a tree decomposition $\mathcal{T} = \langle T, \mathcal{G} \rangle$ of a graph $G$ into a set of subgraphs $\mathcal{G} \triangleq \{ G_t \}$ of $G$, where $t$ are \textit{nodes} of a tree $T$, that is, $t \in V(T)$. One of the nodes of the tree, $r \in V(T)$, is selected as the root. For each node $t \in V(T)$, its \textit{parent} is the first node on the unique path from $t$ to $r$. $G_{\leq t}$ denotes the graph union of $G_{t'}$ for all the nodes $t'$ in $V(T)$ that are $t$ or its descendants. $G_{\nleq t}$ denotes the graph union of $G_{t'}$ for all the nodes $t'$ in $V(T)$ that are neither $t$ nor descendants of~$t$. For two neighboring nodes of the tree, $t, p \in V(T)$ and $\{ t, p \} \in E(T)$, the set of overlapping vertices of $G_t$ and $G_p$, $K \triangleq V(G_t) \cap V(G_p)$, is called an \textit{attachment set} of~$t$ or~$p$. If $p$ is a parent of~$t$, then $K$ is a \textit{navel} of $t$. We assume that the navel of the root is empty. $\mathcal{T}$ is a \textit{$c$-nice decomposition} of $G$ if the following requirements are satisfied: \begin{enumerate} \item $\forall t \in V(T)$ with a navel $K$, it holds that $K = V(G_{\leq t}) \cap V(G_{\nleq t})$. \item Every attachment set $K$ is of size $0$, $1$, $2$, or $3$. \item $\forall t \in V(T)$, either $| V(G_t) | \leq c$ or $G_t$ is planar. \item If $t \in V(T)$ is such that $| V(G_t) | > c$, addition of all edges of type $e = \{ v, w \}$, where $v, w$ belong to the same attachment set of $t$ (if $e$ is not yet in $E(G_t)$) does not destroy planarity of $G_t$. \end{enumerate} Stating it informally, the $c$-nice decomposition of $G$ is a tree decomposition of $G$ into planar and ``small'' (of size at most $c$) subgraphs $G_t$, ``glued'' via subsets of at most three vertices of $G$. Figure~\ref{fig:k5}(a) shows an example of a $c$-nice decomposition with $c = 8$. There are various similar ways to define a graph decomposition in literature, and the one presented above is customized to include only properties significant for our consecutive analysis. The remainder of this section is devoted to a constructive proof of the following statement. \begin{theorem} \label{th:main} Let $\mathcal{I} = \langle G, 0, J \rangle$ be any zero-field Ising model where there exists a $c$-nice decomposition $\mathcal{T}$ of $G$, where $c$ is an absolute constant. Then, there is an algorithm which, given $\mathcal{I}, \mathcal{T}$ as an input, does two things: (1) finds $Z$ and (2) samples a configuration from $\mathcal{I}$ in time $O( \sum\limits_{t \in V(T)} | V(G_t) |^\frac32 )$. \end{theorem} \begin{figure}[!th] \centering \includegraphics[width=0.9\linewidth]{k5-all} \caption{a) An exemplary graph $G$ and its $8$-nice decomposition $\mathcal{T}$, where $t\in \{1, \cdots, 7\}$ labels nodes of the decomposition tree $T$ and node $4$ is chosen as the root ($r = 4$). Identical vertices of $G$ in its subgraphs $G_t$ are shown connected by dashed lines. Navels of size $1$, $2$, and $3$ are highlighted. Component $G_5$ is nonplanar, and $G_4$ becomes nonplanar when all attachment edges are added (according to the fourth item of the definition of the $c$-nice decomposition). $G_{\leq 3}$ and $G_{\nleq 3}$ are shown with dotted lines. Note that the decomposition is non-unique for the graph. For instance, edges that belong to the attachment set can go to either of the two subgraphs containing this set or even repeat in both. b) Minors $K_5$ and $K_{33}$ are forbidden in the planar graphs. M\"{o}bius ladder and its subgraphs are the only nonplanar graphs allowed in the $8$-nice decomposition of a $K_5$-free graph. c) The left panel is an example of conditioning on three vertices/spins in the center of a graph. The right panel shows a modified graph where the three vertices (from the left panel) are reduced to one vertex, then leading to a modification of the pairwise interactions within the associated zero-field Ising model over the reduced graph. d) Example of a graph that contains $K_5$ as a minor: by contracting the highlighted groups of vertices and deleting the remaining vertices, one arrives at the $K_5$ graph.} \label{fig:k5} \end{figure} \subsection{Inference and sampling conditioned on 1, 2, or 3 vertices/spins} \label{sec:cond} Before presenting the algorithm that proves Theorem \ref{th:main} constructively, let us introduce auxiliary machinery of ``conditioning'', which describes the partition function of a zero-field Ising model over a planar graph conditioned on $1$, $2$, or $3$ spins. Consider a zero-field Ising model $\mathcal{I} = \langle G, 0, J \rangle$ defined over a planar graph $G$. Recall the following result, rigorously proven in \cite[Corollary under Theorem 1]{k33}, which we intend to use in the aforementioned tree decomposition as a black box. \begin{theorem} Given $\mathcal{I} = \langle G, 0, J \rangle$, where $G$ is planar, $Z$ can be found in time $O(N^\frac32)$. Drawing a sample from $\mathcal{I}$ is a task of $O(N^\frac32)$ complexity. \label{th:planar} \end{theorem} Let us now introduce the notion of \textit{conditioning}. Consider a spin configuration $X \in \{ \pm 1 \}^N$, a subset $V' = \{ v^{(1)}, \dots, v^{(\omega)} \} \subseteq V(G)$, and define a \textit{condition} $S = \{ x_{v^{(1)}} = s^{(1)}, \dots, x_{v^{(\omega)}} = s^{(\omega)} \}$ \textit{on} $V'$, where $s^{(1)}, \dots, s^{(\omega)} = \pm 1$ are fixed values. Conditional versions of the probability distribution (\ref{eq:zfim}--\ref{eq:Z}) and the \textit{conditional} partition function become \begin{eqnarray} && \mathbb{P}(X | S) \triangleq \frac{\mathcal{W}(X) \times \mathbbm{1}(X | S)}{Z_{|S}}, \quad \mathbbm{1} (X | S) \triangleq \left\{ \begin{array} {cc}1, & x_{v^{(1)}} = s^{(1)}, \dots, x_{v^{(\omega)}} = s^{(\omega)} \\ 0, & \mbox{otherwise} \end{array} \right. , \label{eq:zfim_cond} \\ && \text{where}~Z_{|S} \triangleq \sum_{X \in \{\pm 1\}^N} \mathcal{W}(X) \times \mathbbm{1} (X | S). \label{eq:Z_cond} \end{eqnarray} \begin{comment} Let us now extend the notion of the partition function as follows. Let $P: \{ \pm 1 \}^N \to \{ \text{false}{\color{red} =0}, \text{true}{\color{red}=1} \}$ be a predicate of a spin configuration. Then $Z_{\,| \, P(S)}$ (\textit{conditional partition function}) denotes the following quantity: \begin{equation} Z_{ \,| \, P(S)} \triangleq Z \cdot \mathbb{P} (P(S)) = \sum_{X, \, P(X)} \exp\left( \sum_{ e = \{ v, w \} \in E(G)} J_e x_v x_w \right) \end{equation} \end{comment} Notice that when $\omega = 0$, $S = \{ \}$ and (\ref{eq:zfim_cond}--\ref{eq:Z_cond}) is reduced to (\ref{eq:zfim}--\ref{eq:Z}). The subset of $V(G)$ is \textit{connected} whenever the subgraph, induced by this subset is connected. Theorem \ref{th:planar} can be extended as follows (a formal proof can be found in the supplementary materials). \begin{lemma} \label{lemma:cond} Given $\mathcal{I} = \langle G, 0, J \rangle$ where $G$ is planar and a condition $S$ on a connected subset $V' \subseteq V(G)$, $| V' | \leq 3$, computing the conditional partition function $Z_{|S}$ and sampling from $\mathbb{P}(X | S)$ are tasks of $O(N^\frac32)$ complexity. \end{lemma} We omit here the tedious proof of the Lemma, also mentioning that the conditioning algorithm proving the Lemma takes the subset of connected vertices and ``collapses'' them into a single vertex. The graph remains planar and the task is reduced to conditioning on one vertex, which is an elementary operation given in Theorem \ref{th:planar}. (See Figure \ref{fig:k5}(c) for an illustration.) \subsection{Inference algorithm} \label{sec:inf} This subsection constructively proves the inference part of Theorem \ref{th:main}. For each $t \in V(T)$, let $\mathcal{I}_{\leq t} \triangleq \langle G_{\leq t}, 0, \{ J_e \, | \, e \in E(G_{\leq t}) \subseteq E(G) \} \rangle$ denote a zero-field Ising \textit{submodel} \textit{induced} by $G_{\leq t}$. Denote the partition function and subvector of $X$ related to $\mathcal{I}_{\leq t}$ as $Z^{\leq t}$ and $X_{\leq t} \triangleq \{ x_v | v \in V(G_{\leq t}) \}$, respectively. Further, let $K$ be $t$'s navel and let $S = \{ \forall v \in K: x_v = s^{(v)} \}$ denote some condition on $K$. Recall that $| K | \leq 3$. For each $t$, the algorithm computes conditional partition functions $Z^{\leq t}_{| S}$ for all choices of condition spin values $\{ s^{(v)} = \pm 1 \}$. Each $t$ is processed only when its children have already been processed, so the algorithm starts at the leaf and ends at the root. If $r \in G(T)$ is a root, its navel is empty and $G_{\leq r} = G$, hence $Z = Z^{\leq r}_{| \{ \}}$ is computed after $r$'s processing. Suppose all children of $t$, $c_1, ..., c_m \in V(T)$ with navels $K_1, ..., K_m \subseteq V(G_t)$ have already been processed, and now $t$ itself is considered. Denote a spin configuration on $G_t$ as $Y_t \triangleq \{ y_v = \pm 1 \, | \, v \in V(G_t) \}$. $\mathcal{I}_{\leq c_1}, ..., \mathcal{I}_{\leq c_m}$ are $\mathcal{I}_{\leq t}$'s submodels induced by $G_{\leq c_1}, ..., G_{\leq c_m}$, which can only intersect at their navels in $G_t$. Based on this, one states the following dynamic programming relation: \begin{equation} Z^{\leq t}_{| S} = \sum_{Y_t \in \{ \pm 1 \}^{| V(G_t) |} } \mathbbm{1} (Y_t | S) \exp \left( \sum_{e = \{ v, w \} \in E(G_t)} J_e y_v y_w \right) \cdot \prod_{i = 1}^m Z^{\leq c_i}_{| S_i [ Y_t ]}. \label{eq:dp} \end{equation} Here, $S_i [ Y_t ]$ denotes a condition $\{ \forall v \in K_i: x_v = y_v \}$ on $K_i$. The goal is to efficiently perform summation in~\eqref{eq:dp}. Let $I^{(0)}, I^{(1)}, I^{(2)}, I^{(3)}$ be a partition of $\{ 1, ..., m \}$ by navel sizes. Figure \ref{fig:infsamp}(a,b) illustrates inference in $t$. \begin{enumerate}[wide, labelwidth=!, labelindent=0pt] \item \textbf{Navels of size 0, 1.} Notice that if $i \in I^{(0)}$, then $Z^{\leq c_i}_{| \{ \}} = Z^{\leq c_i}$ is constant, which was computed before. The same is true for $i \in I^{(1)}$ and $Z^{\leq c_i}_{| S^{(i)} [Y_t]} = \frac{1}{2} Z^{\leq c_i}$. \item \textbf{Navels of size 2.} Let $i \in I^{(2)}$ denote $K_i = \{ u^i, q^i \}$ and simplify notation $Z^{\leq c_i}_{y_1, y_2} \triangleq Z^{\leq c_i}_{x_{u^i} = y_1, x_{q^i} = y_2}$ for convenience. Notice that $Z^{\leq c_i}_{|S_i [ Y_t ]}$ is strictly positive, and due to the zero-field nature of $\mathcal{I}_{\leq c_i}$, one finds $Z^{\leq c_i}_{| +1, +1} = Z^{\leq c_i}_{| -1, -1}$ and $Z^{\leq c_i}_{| +1, -1} = Z^{\leq c_i}_{| -1, +1}$. Then, one arrives at $\log Z^{\leq c_i}_{| S_i [ Y_t ]} = A_i + B_i y_{u^i} y_{q^i} $, where $A_i \triangleq \log Z^{\leq c_i}_{| +1, +1} + \log Z^{\leq c_i}_{| +1, -1}$ and $B_i \triangleq \log Z^{\leq c_i}_{| +1, +1} - \log Z^{\leq c_i}_{| +1, -1}$. \item \textbf{Navels of size 3.} Let $i \in I^{(3)}$, and as above, denote $K_i = \{ u^i, q^i, h^i \}$ and $Z^{\leq c_i}_{y_1, y_2, y_3} \triangleq Z^{\leq c_i}_{x_{u^i} = y_1, x_{q^i} = y_2, x_{h^i} = y_3}$. \begin{figure} \centering \includegraphics[width=\linewidth]{inf-and-samp} \caption{a) Example of inference at node $t$ with children $c_1, c_2, c_3, c_4$. Navels $K_1 = \{ u^1, q^1, h^1 \}, K_2 = \{ u^2, q^2, h^2 \}, K_3 = \{ u^2, q^2 \}, K_4 = \{ u^4 \}$, and $K = \{ u, q, h \}$ are highlighted. Fragments of $\mathcal{I}_{\leq c_i}$ are shown with dotted lines. Here, $I^{(0)} = \varnothing, I^{(1)} = \{ 4 \}, I^{(2)} = \{ 3 \}, \text{and}~ I^{(3)} = \{ 1, 2 \}$, indicating that one child is glued over one node, one child is glued over two nodes, and two children are glued over three nodes. b) ``Aggregated'' Ising model $\mathcal{I}_t$ and its pairwise interactions are shown. Both c) and d) illustrate sampling over $\mathcal{I}_t$. One sample spins in $\mathcal{I}_t$ conditioned on $S^{(t)}$ and then repeats the procedure at the child nodes.} \label{fig:infsamp} \end{figure} Due to the zero-field nature of $\mathcal{I}_{\leq c_i}$, it holds that $Z^{\leq c_i}_{| +1, y_2, y_3} = Z^{\leq c_i}_{| -1, y_2, y_3}$. Observe that there are such $A_i, B_i, C_i, D_i$ that $ \log Z^{\leq c_i}_{| y_1, y_2, y_3} = A_i + B_i y_1 y_2+ C_i y_1 y_3 + D_i y_2 y_3$ for all $y_1, y_2, y_3=\pm 1$, which is guaranteed since the following system of equations has a solution: \begin{equation} \begin{bmatrix} \log Z^{\leq c_i}_{|+1, +1, +1} \\ \log Z^{\leq c_i}_{|+1, +1, -1 } \\ \log Z^{\leq c_i}_{|+1, -1, +1} \\ \log Z^{\leq c_i}_{|+1, -1, -1} \end{bmatrix} = \begin{bmatrix} +1 & +1 & +1 & +1 \\ +1 & +1 & -1 & -1 \\ +1 & -1 & +1 & -1 \\ +1 & -1 & -1 & +1 \end{bmatrix} \times \begin{bmatrix} A_i \\ B_i \\ C_i \\ D_i \end{bmatrix}. \label{eq:3vsystem} \end{equation} \end{enumerate} Considering three cases, one rewrites Eq.~(\ref{eq:dp}) as \begin{align} Z^{\leq t}_{| S} &= M \cdot \sum_{Y_t} \mathbbm{1} (Y_t | S) \exp \biggl( \sum_{e = \{ v, w \} \in E(G_t)} J_e y_v y_w + \sum_{i \in I^{(2)} \cup I^{(3)}} B_i y_{u^i} y_{q^i} \nonumber \\ &+ \sum_{i \in I^{(3)}} ( C_i y_{u^i} y_{h^i} + D_i y_{q^i} y_{h^i}) \biggr), \label{eq:dp4} \end{align} where $M \triangleq 2^{- | I^{(1)} |} \cdot \left( \prod_{i \in I^{(0)} \cup I^{(1)}} Z^{\leq c_i} \right) \cdot \exp( \sum_{i \in I^{(2)} \cup I^{(3)}} A_i)$. The sum in Eq.~(\ref{eq:dp4}) is simply a conditional partition function of a zero-field Ising model $\mathcal{I}_t$ defined over a graph $G_t$ with pairwise interactions of $\mathcal{I}$ adjusted by the addition of $B_i, C_i, \text{and}~ D_i$ summands at the appropriate navel edges (if a corresponding edge is not present in $G_t$, it has to be added). If $| V(G_t) | \leq c$, then (\ref{eq:dp4}) is computed a maximum of four times (depending on navel size) by brute force ($O(1)$ time). Otherwise, if $K$ is a disconnected set in $G_t$, we add zero-interaction edges inside it to make it connected. Possible addition of edges inside $K, K_1, \dots, K_m$ doesn't destroy planarity according to the fourth item in the definition of the $c$-nice decomposition above. Finally, we compute (\ref{eq:dp4}) using Lemma \ref{lemma:cond} in time $O( | V(G_t) |^\frac32 )$. The inference part of Theorem \ref{th:main} follows directly from the procedure just described. \begin{figure} \centering \includegraphics[width=0.9\linewidth]{grid} \caption{Construction of graphs used for approximate inference on a rectangular lattice. For better visualization, vertices connected to an apex are colored white. a) $G'$ graph. b) One of planar $G^{(r)}$ graphs used in \protect\cite{globerson}. Such ``separator'' pattern is repeated for each column and row, resulting in $2(H - 1)$ graphs in $\{ G^{(r)} \}$. In addition, \protect\cite{globerson} adds an \textit{independent variables} graph where only apex edges are drawn. c) A modified ``separator'' pattern we propose. Again, the pattern is repeated horizontally and vertically resulting in $2(H - 2)$ graphs $+$ independent variables graph. This pattern covers more magnetic fields and connects separated parts. Dashed edges indicate the structure of $10$-nice decomposition used for inference. (Nonplanar node of size $10$ is illustrated on the right.) } \label{fig:grid} \end{figure} \subsection{Sampling algorithm} \label{sec:samp} Next, we address the sampling part of Theorem \ref{th:main}. We extend the algorithm from section \ref{sec:inf} so that it supports efficient sampling from $\mathcal{I}$. Assume that the inference pass through $T$ (from leaves to root) has been done so that $\mathcal{I}_t$ for all $t \in V(T)$ are computed. Denote $X_t \triangleq \{ x_v \, | \, v \in V(G_t) \}$. The sampling algorithm runs backwards, first drawing spin values $X_r$ at the root $r$ of $T$ from the marginal distribution $\mathbb{P}(X_r)$, and then processing each node $t$ of $T$ after its parent $p$ is processed. Processing consists of drawing spins $X_t$ from $\mathbb{P}(X_t \, | \, X_p) = \mathbb{P}(X_t \, | \, X^{(t)} \triangleq \{ x_v \, | \, v \in K \})$, where $K$ is a navel of $t$. This marginal-conditional scheme generates the correct sample $X$ of spins over $G$. Let $\mathbb{P}_{\leq t} (X_{\leq t})$ define a spin distribution of $\mathcal{I}_{\leq t}$. Because the Ising model is an example of Markov Random Field, it holds that $\mathbb{P}_{\leq t} (X_{\leq t} \, | \, X^{(t)} ) = \mathbb{P} (X_{\leq t} \, | \, X^{(t)} )$. We further derive \begin{align} &\mathbb{P}(X_t \, | \, X^{(t)}) = \mathbb{P}_{\leq t}(X_t \, | \, X^{(t)}) = \frac{1}{Z^{\leq t}} \sum_{X_{\leq t}\setminus X_t} \exp \biggl( \sum_{e = \{ v, w \} \in E(G_{\leq t})} J_e x_v x_w \biggr) \nonumber \\ &= \frac{1}{Z^{\leq t}} \cdot \exp \biggl( \sum_{e = \{ v, w \} \in E(G_t)} J_e x_v x_w \biggr) \cdot \prod_{i = 1}^m Z^{\leq c_i}_{|S_i [X_t]} \nonumber \\ &\propto \exp \biggl( \sum_{e = \{ v, w \} \in E(G_t)} J_e x_v x_w + \sum_{i \in I^{(2)} \cup I^{(3)}} B_i x_{u^i} x_{q^i} + \sum_{i \in I^{(3)}} ( C_i x_{u^i} x_{h^i} + D_i x_{q^i} x_{h^i}) \biggr). \end{align} In other words, sampling from $\mathbb{P}(X_t \, | \, X^{(t)})$ is reduced to sampling from $\mathcal{I}_t$ conditional on spins $X^{(t)}$ in the navel $K$. It is done via brute force if $| V(G_t) | \leq c$; otherwise, Lemma \ref{lemma:cond} allows one to draw $X_t$ in $O(| V(G_t) |^\frac32)$, since $| K | \leq 3$. Sampling efforts cost as much as inference, which concludes the proof of Theorem \ref{th:main}. Figure \ref{fig:infsamp}(c,d) illustrates sampling in $t$. \begin{figure} \centering \includegraphics[width=0.9\linewidth]{plots.pdf} \caption{Comparison of tree-reweighted approximation (TRW), planar spanning graph (PSG), and decomposition-based spanning graph (DSG) approaches. The first plot is for normalized log-partition error, the second is for error in pairwise marginals, and the third is for error in singleton central marginal. Standard errors over $100$ trials are shown as error bars. An asterisk ``*'' indicates the statistically significant improvement of DSG over PSG, with a $p$-value smaller than $0.01$ according to the Wilcoxon test with the Bonferroni correction \protect\cite{wilcoxon}. } \label{fig:plot} \end{figure} \section{Application: \texorpdfstring{$K_5$}--free zero-field Ising models} \label{sec:k5} \textit{Contraction} is an operation of removing two adjacent vertices $v$ and $u$ (and all edges incident to them) from the graph and adding a new vertex $w$ adjacent to all neighbors of $v$ and $u$. For two graphs $G$ and $H$, $H$ is $G$'s \textit{minor}, if it is isomorphic to a graph obtained from $G$'s subgraph by a series of contractions. $G$ is \textit{$H$-free}, if $H$ is not $G$'s minor. We especially focus on the case when $H = K_5$ (Figure \ref{fig:k5}(d)). Planar graphs are a special type of $K_5$-free graphs, according to Wagner's theorem \cite[Chapter 4.4]{diestel}. Moreover, some nonplanar graphs are $K_5$-free, for example, $K_{33}$ (Figure \ref{fig:k5}(b)). $K_5$-free graphs are neither genus-bounded (a disconnected set of $g$ $K_{33}$ graphs is $K_5$-free and has a genus of $g$ \cite{battle}) and is not treewidth-bounded (planar square grid of size $t \times t$ is $K_5$-free and has a treewidth of $t$ \cite{bodlaender}). \begin{theorem} \label{th:k5dec} Let $G$ be a $K_5$-free graph of size $N$ with no loops or multiple edges. Then, the $8$-nice decomposition $\mathcal{T}$ of $G$ exists and can be computed in time $O(N)$. \end{theorem} \begin{proof}[Proof (Sketch).] An equivalent decomposition is constructed in \cite{reed} in time $O(N)$. We put a formal proof in the Supplementary materials. \end{proof} \begin{remark} The $O(N)$ construction time of $\mathcal{T}$ guarantees that $\sum_{t \in V(T)} | V(G_t) | = O(N)$. All nonplanar components in $\mathcal{T}$ are isomorphic to the M\"{o}bius ladder (Figure \ref{fig:k5}(b)) or its subgraph. \end{remark} The graph in Figure \ref{fig:k5}(a) is actually $K_5$-free. Theorems \ref{th:main} and \ref{th:k5dec} allow us to conclude: \begin{theorem} \label{th:inf} Given $\mathcal{I} = \langle G, 0, J \rangle$ with $K_5$-free $G$ of size $N$, finding $Z$ and sampling from $\mathcal{I}$ take $O(N^\frac32)$ total time. \end{theorem} \begin{proof} Finding $8$-nice $\mathcal{T}$ for $G$ takes $O(N)$ time (Theorem \ref{th:k5dec}). Provided with $\mathcal{T}$, the complexity is \begin{equation*} O \left(\sum_{t \in V(T)} | V(G_t) |^\frac32 \right) = O \left( (\sum_{t \in V(T)} | V(G_t) | )^\frac32 \right) = O(N^\frac32), \end{equation*} where we apply convexity of $f(z) = z^\frac32$ for $z \geq 0$ and the Remark after Theorem \ref{th:k5dec}. \end{proof} \section{Application: approximate inference of square-grid Ising model} \label{sec:emp} In this section, we consider $\mathcal{I} = \langle G, \mu, J \rangle$ such that $G$ is a square-grid graph of size $H \times H$. Finding $Z (G, \mu, J)$ for arbitrary $\mu$, $J$ is an NP-hard problem \cite{barahona} in such a setting. Construct $G'$ by adding an \textit{apex} vertex connected to all $G$'s vertices by edge (Figure \ref{fig:grid}(a)). Now it can easily be seen that $Z (G, \mu, J) = \frac{1}{2} Z(G', 0, J' = (J_\mu \cup J))$, where $J_\mu = \mu$ are interactions assigned for apex edges. Let $\{ G^{(r)} \}$ be a family of spanning graphs ($V(G^{(r)}) = V(G')$, $E(G^{(r)}) \subseteq E(G')$) and $J^{(r)}$ be interaction values on $G^{(r)}$. Also, denote $\hat{J}^{(r)} = J^{(r)} \cup \{ 0, e \in E(G') \setminus E(G^{(r)}) \}$. Assuming that $\log Z (G^{(r)}, 0, J^{(r)})$ are tractable, the convexity of $\log Z (G', 0, J')$ allows one to write the following upper bound: \begin{equation} \label{eq:ub} \log Z (G', 0, J') \leq \min_{\substack{\rho(r) \geq 0, \sum_r \rho(r) = 1 \\ \{ J^{(r)} \}, \sum_r \rho(r) \hat{J}^{(r)} = J'}} \sum_r \rho(r) \log Z(G^{(r)}, 0, J^{(r)}). \end{equation} After graph set $\{ G^{(r)} \}$ has been fixed, one can numerically optimize the right-hand side of (\ref{eq:ub}), as shown in \cite{globerson} for planar $G^{(r)}$. The extension of the basic planar case is straightforward and can be found in the Supplementary materials for convenience. We also put the description of marginal probabilities approximation suggested in \cite{globerson,wainwright}. The choice for a planar spanning graph (PSG) family $\{ G^{(r)} \}$ of \cite{globerson} is illustrated in Figure \ref{fig:grid}(b). A tractable decomposition-based extension of the planar case presented in this manuscript suggests a more advanced construction---decomposition-based spanning graphs (DSG) (Figure \ref{fig:grid}(c)). We compare performance of both PSG and DSG approaches as well as the performance of tree-reweighted approximation (TRW) \cite{wainwright} in the following setting of \textit{Varying Interaction}: $\mu \sim \mathcal{U}(-0.5, 0.5)$, $J \sim \mathcal{U}(-\alpha, \alpha)$, where $\alpha \in \{ 1, 1.2, 1.4, \dots, 3 \}$. We opt optimize for grid size $H = 15$ ($225$ vertices, $420$ edges) and compare upper bounds and marginal probability approximations (superscript \textit{alg}) with exact values obtained using a junction tree algorithm \cite{jensen} (superscript \textit{true}). We compute three types of error: \begin{enumerate} \item normalized log-partition error $\frac{1}{H^2} (\log Z^{alg} - \log Z^{true})$, \item error in pairwise marginals $\frac{1}{| E(G) |} \sum_{e = \{ v, w \} \in E(G)} | \mathbb{P}^{alg} (x_v x_w = 1) - \mathbb{P}^{true} (x_v x_w = 1) |$, and \item error in singleton central marginal $| \mathbb{P}^{alg} (x_v = 1) - \mathbb{P}^{true} (x_v = 1)|$ where $v$ is a vertex of $G$ with coordinates $(8, 8)$. \end{enumerate} We average results over $100$ trials (see Fig.~\ref{fig:plot}).\footnote{Hardware used: 24-core Intel\textregistered \, Xeon\textregistered \, Gold 6136 CPU @ 3.00 GHz}\footnote{Implementation of the algorithms is available at \url{https://github.com/ValeryTyumen/planar\_ising}} We use the same quasi-Newton algorithm \cite{bertsekas} and parameters when optimizing (\ref{eq:ub}) for PSG and DSG, but for most settings, DSG outperforms PSG and TRW. Cases with smaller TRW error can be explained by the fact that TRW implicitly optimizes~\eqref{eq:ub} over the family of \textit{all} spanning trees which can be exponentially big in size, while for PSG and DSG we only use $O(H)$ spanning graphs. Because PSG and DSG approaches come close to each other, we additionally test for each value of $\alpha$ on each plot, whether the difference $err_{PSG} - err_{DSG}$ is bigger than zero. We apply a one-sided Wilcoxon's test \cite{wilcoxon} together with the Bonferroni correction because we test $33$ times \cite{bonferroni}. In most settings, the improvement is statistically significant (Figure \ref{fig:plot}). \section{Conclusion} \label{sec:concl} In this manuscript, we introduce a new family of zero-field Ising models composed of planar components and graphs of $O(1)$ size. For these models, we describe a polynomial algorithm for exact inference and sampling provided that the decomposition tree is also in the input. A theoretical application is $O(N^\frac32)$ inference and sampling algorithm for $K_5$-free zero-field Ising models---a superset of planar zero-field models that is neither treewidth- nor genus-bounded. A practical application is an improvement of an approximate inference scheme for arbitrary topologies based on planar spanning graphs \cite{globerson} but using tractable spanning decomposition-based graphs instead of planar. We leave the algorithm as it is but substitute planar graphs with a family of spanning decomposition-based graphs that are tractable. This alone gives a tighter upper bound on the true partition function and a more precise approximation of marginal probabilities. \section{Acknowledgements} This work was supported by the U.S. Department of Energy through the Los Alamos National Laboratory as part of LDRD and the DOE Grid Modernization Laboratory Consortium (GMLC). Los Alamos National Laboratory is operated by Triad National Security, LLC, for the National Nuclear Security Administration of U.S. Department of Energy (Contract No. 89233218CNA000001). \bibliographystyle{chicago}
{'timestamp': '2019-06-18T02:03:12', 'yymm': '1906', 'arxiv_id': '1906.06431', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06431'}
arxiv
\section{Introduction} \label{intro} Computer Generated Imagery (CGI) has become an inextricable part of the entertainment industry due to its ability to produce high quality results in a controllable manner. One very important element of CGI is facial animation because the face is capable of conveying a plethora of information not only about the character but also about the scene in general (\eg tension, danger). The problem of generating realistic talking heads is multifaceted, requiring high-quality faces, lip movements synchronized with the audio, and plausible facial expressions. This is especially challenging because humans are adept at picking up subtle abnormalities in facial motion and audio-visual synchronization. Facial synthesis in CGI is traditionally performed using face capture methods, which have seen drastic improvement over the past years and can produce faces that exhibit a high level of realism. However, these approaches require expensive equipment and significant amounts of labour, which is why CGI projects are still mostly undertaken by large studios. In order to drive down the cost and time required to produce high quality CGI researchers are looking into automatic face synthesis using machine learning techniques. Of particular interest is speech-driven facial animation since speech acoustics are highly correlated with facial movements \cite{Yehia1998QuantitativeBehavior}. These systems could simplify the film animation process through automatic generation from the voice acting. They can also be applied in post-production to achieve better lip-synchronization in movie dubbing. Moreover, they can be used to generate parts of the face that are occluded or missing in a scene. Finally, this technology can improve band-limited visual telecommunications by either generating the entire visual content based on the audio or filling in dropped frames. The majority of research in this domain has focused on mapping audio features (\eg MFCCs) to visual features (\eg landmarks, visemes) and using computer graphics (CG) methods to generate realistic faces \cite{Karras2017}. Some methods avoid the use of CG by selecting frames from a person-specific database and combining them to form a video \cite{Bregler1997, Suwajanakorn2017}. Regardless of which approach is adopted these methods are subject dependent and are often associated with a considerable overhead when transferring to new speakers. Subject independent approaches have been proposed that transform audio features to video frames \cite{Chung2017, Chen2018LipGlance}. However, most of these methods restrict the problem to generating only the mouth. Even techniques that generate the entire face are primarily focused on obtaining realistic lip movements, and typically neglect the importance of generating facial expressions. Natural facial expressions play a crucial role in producing truly realistic characters and their absence creates an unsettling feeling for many viewers. This lack of expressions is a clear tell-tale sign of generated videos which is often exploited by systems such as the one proposed in \cite{LiInBlinking}, which exposes synthetic faces based on the existence and frequency of blinks. Some methods generate frames based solely on present information \cite{Chung2017, Chen2018LipGlance}, without taking into account the dynamics of facial motion. However, generating natural sequences, which are characterized by a seamless transition between frames, can be challenging when using this static approach. Some video generation methods have dealt with this problem by generating the entire sequence at once \cite{Vondrick2016} or in small batches \cite{Saito2016}. However, this introduces a lag in the generation process, prohibiting their use in real-time applications and requiring fixed length sequences for training. In this work we propose a temporal generative adversarial network (GAN)\footnote{Videos and models are available on the following website: \\ \url{https://sites.google.com/view/facial-animation}}, capable of generating a video of a talking head from an audio signal and a single still image (see \figref{fig:1}). Our model builds on the system proposed in \cite{Vougioukas2018End-to-EndGANs} which uses separate discriminators at the frame and sequence levels to generate realistic videos. The frame-level discriminator ensures that generated frames are sharp and detailed, whereas the temporal discriminator is responsible for audio visual correspondence and generating realistic facial movements. During training the discriminator learns to differentiate real and fake videos based on synchrony or the presence of natural facial expressions. Although the temporal discriminator helps with the generation of expressions and provides a small improvement in audio-visual correspondence, there is no way of ensuring that both these aspects are captured in the video. To solve this problem we propose using 2 temporal discriminators to enforce audio-visual correspondence and realistic facial movements on the generated videos. By separating these two tasks, which were undertaken by a single discriminator in \cite{Vougioukas2018End-to-EndGANs}, we are able to explicitly focus on audio-visual synchronization through a synchronisation discriminator trained to detect audio-visual misalignment. Furthermore, isolating expressions from synchronisation further encourages the generation of spontaneous facial expressions, such as blinks. \begin{figure} \includegraphics[width=\columnwidth]{images/Fig1.pdf} \caption{The proposed end-to-end face synthesis model, capable of producing realistic sequences of faces using one still image and an audio track containing speech. The generated sequences exhibit smoothness and natural expressions such as blinks and frowns.} \label{fig:1} \end{figure} We also present a comprehensive assessment of the performance of our method. This is done using a plethora of quantitative measures and an in depth analysis that is missing from previous studies. Our model is trained and evaluated on the GRID \cite{Cooke2006}, TCD TIMIT \cite{Harte2015}, CREMA-D \cite{Cao2014CREMA-D:Dataset} and LRW \cite{Chung16} datasets. The frame quality is measured using well-established reconstruction and sharpness metrics. Additionally, we use lip reading systems to verify the accuracy of the spoken words and face verification to ensure that the identity is correctly captured and maintained throughout the sequence. Furthermore, we examine the audio-visual correspondence in produced videos by using a recent speech synchronization detection method. Finally, using a blink detector we measure the number of blinks on the generated videos as well as the blink duration. This work provides an in-depth look at our method, examining how each element affects the quality of the video. The contribution of each discriminator in our GAN is quantified using the aforementioned metrics through an ablation study performed on the GRID \cite{Cooke2006} dataset. Furthermore, we examine the latent space in order to determine how well our system encodes the speaker identity. Moreover, we analyze the characteristics of the spontaneous expressions on videos generated using our method and compare with those of real videos. Finally, we present the results of an online Turing test, where users are shown a series of generated and real videos and are asked to identify the real ones. \section{Related Work} \label{sec:related} The problem of speech-driven video synthesis is not new in computer vision and in fact, has been a subject of interest for decades. Yehia \etal \cite{Yehia1998QuantitativeBehavior} were first to investigate the relationship between acoustics, vocal-tract and facial motion, discovering a strong correlation between visual and audio features and a weak coupling between head motion and the fundamental frequency of the speech signal \cite{Yehia2002LinkingAcoustics}. These findings have encouraged researchers to find new ways to model the audio-visual relationship. The following sections present the most common methods used in each modelling approach. \subsection{Visual Feature Selection and Blending} \label{sec:vis_feat_selection} The relationship between speech and facial motion has been exploited by some CG methods, which assume a direct correspondence between basic speech and video units. Cao \etal \cite{Cao2005ExpressiveAnimation} build a graph of visual representations called \textit{animes} which correspond to audio features. The graph is searched in order to find a sequence that best represents a given utterance under certain co-articulation and smoothness constraints. Additionally, this system learns to detect the emotion of the speech and adjust the \textit{animes} accordingly to produce movements on the entire face. The final result is obtained by time-warping the \textit{anime} sequence to match the timing of the spoken utterance and blending for smoothness. Such methods use a small set of visual features and interpolate between key frames to achieve smooth movement. This simplification of the facial dynamics usually results in unnatural lip movements, which is why methods that attempt to model the facial dynamics are preferred over these approaches. \subsection{Synthesis Based on Hidden Markov Models} \label{sec:hmm} Some of the earliest methods for facial animation relied on Hidden Markov Models (HMMs) to capture the dynamics of the video and speech sequences. Simons and Cox \cite{Simons1990} used vector quantization to achieve a compact representation of video and audio features, which were used as the states for their fully connected Markov model. The Viterbi algorithm was used to recover the most likely sequence of mouth shapes for a speech signal. A similar approach is used in \cite{Yamamoto1998} to estimate the sequence of lip parameters. Finally, the {\em Video Rewrite} method \cite{Bregler1997} relies on the same principles to obtain a sequence of triphones, which are used to look up mouth images from a database. The final result is obtained by time-aligning the images to the speech and then spatially aligning and stitching the jaw sections to the background face. Since phonemes and visemes do not have a one-to-one correspondence some HMM-based approaches replace the single Markov chain approach with a multi-stream approach. Xie \etal \cite{Xie2007AAnimation} propose a coupled HMM to model the audio-visual dependencies and compare the performance of this model to other single and multi-stream HMM architectures. \subsection{Synthesis Based on Deep Neural Networks} \label{sec:deep_neural_networks} Although HMMs were initially preferred to neural networks due to their explicit breakdown of speech into intuitive states, recent advances in deep learning have resulted in neural networks being used in most modern approaches. Like past attempts, most of these methods aim at performing a feature-to-feature translation. A typical example of this, proposed in \cite{Taylor2017}, uses a deep neural network (DNN) to transform a phoneme sequence into a sequence of shapes for the lower half of the face. Using phonemes instead of raw audio ensures that the method is subject independent. Most deep learning approaches use convolutional neural networks (CNN) due to their ability to efficiently capture useful features in images. Karras \etal \cite{Karras2017} use CNNs to transform audio features to 3D meshes of a specific person. This system is conceptually broken into sub-networks responsible for capturing articulation dynamics and estimating the 3D points of the mesh. Analogous approaches,which are capable of generating facial descriptors from speech using recurrent neural networks (RNNs) have been proposed in \cite{Fan2015, Suwajanakorn2017, Pham2017Speech}. In particular, the system proposed in \cite{Suwajanakorn2017} uses Long Short Term Memory (LSTM) cells to produce mouth shapes from Mel-Frequency Cepstral Coefficients (MFCCs). For each generated mouth shape a set of best matching frames is found from a database and used to produce mouth images. These mouth shapes are blended with the frames of a real target video to produce very realistic results. Although visual features such as mouth shapes and 3D meshes are very useful for producing high quality videos they are speaker specific. Therefore, methods that rely on them are subject dependent and require additional retraining or re-targeting steps to adapt to new faces. For this reason methods like the one proposed in \cite{Zhou2018VisemeNet:Animation} use speaker independent features such as visemes and Jaw and Lip (JALI) parameters. Finally, Chung {\em et al.} \cite{Chung2017} proposed a CNN applied on MFCCs that generates subject independent videos from an audio clip and a still frame. The method uses an $L_1$ loss at the pixel level resulting in blurry frames, which is why a deblurring step is also required. Secondly, this loss at the pixel level penalizes any deviation from the target video during training, providing no incentive for the model to produce spontaneous expressions and resulting in faces that are mostly static except for the mouth. \subsection{GAN-Based Video Synthesis} \label{sec:gans} The recent introduction of GANs in \cite{Goodfellow2014} has shifted the focus of the machine learning community to generative modelling. GANs consist of two competing networks: a generative network and a discriminative network. The generator's goal is to produce realistic samples and the discriminator's goal is to distinguish between the real and generated samples. This competition eventually drives the generator to produce highly realistic samples. GANs are typically associated with image generation since the adversarial loss produces sharper, more detailed images compared to $L_1$ and $L_2$ losses. However, GANs are not limited to these applications and can be extended to handle videos \cite{Mathieu2015, Li2017, Vondrick2016, Tulyakov2017}. Straight-forward adaptations of GANs for videos are proposed in \cite{Vondrick2016, Saito2016}, replacing the 2D convolutional layers with 3D convolutional layers. Using 3D convolutions in the generator and discriminator networks is able to capture temporal dependencies but requires fixed length videos. This limitation was overcome in \cite{Saito2016} but constraints need to be imposed in the latent space to generate consistent videos. CNN based GAN approaches have been used for speech to video approaches such as the one proposed in \cite{zhou2019talking}. The {\em MoCoGAN} system proposed in \cite{Tulyakov2017} uses an RNN-based generator, with separate latent spaces for motion and content. This relies on the empirical evidence shown in \cite{Radford2015} that GANs perform better when the latent space is disentangled. {\em MoCoGAN} uses a 2D and 3D CNN discriminator to judge frames and sequences respectively. A sliding window approach is used so that the 3D CNN discriminator can handle variable length sequences. Furthermore, the GAN-based system proposed in \cite{Pham2018GenerativeNetwork} uses Action Unit (AU) coefficients to animate a head. A similar approach is used in the GANimation model proposed in \cite{pumarola2018ganimation}. These approaches can be combined with speech-driven animation methods \cite{Pham2017Speech} that produce AU coefficients which drive facial expressions from speech. GANs have also been used in a variety of cross-modal applications, including text-to-video and audio-to-video. The text-to-video model proposed in \cite{Li2017} uses a combination of variational auto encoders (VAE) and GANs in its generating network and a 3D CNN as a sequence discriminator. Finally, Chen {\em et al.} \cite{Chen2017} propose a GAN-based encoder-decoder architecture that uses CNNs in order to convert audio spectrograms to frames and vice versa. This work is extended in \cite{Chen_2019_CVPR}, using an attention mechanism which helps the network focus on frame regions that correlate highly with the audio. However as a result this method neglects other areas such as the brow and eyes. \section{Speech-Driven Facial Synthesis} \label{sec:method} The proposed architecture for speech-driven facial synthesis is shown in \figref{fig:model_block}. The system consists of a temporal generator and multiple discriminators, each of which evaluates the generated sequence from a different perspective. The capability of the generator to capture various aspects of natural sequences is proportional to the ability of each discriminator to discern videos based on them. \begin{figure}[t] \centering \includegraphics[width=0.9\columnwidth]{images/model_block_journal.pdf} \caption{The deep model for speech-driven facial synthesis. It uses 3 discriminators to incorporate different aspects of a realistic video.} \label{fig:model_block} \end{figure} \subsection{Generator} \label{sec:generator} The generator accepts as input a single image and an audio signal, which is divided into overlapping frames corresponding to $0.2$ seconds. Each audio frame must be centered around a video frame. In order to achieve this one-to-one correspondence we zero pad the audio signal on both sides and use the following formula for the stride: \begin{equation} stride=\frac{audio\; sampling\;rate}{video\;fps} \label{eq:cutting_stride} \end{equation} The generator network has an encoder-decoder structure and can be conceptually divided into sub-networks as shown in \figref{fig:generator_modules}. We assume a latent representation that is made up of 3 components which account for the speaker identity, audio content and spontaneous facial expressions. These components are generated by different modules and combined to form an embedding which can be transformed into a frame by the decoding network. \begin{figure}[t] \centering \includegraphics[width=\columnwidth]{images/generator_step.pdf} \caption{The architecture of the {\em generator} network which consists of a {\em Content Encoder} (audio encoder and RNN), an {\em Identity Encoder}, a {\em Frame Decoder} and {\em Noise Generator}} \label{fig:generator_modules} \end{figure} \subsubsection{Identity Encoder} \label{sec:id_encoder} The speaker's identity is encoded using a 6-layer CNN. Each layer uses strided 2D convolutions, followed by batch normalization and ReLU activation functions. The {\em Identity Encoder} network reduces a $96\times128$ input image to a $128$ dimensional encoding $z_{id}$. \subsubsection{Content Encoder} \label{sec:content_encoder} Audio frames are encoded using a network comprising of 1D convolutions followed by batch normalization and ReLU activation functions. The initial convolutional layer starts with a large kernel, as recommended in \cite{Dai2016}, which helps limit the depth of the network while ensuring that the low-level features are meaningful. Subsequent layers use smaller kernels until an embedding of the desired size is achieved. The audio frame encoding is input into a 1-layer GRU, which produces a content encoding $z_c$ with $256$ elements. \subsubsection{Noise Generator} \label{sec:noise_gen} Although speech contains the necessary information for lip movements it can not be used to produce spontaneous facial expressions. To account for such expressions we propose appending a noise component to our latent representation. Spontaneous expressions such as blinks are coherent facial motions and therefore we expect the latent space that models them to exhibit the same temporal dependency. We therefore, avoid using white noise to model these expressions since it is by definition temporally independent. Instead we use a {\em Noise Generator} capable of producing noise that is temporally coherent. A 10 dimensional vector is sampled from a Gaussian distribution with mean $0$ and variance of $0.6$ and passed through a single-layer GRU to produce the noise sequence. This latent representation introduces randomness in the face synthesis process and helps with the generation of blinks and brow movements. \subsubsection{Frame Decoder} \label{sec:frame_decoder} The latent representation for each frame is constructed by concatenating the identity, content and noise components. The {\em Frame Decoder} is a CNN that uses strided transposed convolutions to produce the video frames from the latent representation. A U-Net \cite{Ronneberger2015} architecture is used with skip connections between the {\em Identity Encoder} and the {\em Frame Decoder} to preserve the identity of the subject as shown in \figref{fig:unet_contribution}. \begin{figure}[t] \centering \begin{subfigure}[b]{0.3\linewidth} \centering\includegraphics[width=0.6\textwidth]{images/frame_no_unet.pdf} \caption{\label{fig:no_skip}} \end{subfigure} \begin{subfigure}[b]{0.3\linewidth} \centering\includegraphics[width=0.6\textwidth]{images/frame_original.pdf} \caption{\label{fig:original_frame} } \end{subfigure} \begin{subfigure}[b]{0.3\linewidth} \centering\includegraphics[width=0.6\textwidth]{images/frame_w_frame_disc.pdf} \caption{\label{fig:skip connections} } \end{subfigure} \caption{The effect of adding skip connections to the generator network. The frames obtained without skip connections shown in (\subref{fig:no_skip}) do not resemble the person in the ground truth video (\subref{fig:original_frame}). Adding skip connections ensures that the identity is preserved in frames (\subref{fig:skip connections}).} \label{fig:unet_contribution} \end{figure} \subsection{Discriminators} \label{sec:discriminators} Our system uses multiple discriminators in order to capture different aspects of natural videos. The {\em Frame Discriminator} achieves a high-quality reconstruction of the speakers' face throughout the video. The {\em Sequence Discriminator} ensures that the frames form a cohesive video which exhibits natural movements. Finally, the {\em Synchronization Discriminator} reinforces the requirement for audio-visual synchronization. \subsubsection{Frame Discriminator} \label{sec:frame_disc} The {\em Frame Discriminator} is a 6-layer CNN that determines whether a frame is real or not. Adversarial training with this discriminator ensures that the generated frames are realistic. Furthermore, the original still frame is concatenated channel-wise to the target frame and used as a condition, which enforces the identity onto the video frames. \subsubsection{Sequence Discriminator} \label{sec:seq_disc} The {\em Sequence Discriminator} distinguishes between real and synthetic videos. At every time step the discriminator will use a CNN with spatio-temporal convolutions to extract transient features, which are then fed into a 1-layer GRU. A single layer classifier used at the end of the sequence determines if a sequence is real or not. \subsubsection{Synchronization Discriminator} \label{sec:sync_disc} The {\em Synchronization Discriminator} is given fixed-length snippets (corresponding to $0.2s$) of the original video and audio and determines whether they are in or out of sync. This discriminator uses a two stream architecture to compute an embedding for audio and video. The Euclidean distance between the 2 embeddings is calculated and fed into a single layer perceptron for classification. The architecture of this discriminator is shown in \figref{fig:sync_disc}. \begin{figure}[t] \centering \includegraphics[width=\columnwidth]{images/Sync_disc.pdf} \caption{The synchronization discriminator decides if an audio-visual pair is in or out of sync. It uses 2 encoders to obtain embeddings for audio and video and decides if they are in or out of sync based on their Euclidean distance.} \label{fig:sync_disc} \end{figure} Showing the discriminator only real or fake audio-video pairs will not necessarily result in samples being classified based on their audio visual correspondence. In order to force the discriminator to judge the sequences based on synchronization we also train it to detect misaligned audio-visual pairs taken from real videos. During training the discriminator learns to reduce the distance between the encodings of synchronized audio-video pairs and increase the distance between misaligned pairs. The distance for the fake pair (generated video with real audio) lies between these two distances and its location is determined by how dominant the discriminator is over the generator. Finally, since movements on the upper half of the face do not affect audio-visual synchrony we have chosen to use only the lower half of the face to train the {\em Synchronization Discriminator}. \subsection{Training} \label{sec:training} The {\em Frame discriminator} ($D_{img}$) is trained on frames that are sampled uniformly from a video $x$ using a sampling function $S(x)$. Using the process shown in \figref{fig:snip_selection} we obtain in and out of sync pairs $p_{in}$, $p_{out}$ from the real video $x$ and audio $a$ and a fake pair $p_{f}$. We use these pairs as training data for the \emph{Synchronization discriminator} ($D_{sync}$). Finally the \emph{Sequence Discriminator} ($D_{seq}$), classifies based on the entire sequence $x$. The total adversarial loss $\pazocal{L}_{adv}$ is made up of the adversarial losses associated with the {\em Frame} ($\pazocal{L}^{img}_{adv}$), {\em Synchronization} ($\pazocal{L}^{sync}_{adv}$) and {\em Sequence} ($\pazocal{L}^{seq}_{adv}$) discriminators. These losses are described by \eref{eq:adv_loss_img} -- \ref{eq:adv_loss_seq}. The total adversarial loss is an aggregate of the losses associated with each discriminator as shown in \eref{eq:total_adv_loss}, where each loss is assigned a corresponding weight ($\lambda_{img}$, $\lambda_{sync}$, $\lambda_{seq}$). \begin{figure}[t] \centering \includegraphics[width=0.9\columnwidth]{images/sync.pdf} \caption{All possible pairs that are used to train the synchronization discriminator. Pairs belong to in one of the following categories \{real video, in-sync audio\}, \{real video, shifted audio\}, \{fake video, matching audio\}} \label{fig:snip_selection} \end{figure} \begin{small} \begin{align} \begin{split} \pazocal{L}^{img}_{adv} = & \EX_{x \sim P_d}[\log D_{img}(S(x), x_1)] + \\ &\EX_{z \sim P_z}[\log (1- D_{img}(S(G(z)), x_1))] \end{split}\label{eq:adv_loss_img}\\ \begin{split} \pazocal{L}^{sync}_{adv} = \; & \EX_{x \sim P_d}[\log D_{sync}(p_{in})] + \frac{1}{2}\EX_{x \sim P_d}[\log 1-D_{sync}(p_{out})] \; +\\ &\frac{1}{2}\EX_{z \sim P_z}[\log (1- D_{sync}(S_{snip}(p_f))] \end{split}\label{eq:adv_loss_sync}\\ \begin{split} \pazocal{L}^{seq}_{adv} = \; & \EX_{x \sim P_d}[\log D_{seq}(x, a)] + \EX_{z \sim P_z}[\log (1- D_{seq}(G(z), a))] \end{split}\label{eq:adv_loss_seq}\\ \begin{split} \pazocal{L}_{adv} =\; & \lambda_{img} \pazocal{L}^{img}_{adv} + \lambda_{sync} \pazocal{L}^{sync}_{adv} + \lambda_{seq} \pazocal{L}^{seq}_{adv} \end{split}\label{eq:total_adv_loss} \end{align} \end{small} An $L_1$ reconstruction loss is also used to help capture the correct mouth movements. However we only apply the reconstruction loss to the lower half of the image since it discourages the generation of facial expressions. For a ground truth frame $F$ and a generated frame $G$ with dimensions $W \times H$ the reconstruction loss at the pixel level is \eref{eq:reconstruction_loss}. \begin{equation} \pazocal{L}_{L_1} = \sum_{p \in [ 0, W] \times [ \frac{H}{2}, H ] }|F_{p} - G_{p}| \label{eq:reconstruction_loss} \end{equation} The loss of our model, shown in \eref{eq:loss}, is made up of the adversarial loss and the reconstruction loss. The $\lambda_{rec}$ hyperparameter controls the contribution of of the reconstruction loss compared to the adversarial loss and is chosen so that, after weighting, this loss is roughly triple the adversarial loss. Through fine tuning on the validation set we find that the optimal values of the loss weights are $\lambda_{rec}= 600$, $\lambda_{img}= 1$, $\lambda_{sync}= 0.8$ and $\lambda_{seq}= 0.2$. The model is trained until no improvement is observed in terms of the audio-visual synchronization on the validation set for 5 epochs. We use pre-trained lipreading models where available or other audio-visual synchronization models to evaluate the audio-visual synchrony of a video. \begin{equation} \begin{split} \arg \min_{G} \max_{D} \;\; \pazocal{L}_{adv} +\; \lambda_{rec} \pazocal{L}_{L_1} \end{split} \label{eq:loss} \end{equation} We used Adam \cite{Kingma2014} for all the networks with a learning rate of $0.0001$ for the {\em Generator} and {\em Frame Discriminator}. The {\em Sequence Discriminator} and {\em Synchronization Discriminator} use a smaller learning rate of $10^{-5}$. Smaller learning rates for the sequence and synchronization discriminators are required in order to avoid over-training the discriminators, which can lead to instability \cite{Arjovsky2017TowardsNetworks}. The learning rate of the generator and discriminator decays with rates of $2\%$ and $10\%$, respectively, every 10 epochs. \section{Datasets} \label{sec:datasets} Experiments are run on the GRID, TCD TIMIT, CREMA-D and LRW datasets. The GRID dataset has 33 speakers each uttering 1000 short phrases, containing 6 words randomly chosen from a limited dictionary. The TCD TIMIT dataset has 59 speakers uttering approximately 100 phonetically rich sentences each. Finally, in the CREMA-D dataset 91 actors coming from a variety of different age groups and races utter 12 sentences. Each sentence is acted out by the actors multiple times for different emotions and intensities. We use the recommended data split for the TCD TIMIT dataset but exclude some of the test speakers and use them as a validation set. For the GRID dataset speakers are divided into training, validation and test sets with a $50\% - 20\% - 30\%$ split respectively. The CREMA-D dataset is also split with ratios $70\% - 15\% - 15\%$ for training, validation and test sets. Finally, for the LRW dataset we use the recommended training, validation and test sets. However we limit our training to faces that are nearly frontal. To do this we use pose estimation software \cite{3ddfa_cleardusk} based on the model proposed in \cite{zhu2017face} to select faces whose roll, pitch and yaw angles are smaller 10\degree. As part of our pre-processing all faces are aligned to the canonical face and images are normalized. We perform data augmentation on the training set by mirroring the videos. The amount of data used for training and testing is presented in \tabref{tab:Subjects}. \begin{table}[t] \small \begin{center} \begin{tabular}{|l|l|} \hline \multicolumn{1}{|c|}{Dataset} & \multicolumn{1}{c|}{Test Subjects} \\ \hline\hline GRID & 2, 4, 11, 13, 15, 18, 19, 25, 31, 33 \\ \hline TCD TIMIT & 8, 9, 15, 18, 25, 28, 33, 41, 55, 56 \\ \hline CREMA-D & 15, 20, 21, 30, 33, 52, 62, 81, 82, 89 \\ \hline \end{tabular} \end{center} \caption{The subject IDs that our model is tested on for each dataset.} \label{tab:test_subjects} \end{table} \begin{table}[t] \small \begin{center} \tabcolsep=0.06cm \begin{tabular}{|l|c|c|c|c|c|} \hline Dataset & Samples/Hrs (Tr) & Samples/Hrs (V)& Samples/Hrs (T) \\ \hline\hline GRID & 31639 / 26.4 & 6999 / 5.8 & 9976 / 8.31 \\ TCD & 8218 / 9.1 & 686 / 0.8 &977 / 1.2 \\ CREMA & 11594 / 9.7 & 819 / 0.7 & 820 / 0.68 \\ LRW & 112658 / 36.3 & 5870 / 1.9& 5980 / 1.9\\ \hline \end{tabular} \end{center} \caption{The samples and hours of video in the training (Tr), validation (V) and test (T) sets.} \label{tab:Subjects} \end{table} \begin{table}[t] \small \begin{center} \begin{tabular}{|c|c|c|c|c|} \hline Accuracy & Precision & Recall & MAE (Start) & MAE (End)\\ \hline 80\% & 100\% & 80\% & 1.4 & 2.1\\ \hline \end{tabular} \end{center} \caption{Performance of the blink detector on a small selection of videos from the GRID database that was manually annotated.} \label{tab:blink-performance} \end{table} \section{Metrics} \label{sec:metrics} This section describes the metrics that are used to assess the quality of generated videos. The videos are evaluated using traditional image reconstruction and sharpness metrics. Although these metrics can be used to determine frame quality they fail to reflect other important aspects of the video such as audio-visual synchrony and the realism of facial expressions. We therefore propose using alternative methods that are capable of capturing these aspects of the generated videos. \begin{description}[leftmargin=0cm] \item [\bt{Reconstruction Metrics}:] We use common reconstruction metrics such as the peak signal-to-noise ratio (PSNR) and the structural similarity (SSIM) index to evaluate the generated videos. During our assessment it is important to take into account the fact that reconstruction metrics will penalize videos for any facial expression that does not match those in the ground truth videos. \item [\bt{Sharpness Metrics}:] The frame sharpness is evaluated using the cumulative probability blur detection (CPBD) measure \cite{Narvekar2009}, which determines blur based on the presence of edges in the image. For this metric as well as for the reconstruction metrics larger values imply better quality. \item [\bt{Content Metrics}:] The content of the videos is evaluated based on how well the video captures identity of the target and on the accuracy of the spoken words. We verify the identity of the speaker using the average content distance (ACD) \cite{Tulyakov2017}, which measures the average Euclidean distance of the still image representation, obtained using OpenFace \cite{Amos2016}, from the representation of the generated frames. The accuracy of the spoken message is measured using the word error rate (WER) achieved by a pre-trained lip-reading model. We use the LipNet model \cite{Assael2016}, which surpasses the performance of human lip-readers on the GRID dataset. For both content metrics lower values indicate better accuracy. \item [\bt{Audio-Visual Synchrony Metrics}:] Synchrony is quantified using the methods proposed in \cite{Chung2016OutWild}. In this work Chung \etal propose the SyncNet network which calculates the euclidean distance between the audio and video encodings on small (0.2 second) sections of the video. The audio-visual offset is obtained by using a sliding window approach to find where the distance is minimized. The offset is measured in frames and is positive when the audio leads the video. For audio and video pairs that correspond to the same content the distance will increase on either side of point where the minimum distance occurs. However, for uncorrelated audio and video the distance is expected to be stable. Based on this fluctuation Chung \etal \cite{Chung2016OutWild} further propose using the difference between the minimum and the median of the Euclidean distances as an audio-visual (AV) confidence score which determines the audio-visual correlation. Higher scores indicate a stronger correlation, whereas confidence scores smaller than 0.5 indicate that audio and video are uncorrelated. \begin{figure}[t] \centering \begin{subfigure}[b]{0.37\linewidth} \centering\includegraphics[width=0.99\textwidth]{images/ear_open.pdf} \caption{\label{fig:ear_open}} \end{subfigure} \begin{subfigure}[b]{0.37\linewidth} \centering\includegraphics[width=0.99\textwidth]{images/ear_closed.pdf} \caption{\label{fig:ear_closed} } \end{subfigure} \caption{Landmarks used for EAR calculation. An open eye will have a larger EAR compared to a closed eye.} \label{fig:ear} \end{figure} \begin{figure}[t] \includegraphics[width=\columnwidth]{images/blinks.pdf} \caption{A blink is detected at the location where a sharp drop occurs in the EAR signal (blue dot). We consider the start (green dot) and end (red dot) of the blink to correspond to the peaks on either side of the blink location.} \label{fig:5} \end{figure} \item [\bt{Expression Evaluation}:] We investigate the generation of spontaneous expressions since it is one of the main factors that affect our perception of how natural a video looks. According to the study presented in \cite{Bentivoglio1997AnalysisSubjects} the average person blinks 17 times per minute (0.28 blinks/sec), although this rate increases during conversation and decreases when reading. We use a blink detector based on the one proposed in \cite{Soukupova2016Real-timeLandmarks}, which relies on the eye aspect ratio (EAR) to detect the occurrence of blinks in videos. The EAR is calculated per frame according to the formula shown in eq. \eqref{eq:EAR} using facial landmarks $p_1$ to $p_6$ shown in \figref{fig:ear}. The blink detector algorithm first calculates the EAR signal for the entire video and then identifies blink locations by detecting a sharp drop in the EAR signal. \end{description} \begin{equation} EAR =\frac{ \| p_2-p_6\| + \| p_3-p_5\|}{\| p_1-p_4\|} \label{eq:EAR} \end{equation} Once the blink is detected we can identify the start and end of the blink by searching for the peaks on either side of that location as shown in \figref{fig:5}. Using this information we can calculate the duration of blinks and visualize the blink distribution. To gauge the performance of the blink detector we measure its accuracy on 50 randomly selected videos from the GRID validation set that we have manually annotated. The performance metrics for the blink detection as well as the mean absolute error (MAE) for detecting the start and end points of the blinks are shown in \tabref{tab:blink-performance}. The MAE is measured in frames and the video frame rate is 25 fps. This method detects blinks with a high accuracy of 80\%, which means that we can rely on it to give us accurate statistics for the generated videos. We have chosen a very strict threshold for the drop in EAR in order to ensure that there are minimal if any false alarms. This is evident by the very high precision of the method. Finally, we note that the detector detects the start and end of a blink with an average error of $1.75$ frames. We can use the blink detector to obtain the distribution for the number of blinks per video (GRID videos are 3 seconds long) as well as the distribution for blink duration for the GRID test set. These results are shown in \figref{fig:real_blink}. The mean blink rate is 1.18 blinks/video or 0.39 blinks/second which is similar to the average human blink rate of 0.28 blinks/second, especially when considering that the blink rate increases to 0.4 blinks/second during conversation. The average duration of a blink was found to be 10 frames (0.41s). However, we find that using the median is more accurate since this is less sensitive to outliers caused by the detector missing the end of the blink. Finally, it is important to note that the short length of the videos will affect our estimate of the blink rate. The blinks for all the datasets are shown in \tabref{tab:blink_dataset}. \begin{table}[t] \small \begin{center} \begin{tabular}{|c|c|c|c|c|} \hline & GRID & TIMIT & CREMA & LRW\\ \hline blinks/sec& 0.39 & 0.28 & 0.26 & 0.53\\ median duration (sec)& 0.4 & 0.2& 0.36 & 0.32\\ \hline \end{tabular} \end{center} \caption{The average blink rate and median blink duration for real videos in each dataset.} \label{tab:blink_dataset} \end{table} \begin{figure}[t] \centering \begin{subfigure}[b]{0.45\linewidth} \centering\includegraphics[width=0.99\textwidth]{images/blink_distro_real.pdf} \caption{\label{fig:blink_distro}} \end{subfigure} \begin{subfigure}[b]{0.45\linewidth} \centering\includegraphics[width=0.99\textwidth]{images/blink_durations_distro_real.pdf} \caption{\label{fig:blink_duration_distro} } \end{subfigure} \caption{The distributions for (\subref{fig:blink_distro}) amount of blinks per video and (\subref{fig:blink_duration_distro}) the average blink duration per video from the GRID dataset.} \label{fig:real_blink} \end{figure} \section{Experiments} \label{sec:experiments} Our model is implemented in PyTorch and takes approximately a week to train using a single Nvidia GeForce GTX 1080 Ti GPU. During inference the average generation time per frame is 7ms on the GPU, permitting the use of our method in real time applications. A sequence of 75 frames can be synthesized in 0.5s. The frame and sequence generation times increase to 1s and 15s respectively when processing is done on the CPU. \subsection{Ablation Study} \label{sec:ablation} In order to quantify the effect of each component of our system we perform an ablation study on the GRID dataset (see \tabref{tab:ablation}). We use the metrics from section \ref{sec:metrics} and a pre-trained LipNet model which achieves a WER of $21.76 \%$ on the ground truth videos. The average value of the ACD for ground truth videos of the same person is $0.98 \cdot 10^{-4}$ whereas for different speakers it is $1.4 \cdot 10^{-3}$. \begin{table*}[ht] \small \begin{center} \begin{tabular}{|l|c|c|c|c|c|c|c|c|c|} \hline \multicolumn{1}{|l|}{Method} & \multicolumn{1}{c|}{PSNR} & \multicolumn{1}{c|}{SSIM} & \multicolumn{1}{c|}{CPBD} & \multicolumn{1}{c|}{ACD} & \multicolumn{1}{c|}{WER} & \multicolumn{1}{c|}{AV Offset} & \multicolumn{1}{c|}{AV Confidence} & \multicolumn{1}{c|}{blinks/sec}& \multicolumn{1}{c|}{blink dur. (sec)}\\ \hline\hline GT & $\infty$ & 1.00 & 0.276 & $0.98 \cdot 10^{-4}$ & 21.76\% & 1 & 7.0 & 0.39 & 0.41\\ w/o $\pazocal{L}_{adv}$ & \bt{28.467} & \bt{0.855} &0.210 & $ 1.92 \cdot 10^{-4}$ & 26.6\% & 1 &7.1 & 0.02 & 0.16\\ w/o $\pazocal{L}_{L_1}$ & 26.516 & 0.805 &\bt{0.270} & $ \bt{1.03} \cdot 10^{-4}$ & 56.4\% & 1 & 6.3 & 0.41 & 0.32\\ w/o $\pazocal{L}^{img}_{adv}$ & 26.474 & 0.804 &0.252 & $1.96 \cdot 10^{-4}$ & 23.2\% & 1 & 7.3 & 0.16 & 0.28\\ w/o $\pazocal{L}^{sync}_{adv}$ & 27.548 & 0.829 & 0.263 & 1.19 $\cdot 10^{-4}$ & 27.8\% & 1 & 7.2 & 0.21 & 0.32\\ w/o $\pazocal{L}^{seq}_{adv}$ & 27.590 & 0.829 & 0.259 & 1.13 $\cdot 10^{-4}$ & 27.0\% & 1 & \bt{7.4} & 0.03 & 0.16\\ Full Model & 27.100 & 0.818 &0.268 & $ 1.47 \cdot 10^{-4}$ & \bt{23.1\%} & 1 & \bt{7.4} & 0.45 & 0.36\\ \hline \end{tabular} \end{center} \centering \caption{Ablation study performed on the GRID dataset. In every experiment we train the model by removing a single term from eq. \eqref{eq:loss}.} \label{tab:ablation} \end{table*} The model that uses only an $L_1$ loss achieves better PSNR and SSIM results, which is expected as it does not generate spontaneous expressions, which are penalized by these metrics unless they happen to coincide with those in ground truth videos. We also notice that it results in the most blurry images. The blurriness is minimized when using the frame adversarial loss as indicated by the higher CPBD scores. This is also evident when comparing video frames generated with and without adversarial training as shown in \figref{fig:bluriness}. \begin{figure}[t] \centering \begin{subfigure}[b]{0.8\linewidth} \centering\includegraphics[width=0.99\textwidth]{images/blur_blurry.pdf} \caption{\label{fig:bluriness_l1} $L_1$ loss on entire frame} \end{subfigure} \begin{subfigure}[b]{0.8\linewidth} \centering\includegraphics[width=0.99\textwidth]{images/blur_clear.pdf} \caption{\label{fig:bluriness_model} Proposed loss on frames} \end{subfigure} \caption{Frames using (\subref{fig:bluriness_l1}) only an $L_1$ loss on the entire face compared to (\subref{fig:bluriness_model}) frames produced using the proposed method. Frames are taken from videos generated on the CREMA-D test set.} \label{fig:bluriness} \end{figure} The Average Content Distance is close to that of the real videos, showing that our model captures and maintains the subject identity throughout the video. Based on the results of the ablation study this is in large part due to the {\em Frame Discriminator}. Furthermore, this indicates that the identity encoder has managed to capture the speaker identity. Indeed, when plotting the identity encoding (\figref{fig:tsne}) of 1250 random images taken from the GRID test set using the t-Distributed Stochastic Neighbor Embedding (t-SNE) algorithm \cite{VanDerMaaten2008VisualizingT-sne} we notice that images of the same subject have neighbouring encodings. Additionally, we notice that the data points can be separated according to gender. \begin{figure}[t] \centering \includegraphics[width=0.9\columnwidth]{images/id_tsne.pdf} \caption{t-SNE plot of the identity encoding of random frames from the GRID test set. Frames corresponding to the same subject have the same colour. Male subjects are indicated by a cross whereas female subjects are indicated by a circle.} \label{fig:tsne} \end{figure} The \emph{Sequence Discriminator} is responsible for the generation of natural expressions. To quantify its effect we compare the distribution of blinks for videos generated by the full model to those generated without the \emph{Sequence Discriminator}. This is shown in \figref{fig:blink_distro_comp}, where it is evident that removing the sequence discriminator drastically reduces blink generation. Furthermore, we note the similarity of the generated and real distribution of blinks and blink duration. The average blink rate in videos generated by our model is 0.4 blinks/sec with the meadian blink lasting 9 frames (0.36s). Both the average blink rate and median duration are very close to those found in the ground truth videos in \tabref{tab:blink_dataset}. We also notice that the removal of the sequence discriminator coincides with a an increase in PSNR and SSIM, which is likely due to the generation of blinks and head movements. We test this hypothesis by calculating the PSNR only on the lower half of the image and find that gap between the non-adversarial model and our proposed model reduces by 0.3 dB. The effect of the synchronization discriminator is reflected in the low WER and high AV confidence values. Our ablation study shows that the temporal discriminators have a positive contribution to both the audio-visual synchronization and the WER. \begin{figure}[t] \centering \begin{subfigure}[b]{0.45\linewidth} \centering\includegraphics[width=\textwidth]{images/blink_distro_full_real.pdf} \caption{\label{fig:real_full_blinks} Full model} \end{subfigure}% \begin{subfigure}[b]{0.45\linewidth} \centering\includegraphics[width=\textwidth]{images/blink_distro_noseq_real.pdf} \caption{\label{fig:real_noseq_blinks} w/o $\pazocal{L}^{seq}_{adv}$ } \end{subfigure} \begin{subfigure}[b]{0.45\linewidth} \centering\includegraphics[width=\textwidth]{images/duration_distro_full_real.pdf}% \caption{\label{fig:real_full_durations} Full model} \end{subfigure} \begin{subfigure}[b]{0.45\linewidth} \centering\includegraphics[width=\textwidth]{images/duration_distro_noseq_real.pdf} \caption{\label{fig:real_noseq_durations} w/o $\pazocal{L}^{seq}_{adv}$} \end{subfigure} \caption{The distribution of blinks for videos generated by (\subref{fig:real_full_blinks}) our proposed model and (\subref{fig:real_noseq_blinks}) a model without the {\em Sequence Discriminator}. When the {\em Sequence Discriminator} is used (\subref{fig:real_full_durations}) the distribution of blink duration closely resembles that of the real videos. The same does not hold when (\subref{fig:real_noseq_durations}) the {\em Sequence Discriminator} is omitted.} \label{fig:blink_distro_comp} \end{figure} \begin{figure*}[t] \begin{center} \includegraphics[width=0.99\linewidth]{images/diffface_journal.pdf}\\ \end{center} \caption{Animation of different faces using the same audio. The movement of the mouth is similar for both faces as well as for the ground truth sequence. Both audio and still image are taken from the TIMIT dataset and are unseen during training.} \label{fig:diffface} \end{figure*} \begin{figure}[t] \centering \begin{subfigure}[b]{\linewidth} \centering\includegraphics[width=0.08\textwidth]{images/flow_ref.pdf} \caption{\label{fig:reference} Movement direction map} \end{subfigure} \begin{subfigure}[b]{\linewidth} \centering\includegraphics[width=0.95\textwidth]{images/lrw_blink_heatmap_longer.pdf} \caption{\label{fig:blink} Generated blink using audio from LRW and image from CelebA} \end{subfigure} \begin{subfigure}[b]{\linewidth} \centering\includegraphics[width=0.95\textwidth]{images/frown_heatmap_longer.pdf} \caption{\label{fig:frown} Generated frown on GRID dataset} \end{subfigure} \begin{subfigure}[b]{\linewidth} \centering\includegraphics[width=0.95\textwidth]{images/angry_heatmap_longer.pdf} \caption{\label{fig:shouting} Angry expression from shouting audio on CREMA-D dataset} \end{subfigure} \caption{Facial expressions generated using our framework include (\subref{fig:blink}) blinks, (\subref{fig:frown}) frowns and (\subref{fig:shouting}) shouting expressions. The corresponding optical flow motion map is shown above each sequence. A reference diagram for the direction of the movement is shown in (\subref{fig:reference}).} \label{fig:expressions} \end{figure} \begin{figure}[t] \begin{center} \includegraphics[width=\linewidth]{images/emotions2.pdf}\\ \end{center} \caption{Videos produced by the proposed method using the same image taken from the CREMA-D test set and driven by the sentence ``its eleven o'clock'' spoken with a female voice with multiple emotions.} \label{fig:emotions} \end{figure} \begin{figure*}[t] \begin{center} \includegraphics[width=0.76\linewidth]{images/celebA.pdf}\\ \end{center} \vspace{-11pt} \caption{Videos produced using model trained on LRW for unseen faces taken from the CelebA dataset. The speech clip is taken from the test set of the LRW dataset and corresponds to the word "stand". Frames which contain blinking eyes are highlighted.} \label{fig:celebA_faces} \end{figure*} \subsection{Qualitative Results} \label{sec:qualitative} Our method is capable of producing realistic videos of previously unseen faces and audio clips taken from the test set. The same audio used on different identities is shown in \figref{fig:diffface}. From visual inspection it is evident that the lips are consistently moving similarly to the ground truth video. Our method not only produces accurate lip movements but also natural videos that display characteristic human expressions such as frowns, blinks and angry expressions, examples of which are shown in \figref{fig:expressions}. In these examples we highlight the regions of the frames that exhibit the most movement using motion maps. These maps are obtained by calculating the optical flow between consecutive frames, reflecting the angle of movement in the hue and assigning the magnitude of the motion to the value component in the Hue Saturation Value (HSV) color-space. The amount and variety of expressions generated is dependent on the amount of expressions present in the dataset used for training and hence faces generated by models trained on expressive datasets such as CREMA-D will exhibit a wider range of expressions. This is illustrated in \figref{fig:emotions}, where the facial expressions reflect the emotion of the speaker. The works that are closest to ours are those proposed in \cite{Suwajanakorn2017} and \cite{Chung2017}. The former method is subject dependent and requires a large amount of data for a specific person to generate videos. There is no publicly available implementation for the \textit{Speech2Vid} method proposed in \cite{Chung2017} but a pre-trained model is provided, which we can use for comparison. For completeness we also compare against a GAN-based method that uses a combination of an $L_1$ loss and an adversarial loss on individual frames. We consider this approach as the baseline GAN-based approach. Finally, we also compare with the \emph{ATVGNet} model proposed in \cite{Chen_2019_CVPR}, which is pretrained on the LRW dataset. Since the baseline and the \textit{Speech2Vid} model are static methods they produce less coherent sequences, characterized by jitter, which becomes worse in cases where the audio is silent (e.g. pauses between words). This is likely due to the fact that there are multiple mouth shapes that correspond to silence and since the model has no knowledge of its past state it generates them at random. \figref{fig:jitterface} highlights such failures of static models and compares it to our method. The \textit{Speech2Vid} model only uses an $L_1$ reconstruction loss during training and therefore it will discourage spontaneous expressions which mostly occur on the upper part of the face. In order to examine the movement we use optical flow and create a heatmap for the average magnitude of movement over a set of 20 videos of the same subject from the LRW test set. The heatmaps shown in \figref{fig:average_heatmaps} reveal the areas of the face that are most often animated. Videos generated using our approach have heatmaps that more closely resemble those of real videos. The static baseline is characterized by considerably more motion on the face which likely corresponds to jitter. The \textit{Speech2Vid} and \emph{ATVGNet} models do not animate the upper part of the face. This means that that these methods do not capture speaker's tone and cannot therefore generate matching facial expressions. An example of this shortcoming is shown in \figref{fig:speech2vid_compare} where we compare a video generated from the CREMA-D dataset using the \textit{Speech2Vid} model and our proposed method. \begin{table*}[t] \small \centering \begin{tabular}{|c|l|c|c|c|c|c|c|c|c|c|c|} \hline & \multicolumn{1}{c|}{Method}& \multicolumn{1}{c|}{PSNR} & \multicolumn{1}{c|}{SSIM} & \multicolumn{1}{c|}{CPBD} & \multicolumn{1}{c|}{ACD}& \multicolumn{1}{c|}{WER}& \multicolumn{1}{c|}{AV Off.} & \multicolumn{1}{c|}{AV Conf.}& \multicolumn{1}{c|}{blinks/sec}& \multicolumn{1}{c|}{blink dur. (sec)}\\ \hline\hline \small \parbox[t]{2mm}{\multirow{3}{*}{\centering \rotatebox[origin=c]{90}{GRID}}} & Proposed Model & \bt{27.100} & \bt{0.818}& \bt{0.268} & 1.47 $\cdot 10^{-4}$ & \bt{23.1\%} & \bt{1} & \bt{7.4} & 0.45 & 0.36\\ & Baseline & 27.023 & 0.811 & 0.249 & $\bt{1.42} \cdot 10^{-4}$ & 36.4\% & 2 & 6.5 & 0.04 & 0.29\\ & \emph{Speech2Vid}& 22.662 & 0.720 & 0.255 & $ 1.48 \cdot 10^{-4}$ & 58.2\% & \bt{1} & 5.3 & 0.00 & 0.00\\ \hline \small \parbox[t]{2mm}{\multirow{3}{*}{\rotatebox[origin=c]{90}{TCD}}} & Proposed Model & \bt{24.243} & \bt{0.730}& \bt{0.308} & \bt{1.76} $\cdot 10^{-4}$ & N/A & \bt{1} & \bt{5.5} & 0.19 & 0.33\\ & Baseline &24.187 & 0.711 & 0.231 & $1.77 \cdot 10^{-4}$ & N/A & 8 & 1.4 & 0.08 & 0.13\\ & \emph{Speech2Vid}& 20.305 & 0.658 & 0.211 & $ 1.81 \cdot 10^{-4}$ & N/A & \bt{1} & 4.6 & 0.00 & 0.00\\ \hline \small \parbox[t]{2mm}{\multirow{3}{*}{\rotatebox[origin=c]{90}{CREMA}}} & Proposed Model & \bt{23.565} & \bt{0.700} & 0.216 & \bt{1.40} $\cdot 10^{-4}$ & N/A & 2 & \bt{5.5} & 0.25 & 0.26\\ & Baseline & 22.933 & 0.685 & 0.212 & $ 1.65 \cdot 10^{-4}$ & N/A & 2 & 5.2 & 0.11& 0.13\\ & \emph{Speech2Vid} & 22.190 & 0.700 & \bt{0.217} & $ 1.73 \cdot 10^{-4}$ & N/A & \bt{1} & 4.7 & 0.00 & 0.00\\ \hline \small \parbox[t]{2mm}{\multirow{4}{*}{\rotatebox[origin=c]{90}{LRW}}} & Proposed Model &\bt{23.077} & \bt{0.757} & \bt{0.260} & 1.53 $\cdot 10^{-4}$ & N/A & \bt{1} & \bt{7.4} & 0.52& 0.28\\ & Baseline & 22.884 & 0.746 & 0.218 & \bt{1.02} $\cdot 10^{-4}$ & N/A & 2 & 6.0 & 0.42& 0.13\\ & \emph{Speech2Vid} & 22.302 & 0.709 & 0.199 & $2.61 \cdot 10^{-4}$ & N/A & 2 & 6.2 & 0.00 & 0.00\\ & \emph{ATVGNet} & 20.107 & 0.743 & 0.189 & $ 2.14 \cdot 10^{-4}$ & N/A & 2 & 7.0 & 0.00& 0.00 \\ \hline \end{tabular} \caption{Performance comparison of the proposed method against the static baseline and \emph{Speech2Vid} \cite{Chung2017}. A pretrained LipNet model is only available for the GRID dataset so the WER metric is omitted on other datasets. The LRW datasets contains only one word so calculating WER is not possible} \label{tab:quantitative} \end{table*} \subsection{Quantitative Results} \label{sec:quantitative} We measure the performance of our model on the GRID, TCD TIMIT, CREMA-D and LRW datasets using the metrics proposed in section \ref{sec:metrics} and compare it to the baseline and the \emph{Speech2Vid} model. For the LRW dataset we also compare with the \emph{ATVGNet} GAN-based method proposed in \cite{Chen_2019_CVPR}, for which we use the provided pretrained model. The preprocessing procedure for \emph{ATVGNet} is only provided for the LRW dataset hence we do not compare with this model on other datasets. The results in \tabref{tab:quantitative} show that our method outperforms other approaches in both frame quality and content accuracy. For the LRW dataset our model is better not only from the static approaches but also from \emph{ATVGNet}. Our model performs similarly or better than static methods when in terms of frame-based measures (PSNR, SSIM, CBPD, ACD). However, the difference is substantial in terms of metrics that measure content such as lipreading WER. Also our method achieves a higher AV confidence, although it must be noted that based on the offset estimated using the SyncNet model our videos generated for the CREMA-D dataset exhibit a slight lag of 1 frame compared to the \textit{Speech2Vid} method. Finally, we emphasize that our model is capable of generating natural expressions, which is reflected in the amount and duration of blinks (\tabref{tab:quantitative}), closely matching those of the real videos, shown in \tabref{tab:blink_dataset}. We note that the \emph{Speech2Vid} and \emph{ATVGNet} methods are not capable of generating any blinks. For the \emph{Speech2Vid} model this due to using only an $L_1$ loss and for the \emph{ATVGNet} this is likely due to the attention mechanism which focuses only on the mouth since it is the region that correlates with speech. The static baseline is capable of producing frames with closed eyes but these exhibit no continuity and are characterised by very short duration as shown in \tabref{tab:quantitative}. We further note the differences in the performance of our method for different datasets. In particular we note that the reconstruction metrics are better for the GRID dataset. In this dataset subjects are recorded under controlled conditions and faces are not characterised by much movement. Synthesized faces will mimic the motion that is present in the training videos, generating emotions and head movements. However since these movements cause deviation from the ground truth videos and therefore will be penalized by reference metrics such as PSNR and SSIM. Performance based on reconstuction metrics becomes worse as datasets become less controlled and exhibit more expressions. Another noteworthy phenomenon is the drop in audio-visual correlation, indicated by the lower AV confidence for the TCD TIMIT and CREMA-D datasets compared to GRID and LRW. We attribute to this drop in performance to the fact that the TCD TIMIT and CREMA-D are smaller datasets. It is therefore likely that the datasets do not have the sufficient data for the models to capture the articulation as well as for larger datasets. \begin{figure}[t] \centering \includegraphics[width=0.77\columnwidth]{images/jitterface_journal.pdf} \caption{Example of consecutive frames showcasing the failure of static methods to produce a coherent motion. During silent periods static approaches exhibit jittery motion in the mouth.} \label{fig:jitterface} \end{figure} \subsection{User Study} Human perception of synthesized videos is hard to quantify using objective measures. Therefore, we further evaluate the realism of the generated videos through an online Turing test \footnote{Test available \url{https://forms.gle/XDcZm8q5zbWmH7bD9}}. In this test users are shown 24 videos (12 real - 12 synthesized), which were chosen at random from the GRID, TIMIT and CREMA datasets. We have not included videos from the LRW since uploading them publicly is not permitted. Users are asked to label each video as real or fake. Responses from 66 users were collected with the average user labeling correctly $52\%$ of the videos. The distribution of user scores is shown in \figref{fig:turing_test}. \begin{figure}[t] \centering \includegraphics[width=0.85\columnwidth]{images/turing_test.pdf} \caption{Distribution of correct responses of users in the online Turing test. The red line symbolizes the a Gaussian distribution with the same mean and std. dev. as the data.} \label{fig:turing_test} \end{figure} \section{Conclusion and Future Work} \label{sec:conclusion} In this work we have presented an end-to-end model using temporal GANs for speech-driven facial animation. Our model produces highly detailed frames scoring high in terms of PSNR, SSIM and in terms of the sharpness on multiple datasets. According to our ablation study this can be mainly attributed to the use of a \emph{Frame Discriminator}. \begin{figure}[t] \centering \begin{subfigure}[b]{0.95\linewidth} \centering\includegraphics[width=0.99\textwidth]{images/chung_compare.pdf} \caption{\label{fig:sp2vid_crema} \textit{Speech2Vid}} \end{subfigure} \begin{subfigure}[b]{0.95\linewidth} \centering\includegraphics[width=0.99\textwidth]{images/ours_compare.pdf} \caption{\label{fig:ours_crema} Proposed Model} \end{subfigure} \caption{Comparison of the proposed model with \emph{Speech2Vid}. It is obvious that \emph{Speech2Vid} can only generate mouth movements and cannot generate any facial expression.} \label{fig:speech2vid_compare} \end{figure} \begin{figure}[t!] \centering \includegraphics[width=\columnwidth]{images/lrw.pdf} \caption{Average motion heatmaps showing which areas of the face exhibit the most movement. The heatmaps are an average of the magnitude of the optical flow taken for 20 videos of the same subject of the LRW dataset. An example sequence is shown next to the heatmap of each model.} \label{fig:average_heatmaps} \end{figure} Furthermore, our method produces more coherent sequences and more accurate mouth movements compared to the GAN-based static baseline and the \emph{Speech2Vid} method. This is demonstrated by a resounding difference in the WER. We believe that these improvements are not only a result of using a temporal generator but also due to the use of the \emph{Synchronization Discriminator}. Unlike the \emph{Speech2Vid} and \emph{ATVGNet} that prohibit the generation of facial expressions, the adversarial loss on the entire sequence encourages spontaneous facial gestures. This has been demonstrated with examples of blinks, head and brow movements. Furthermore, our model is capable of capturing the emotion of the speaker and reflecting it in the generated face. This model has shown promising results in generating lifelike videos, which produce facial expressions that reflect the speakers tone. The inability of users to distinguish the synthesized videos from the real ones in the Turing test verifies that the videos produced look natural. The current limitation of our method is that it only works for well-aligned frontal faces. Therefore, the natural progression of this work will be to produce videos that simulate in the wild conditions. Finally, future work should also focus on extending the network architecture to produce high definition video. \section*{Acknowledgements} We would like to thank Berk Tinaz for his help with the detection of blinks and the estimation blink duration. We also gratefully acknowledge the support of NVIDIA Corporation with the donation of the Titan V GPU used for this research and Amazon Web Services for providing the computational resources for our experiments.
{'timestamp': '2019-06-18T02:00:39', 'yymm': '1906', 'arxiv_id': '1906.06337', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06337'}
arxiv
\section{Introduction} An interesting natural phenomenon is the ability of swarms of simple individuals to form complex and very regular patterns: swarms of fishes \cite{x1}, birds \cite{x2}, ants \cite{x3}... They do so in a totally distributed manner, without any centralized or irreplaceable leader. Such behaviors are a great source of inspiration for distributed computing. Problems of \emph{pattern formation} have been extensively studied by the distributed computing community \cite{u6,u7,z1,z2}. In order to prove mathematical results, the model is of course simplified: the individuals (\emph{processes}) are usually geometric points in a Euclidean space. A famous example is the circle formation algorithm by Suzuki and Yamashita \cite{u7}. In particular, a pattern formation problem which has been extensively studied is the \emph{gathering} problem \cite{u2,u3,u4,b1,b4}: processes must gather at a same point in a finite time. This apparently simple problem can become surprisingly complex, depending on the model and hypotheses: scheduler, symmetry, computational power, memory, orientation... When gathering is impossible, a close problem is the \emph{convergence} problem \cite{u5,b2}: processes must get always closer to a same point. One of these hypotheses is \emph{visibility}. Most pattern formation papers assume \emph{unlimited} visibility \cite{u1,u2,u3,u4,u5,u6,u7}: processes have a global view of the position of other processes. Some papers assume a \emph{limited} visibility \cite{b1,b2,b3,b4}: processes can only see other processes within a certain radius. However, even with a limited visibility, each process is supposed to analyze the position of several neighbor processes at each computing step. This leads us to the following question: what is the simplest hypothesis we could make on visibility? In this paper, we assume that each process can only see its closest neighbor (i.e., the closest other process), and ignores the total number of processes. To our knowledge, no paper has yet considered such a minimalist setting. We then study to what extent the gathering and convergence problems can be solved in this setting. We assume a synchronous scheduler and memoryless processes that cannot communicate with messages. There is an indeterminacy in the case where there are several ``closest neighbors'' (i.e., two or more processes at the same distance of a given process). We first assume that, in this situation, the closest neighbor is arbitrarily chosen by an external adversary (worst-case scenario). In this scenario, we show that, surprisingly, the problems can only be solved for a small number of processes. More precisely, if $n$ is the number of processes and $d$ is the number of dimensions of the Euclidean space, then the gathering (resp. convergence) problem can be solved if and only if $d = 1$ or $n \leq 2$ (resp. $d = 1$ or $n \leq 5$). Indeed, for larger values of $n$, there exists initial configurations from which gathering or convergence is impossible, due to symmetry. The proof is constructive: for the small values of $n$, we provide an algorithm solving the problems. The proof is non-trivial for $n = 4$ and $n = 5$, as several families of cases need to be considered. Therefore, to solve the problems for larger values of $n$, one additional hypothesis must necessarily be added. We remove the aforementioned indeterminacy by making the choice of the closest neighbor (when there is more than one) deterministic instead of arbitrary (according to an order on the positions of processes). Then, we show that the gathering problem is always solved in at most $n - 1$ steps by a simple ``Move to the Middle'' (MM) algorithm. We finally consider the case of crash failures, where at most $f$ processes lose the ability to move. We show that the gathering (resp. convergence) problem can only be solved when $f = 0$ (resp. $f \leq 1$). When the convergence problem can be solved, the MM algorithm solves it. Beyond this first work, we believe that this minimalist model can be the ground for many other interesting results. The paper is organized as follows. In Section~\ref{secmodel}, we define the model and the problems. In Section~\ref{secalgo}, we characterize the class of algorithms allowed by our model, and define a simple algorithm to prove the positive results. In Section~\ref{seclb}, we prove the aforementioned lower bounds. In Section~\ref{secpos}, we remove indeterminacy and show that the gathering problem can be solved for any $n$. In Section~\ref{secft}, we consider the case of crash failures. We conclude in Section~\ref{sec_conc}. \section{Model and problems} \label{secmodel} \paragraph{Model.} We consider a Euclidean space $S$ of dimension $d$ ($d \geq 1$). The position of each point of $S$ is described by $d$ coordinates $(x_1,x_2,\dots,x_d)$ in a Cartesian system. For two points $A$ and $B$ of coordinates $(a_1,\dots,a_d)$ and $(b_1,\dots,b_d)$, let $d(A,B) = \sqrt{\Sigma_{i=1}^{i=d} (a_i - b_i)^2}$ be the distance between $A$ and $B$. Let $P$ be a set of $n$ processes. $\forall p \in P$, let $M_p$ be the position of $p$ in $S$. Let $\Omega$ be the set of positions occupied by the processes of $P$. As several processes can share the same position, $1 \leq |\Omega| \leq |P|$. The time is divided in discrete steps $t \in \{0,1,2,3,\dots\}$. If $|\Omega| = 1$, the processes are \emph{gathered} (they all have the same position). If $|\Omega| \geq 2$, $\forall p \in P$, let $D(p) = \min_{K \in \Omega - \{M_p\}} d(M_p,K)$, and let $N(p)$ be the set of processes $q$ such that $d(M_p,M_q) = D(p)$. At a given time $t$, the \emph{closest neighbor} of a process $p$ is a process of $N_p$ arbitrarily chosen by an external adversary. We denote it by $C(p)$. We consider a synchronous execution model. At a given time $t$, a process $p$ can only see $M_p$ and $M_{C(p)}$ (without global orientation), and use these two points to compute a new position $K$. Then, the position of $p$ at time $t+1$ is $K$. The processes are oblivious (they have no memory), mute (they cannot communicate) and anonymous (they cannot distinguish each other with identifiers). Note that this model does not assume multiplicity detection (the ability to count the processes at a same position). The processes do not know $n$. At $t = 0$, the $n$ processes can have any arbitrary positions. \paragraph{Problems.} For a given point $G \in S$ and a given constant $\epsilon$, we say that the processes are $(G,\epsilon)$-gathered if, $\forall M \in \Omega$, $d(G,M) \leq \epsilon$. An algorithm solves the \emph{convergence} problem if, for any initial configuration, there exists a point $G \in S$ such that, $\forall \epsilon > 0$, there exists a time $T$ such that the processes are $(G,\epsilon)$-gathered $\forall t \geq T$. An algorithm solves the \emph{gathering} problem if, for any initial configuration, there exists a point $G$ and a time $T$ such that the processes are $(G,0)$-gathered $\forall t \geq T$. \section{Algorithm} \label{secalgo} In this section, we describe all possible algorithms that our model allows. Doing so enables us to show lower bounds further -- that is, showing that \emph{no algorithm} can solve some problems in our model. This is not to confuse with the $MM$ algorithm (a particular case, defined below), which is only used to prove positive results. Here, an algorithm consists in determining, for any process $p$, the position of $p$ at the next step, as a function of $M_p$ and $M_{C(p)}$. First, let us notice that, if the processes are gathered ($|\Omega| = 1$), the processes have no interest in moving anymore. This corresponds to the case where each process cannot see any ``closest neighbor''. Thus, we assume that any algorithm is such that, when a process $p$ cannot see any closest neighbor, $p$ does not move. Now, consider the case where the processes are not gathered $(|\Omega| \geq 2)$. Let $p$ be the current process, let $D = D(p)$, and let $\vec{x}$ be the unit vector ($ || \vec{x} || = 1$) directed from $M_p$ to $M_{C(p)}$. There are $2$ possible cases. \paragraph{Case 1: $d = 1$.} The next position of $p$ is $M_p + f_x(D)\vec{x}$, where $f_x$ is an arbitrary function. \paragraph{Case 2: $d \geq 2$.} Let $\Delta$ be the axis defined by $M_p$ and $M_{C(p)}$. If $d \geq 2$, as there is no global orientation of processes ($M_p$ can only position itself relatively to $M_{C(p)}$), the next position of $p$ can only be determined by (1) its position on axis $\Delta$ and (2) its distance to $\Delta$. The difference here is that, for two given parameters (1) and (2), there are several possible positions ($2$ positions for $d = 2$, an infinity of positions for $d \geq 3$). Thus, we assume that the next position (among these possible positions) is arbitrarily chosen by an external adversary. More formally, the next position of $p$ is $M_p + f_x(D)\vec{x} + f_y(D)\vec{y}$, where $f_x$ and $f_y$ are arbitrary functions, and where $\vec{y}$ is a vector orthogonal to $\vec{x}$ which is arbitrarily chosen by an external adversary. \paragraph{Move to the Middle (MM) algorithm.} We finally define one particular algorithm to show some upper bounds. The Move to the Middle (MM) algorithm consists, for each process $p$ and at each step, in moving to the middle of the segment defined by $M_p$ and $M_{C(p)}$. More formally, if $d = 1$, the MM algorithm is defined by $f_x(D) = D/2$. If $d \geq 2$, the MM algorithm is defined by $f_x(D) = D/2$ and $f_y(D) = 0$. \section{Lower bounds} \label{seclb} In this section, we show the two following results. \begin{theorem} The gathering problem can be solved if and only if $d = 1$ or $n \leq 2$. When it can be solved, the MM algorithm solves it. \label{th_lb_gath} \end{theorem} \begin{theorem} The convergence problem can be solved if and only if $d = 1$ or $n \leq 5$. When it can be solved, the MM algorithm solves it. \label{th_lb_conv} \end{theorem} \subsection{Gathering problem} Let us prove Theorem~\ref{th_lb_gath}. \begin{lemma} \label{lemd1} If $d = 1$, the MM algorithm solves the gathering problem. \end{lemma} \begin{proof} Let us show that, if $|\Omega| \geq 2$, then $|\Omega|$ decreases at the next step. As $d=1$, let $x(K)$ be the coordinate of point $K$. Let $(K_1,K_2,\dots,K_m)$ be the points of $\Omega$ ranked such that $x(K_1) < x(K_2) < \dots < x(K_m)$. $\forall i \in \{1,\dots,m\}$, let $x_i = x(K_i)$. Then, according to the MM algorithm, the possible positions at the next step are: $(x_1+x_2)/2, (x_2+x_3)/2, \dots, (x_{m-1}+x_m)/2$ (at most $m - 1$ positions). Thus, $|\Omega|$ decreases at the next step. Therefore, after at most $n-1$ steps, we have $|\Omega| = 1$, and the gathering problem is solved.\end{proof} \begin{lemma} \label{lem3pt} If $d \geq 2$ and $n \geq 3$, the gathering problem is impossible to solve. \end{lemma} \begin{proof} First, consider the case $d = 2$. Consider an initial configuration where $\Omega$ contains three distinct points $K_1$, $K_2$ and $K_3$ such that $d(K_1,K_2) = d(K_2,K_3) = d(K_3,K_1) = D$. Let $G$ be the gravity center of the triangle $K_1K_2K_3$. Let $s(1) = 2$, $s(2) = 3$ and $s(3) = 1$. $\forall i \in \{1,2,3\}$, let $A_i$ and $B_i$ be the two half-planes delimited by the axis $(K_iK_{s(i)})$, such that $G$ belongs to $B_i$. Let $\vec{v_i}$ be the unit vector orthogonal to $(K_iK_{s(i)})$ such that the point $K_i + \vec{v_i}$ belongs to $A_i$. Let $\vec{y_i} = \vec{v_i}$ if $f_y(D) \geq 0$, and $\vec{y_i} = -\vec{v_i}$ otherwise. Let $p$ be a process, and let $i$ be such that $M_p = K_i$. The external adversary can choose a closest neighbor $C(p)$ and a vector $\vec{y}$ such that $M_{C(p)} = K_{s(i)}$ and $\vec{y} = \vec{y_i}$. Thus, at the next step, it is always possible that $\Omega$ contains three \emph{distinct} points also forming an equilateral triangle. The choice of vectors $\vec{y}$ prevents the particular case where all processes are gathered in point $G$. We can repeat this reasoning endlessly. Thus, the gathering problem cannot be solved if $d = 2$. Now, consider the case $d > 2$. The external adversary can choose the $\vec{y}$ vectors such that the points of $\Omega$ always remain in the same plane, and their behavior is the same as for $d = 2$. Thus, the gathering problem cannot be solved if $d > 2$. \end{proof} \textbf{Theorem~\ref{th_lb_gath}.} \emph{The gathering problem can be solved if and only if $d = 1$ or $n \leq 2$. When it can be solved, the MM algorithm solves it.} \begin{proof} If $d = 1$, according to Lemma~\ref{lemd1}, the MM algorithm solves the gathering problem. If $n = 1$, the gathering problem is already solved by definition. If $n = 2$, the MM algorithm solves the gathering problem in at most one step. Otherwise, if $d \geq 2$ and $n \geq 3$, according to Lemma~\ref{lem3pt}, the gathering problem cannot be solved. \end{proof} \subsection{Convergence problem} Let us prove Theorem~\ref{th_lb_conv}. We first introduce some definitions. For a given set of points $X \subseteq S$, let $D_{\max}(X) = \max_{\{A,B\} \subseteq X}$ $d(A,B)$. Let $\Omega(t)$ be the set $\Omega$ at time $t$. Let $d_{\max}(t) = \max_{\{A,B\} \subseteq \Omega(t)} d(A,B)$ and $d_{\min}(t) = \min_{\{A,B\} \subseteq \Omega(t)} d(A,B)$. Let $m(A,B)$ be the middle of segment [AB]. Let $\alpha(K) =$ $\sqrt{1 - 1/(4K^2)}$. Let $R(t) = \arg \min_{G \in S} \max_{M \in \Omega(t)} d(G,M)$ (the radius of the smallest enclosing ball of all processes' positions). Let $X_i(t)$ be the smallest $i^{th}$ coordinate of a point of $\Omega(t)$. We say that a proposition $P(t)$ is true \emph{infinitely often} if, for any time $t$, there exists a time $t' \geq t$ such that $P(t)$ is true. \begin{lemma} \label{lem_of_3} If there exists a time $t$ such that $|\Omega(t)| \leq 3$, the MM algorithm solves the convergence problem. \end{lemma} \begin{proof} If $|\Omega(t)| = 1$, the processes are and remain gathered. If $|\Omega(t)| = 2$, then $|\Omega(t+1)| = 1$. If $|\Omega(t)| = 3$, consider the following proposition $P$: there exists $t' > t$ such that $|\Omega(t')| \leq 2$. If $P$ is true, the gathering (and thus, convergence) problem is solved. Now, consider the case where $P$ is false. Let $\Omega(t) = \{A,B,C\}$. Then, as $|\Omega(t+1)| = 3$, $\Omega(t+1) = \{m(A,B),m(B,C),m(C,A)\}$. The center of gravity $G$ of the triangle formed by the three points of $\Omega$ always remains the same, and $d_{\max}(t)$ is divided by two at each step. Thus, $\forall \epsilon > 0$, there exists a time $T$ such that the processes are $(G,\epsilon)$-gathered $\forall t \geq T$.\end{proof} \begin{lemma} \label{lemKalpha} Let $K \geq 1$. If $R(t) \leq K d_{\min}(t)$, then $R(t+1) \leq \alpha(K) R(t)$. \end{lemma} \begin{proof} If the processes move according to the MM algorithm, then $\Omega(t+1) \subseteq \bigcup_{\{A,B\} \subseteq \Omega(t)}$ $\{m(A,B)\}$. Let $G$ be such that, $\forall M \in \Omega(t)$, $d(G,M) \leq R(t)$. Let $A$ and $B$ be two points of $S$ such that $d(G,A) = d(G,B) = R(t)$ and $d(A,B) = d_{\min}(t)$ (two such points $A$ and $B$ exist, as $d_{\min}(t) \leq 2R(t)$). Let $C = m(A,B)$. Then, $\forall M \in \Omega(t+1)$, $d(G,M) \leq d(G,C)$. Thus, $R(t+1) \leq d(G,C)$. Let $x = d(G,C)$, $y = d_{\min}(t)/2$ and $z = R(t)$. Then, $z^2 = x^2 + y^2$ and $x/z = \sqrt{1 - (y/z)^2}$. As $R(t) \leq K d_{\min}(t)$, $y/z \geq 1/(2K)$ and $x/z \leq \sqrt{1 - 1/(4K^2)} = \alpha(K)$. Thus, $R(t+1) \leq d(G,C) \leq \alpha(K) R(t)$. \end{proof} \begin{lemma} \label{lem_milieux} Let $A$, $B$, $C$, $D$ and $E$ be five points (some of them may be identical). Let $x = d(A,D)/100$. Assume $d(A,B) \leq x$, $d(A,C) \leq x$, $d(A,E) \leq 100 x$ and $d(D,E) \geq 40 x$. Let $S = \{A,B,C,D,E\}$ and $S' = \bigcup_{\{A,B\} \subseteq S} \{m(A,B)\}$. Then, $D_{\max}(S') \leq 0.99 D_{\max}(S)$. \end{lemma} \begin{proof} As $d(A,D) = 100x$, $D_{\max}(S) \geq 100x$. Let $M_1 = m(A,D)$, $M_2 = m(A,E)$ and $M_3 = m(D,E)$. We have $d(A,M_1) = 50x$ and $d(A,M_2) \leq 50x$. The maximal value of $y = d(A,M_3)$ is reached when $d(A,D) = d(A,E) = 100x$ and $d(D,E) = 40x$. In this case, with the Pythagorean theorem, we have $(100x)^2 = y^2 + (20x)^2$, and thus $y \leq 98x$. Thus, $\max_{i \in \{1,2,3\}} d(A,M_i) \leq 98x$. Now, suppose that $D_{\max}(S') > 99x$. Let $M_4 = m(A,B)$ and $M_5 = m(A,C)$. This would imply that there exists $i \in \{1,2,3\}$ such that either $d(M_i,M_4) > 99x$ or $d(M_i,M_5) > 99x$, and thus, that either $d(A,B) > x$ or $d(A,C) > x$, which is not the case. Thus, $D_{\max}(S') \leq 99x \leq 0.99 D_{\max}(S)$.\end{proof} \begin{lemma} \label{lem3A} Let $t$ be a given time. If $n = 5$ and $|\Omega(t)| = 5$, then one of the following propositions is true: \\(1) $|\Omega(t+1)| \leq 4$ \\(2) $R(t+1) \leq \alpha(1000) R(t)$ \\(3) $d_{\max}(t+1) \leq 0.99 d_{\max}(t)$ \end{lemma} \begin{proof} Suppose that (1) and (2) are false. According to Lemma~\ref{lemKalpha}, (2) being false implies that $R(t) > 1000 d_{\min}(t)$. Let $A_0$ and $B_0$ be two points of $\Omega(t)$ such that $d(A_0,B_0)$ $= d_{\min}(t)$. As $|\Omega(t+1)| = 5$, it implies that the processes at $A_0$ and $B_0$ did not both move to $m(A_0,B_0)$. Therefore, there is a point $C$ of $\Omega(t)$ such that $d(A_0,C)$ $= d_{\min}(t)$ or $d(B_0,C) = d_{\min}(t)$. If $d(A_0,C) = d_{\min}(t)$, let $A = A_0$ and $B = B_0$. Otherwise, let $A = B_0$ and $B = A_0$. As $R(t) > 1000 d_{\min}(t)$, there exists a point $D_0$ of $\Omega(t)$ such that $d(A,D_0) \geq 100 d_{\min}(t)$. Let $E_0$ be the fifth point of $\Omega(t)$. If $d(A,D_0) \geq d(A_0,E_0)$, let $D = D_0$ and $E = E_0$. Otherwise, let $D = E_0$ and $E = D_0$. Finally, let $x = d(A,D)/100$. Thus, we have $d(A,B)$ $\leq x$, $d(A,C) \leq x$ and $d(A,E) \leq 100x$. If $d(D,E) < 40x$, then the processes at positions $D$ and $E$ both move to $m(D,E)$, and $|\Omega(t+1)| = 4$: contradiction. Thus, $d(D,E) \geq 40x$. Let $S = \Omega(t)$, and let $S' = \bigcup_{\{A,B\} \subseteq S} \{m(A,B)\}$. Then, according to Lemma~\ref{lem_milieux}, \\$D_{\max}(S') \leq 0.99 D_{\max}(S)$. As the processes move according to the MM algorithm, $\Omega(t+1) \subseteq S'$, and $d_{\max}(t+1) \leq D_{\max}(S') \leq 0.99 D_{\max}(S) = 0.99 d_{\max}(t)$. Thus, (3) is true. Therefore, either (1) or (2) are true, or (3) is true.\end{proof} \begin{lemma} \label{lem3B} Let $t$ be a given time. If $|\Omega(t)| = 4$, then one of the following propositions is true: \\(1) $|\Omega(t+1)| \leq 3$ \\(2) $R(t+1) \leq \alpha(1000) R(t)$ \\(3) $d_{\max}(t+1) \leq 0.99 d_{\max}(t)$ \end{lemma} \begin{proof} Suppose that (1) and (2) are false. According to Lemma~\ref{lemKalpha}, (2) being false implies that $R(t) > 1000 d_{\min}(t)$. Let $A$ and $B$ be two points of $\Omega(t)$ such that $d(A,B) = d_{\min}(t)$. As $R(t) > 1000 d_{\min}(t)$, there exists a point $D_0$ of $\Omega(t)$ such that $d(A,D_0) \geq 100 d_{\min}(t)$. Let $E_0$ be the fourth point of $\Omega(t)$. If $d(A,D_0) \geq d(A_0,E_0)$, let $D = D_0$ and $E = E_0$. Otherwise, let $D = E_0$ and $E = D_0$. Let $C = A$ and $x = d(A,D)/100$. Thus, we have $d(A,B) \leq x$, $d(A,C) \leq x$ and $d(A,E) \leq 100x$. If $d(D,E) < 40x$, then the processes at $D$ and $E$ (resp. $A$ and $B$) both move to $m(D,E)$ (resp. $m(A,B)$), and $|\Omega(t+1)| = 2$: contradiction. Thus, $d(D,E) \geq 40x$. Let $S = \Omega(t)$, and let $S' = \bigcup_{\{A,B\} \subseteq S} \{m(A,B)\}$. Then, according to Lemma~\ref{lem_milieux}, $D_{\max}(S') \leq 0.99 D_{\max}(S)$. As the processes move according to the MM algorithm, $|\Omega(t+1)| \subseteq S'$, and $d_{\max}(t+1) \leq D_{\max}(S') \leq 0.99 D_{\max}(S) = 0.99 d_{\max}(t)$. Thus, (3) is true. Therefore, either (1) or (2) are true, or (3) is true.\end{proof} \begin{lemma} \label{lem_r_is_dec} At any time $t$, $R(t+1) \leq R(t)$. \end{lemma} \begin{proof} Suppose the opposite: $R(t+1) > R(t)$. Let $G$ be a point such that, $\forall M \in \Omega(t)$, $d(G,M) \leq R(t)$. If, $\forall M \in \Omega(t+1)$, $d(G,M) \leq R(t)$, then we do not have $R(t+1) > R(t)$. Thus, there exists a point $A$ of $\Omega(t+1)$ such that $d(G,A) > R(t)$. Let $B$ be the previous position of processes at position $A$. As the processes at position $B$ moved to $A$, according to the MM algorithm, there exists a point $C$ of $\Omega(t)$ such that $A = m(B,C)$. As $d(G,B) \leq R(t)$ and $d(G,A) > R(t)$, we have $d(G,C) > R(t)$. Thus, there exists a point $C$ of $\Omega(t)$ such that $d(G,C) > R(t)$: contradiction. \end{proof} \begin{lemma} \label{lem_dmax_dim} At any time $t$, $d_{\max}(t+1) \leq d_{\max}(t)$. \end{lemma} \begin{proof} Suppose the opposite: $d_{\max}(t+1) > d_{\max}(t)$. Let $A$ and $B$ be two points of $\Omega(t+1)$ such that $d(A,B) = d_{\max}(t+1)$. According to the MM algorithm, there exists four points $A_1$, $A_2$, $B_1$ and $B_2$ of $\Omega(t)$ such that $A = m(A_1,A_2)$ and $B = m(B_1,B_2)$. Let $L$ be the line containing $A$ and $B$. Let $A'_1$ (resp. $A'_2$, $B'_1$ and $B'_2$) be the projection of $A_1$ (resp. $A_2$, $B_1$ and $B_2$) on $L$. Then, there exists $i \in \{1,2\}$ and $j \in \{1,2\}$ such that $d(A'_i,B'_j) \geq d(A,B)$. Thus, $d(A_i,B_j) \geq d(A,B) = d_{\max}(t)$: contradiction. \end{proof} \begin{lemma} \label{lemp1p2} Let $n \leq 5$. Let $P_1(t)$ (resp. $P_2(t)$) be the following proposition: $R(t+1) \leq \alpha(1000) R(t)$ (resp. $d_{\max}(t+1) \leq 0.99 d_{\max}(t)$). Let $P(t) = P_1(t) \vee P_2(t)$. If, for any time $t$, $|\Omega(t)| \geq 4$, then $P(t)$ is true infinitely often. \end{lemma} \begin{proof} Let $P^*$ be the following proposition: ``$|\Omega(t)| = 4$'' is true infinitely often. If $P^*$ is false, there exists a time $t'$ such that $\forall t \geq t'$, $|\Omega(t)| = 5$. Thus, the result follows, according to Lemma~\ref{lem3A}. If $P^*$ is true, there exists an infinite set $T = \{t_1,t_2,t_3 \dots \}$ such that $\forall t \in T$, $|\Omega(t)| = 4$. Then, according to Lemma \ref{lem3B}, $P(t+1)$ is true $\forall t \in T$. Thus, the result follows. \end{proof} \begin{lemma} \label{lem_bloc_1_2} Let $n \leq 5$. Suppose that, for any time $t$, $|\Omega(t)| \geq 4$. Then, for any time $t$, there exists a time $t' > t$ such that $R(t') \leq \alpha(1000) R(t)$. \end{lemma} \begin{proof} Suppose the opposite: there exists a time $t_0 $ such that, $\forall t > t_0$, $R(t) > \alpha(1000) R(t_0)$. Consider the propositions $P_1(t)$ and $P_2(t)$ of Lemma \ref{lemp1p2}. Then, $\forall t \geq t_0$, $P_1(t)$ is false. Thus, according to Lemma \ref{lemp1p2}, it implies that $P_2(t)$ is true infinitely often. Let $t' > t_0$ be such that, between time $t_0$ and time $t'$, $P_2(t)$ is true at least $200$ times. According to Lemma~\ref{lem_dmax_dim}, for any time $t$, we have $d_{\max}(t+1) \leq d_{\max}(t)$. Thus, $d_{\max}(t') \leq 0.99^{200} d_{\max}(t_0) \leq d_{\max}(t_0)/4$. For any time $t$, $d_{\max}(t) \geq R(t)$ and $d_{\max}(t) \leq 2R(t)$. Thus, $R(t') \leq R(t_0)/2 \leq \alpha(1000) R(t_0)$: contradiction. Thus, the result follows. \end{proof} \begin{lemma} \label{lem_dgm_dec} Let $G$ be a point such that, $\forall M \in \Omega(t)$, $d(G,M) \leq R(t)$. Then, $\forall M \in \Omega(t+1)$, $d(G,M) \leq R(t)$. \end{lemma} \begin{proof} Suppose the opposite: there exists a point $K$ of $\Omega(t+1)$ such that $d(G,K) > R(t)$. According to the MM algorithm, there exists two points $A$ and $B$ of $\Omega(t)$ such that $K = m(A,B)$. Then, as $d(G,K) > R(t)$, either $d(G,A) > R(t)$ or $d(G,B) > R(t)$: contradiction. Thus, the result follows. \end{proof} \begin{lemma} \label{lemshrink2rt} $\forall i \in \{1,\dots,d\}$ and for any two instants $t$ and $t' > t$, $|X_i(t') - X_i(t)| \leq 2R(t)$. \end{lemma} \begin{proof} For any point $M$, let $x_i(M)$ be the $i^{th}$ coordinate of $M$. Let $G$ be a point such as described in Lemma~\ref{lem_dgm_dec}. According to Lemma~\ref{lem_dgm_dec}, $\forall M \in \Omega(t+1)$, $|x_i(M) - x_i(G)| \leq R(t)$. By induction, $\forall t' > t$ and $\forall M \in \Omega(t')$, $|x_i(M) - x_i(G)| \leq R(t)$. In particular, $|X_i(t) - x_i(G)| \leq R(t)$ and $|X_i(t') - x_i(G)| \leq R(t)$. Thus, $|X_i(t') - X_i(t)| \leq 2R(t)$. \end{proof} \begin{lemma} \label{lemcauchy} Let $(u_k)_k$ be a sequence, Let $\alpha \in ]0,1[$ and let $N$ be an integer. If $\forall k \geq N$, $|u_{k+1} - u_k| \leq \alpha^k$, then $(u_k)_k$ converges. \end{lemma} \begin{proof}As $\alpha \in ]0,1[$, $S_{\alpha} = 1 + \alpha + \alpha^2 + \alpha^3 + \dots$ converges. Let $\epsilon > 0$. Let $K = \log ( \epsilon / S_{\alpha} ) / \log \alpha$ Then, $\alpha^K S_{\alpha} = \epsilon$. Let $k \geq \max(K,N)$ and let $m > k$. $|u_m - u_k| \leq \Sigma_{i = k}^{i = m-1} |u_{i+1} - u_i| \leq \Sigma_{i = k}^{i = m-1} \alpha^i \leq \alpha^k S_{\alpha} \leq \alpha^K S_{\alpha} = \epsilon$ Thus, $(u_k)_k$ is a Cauchy sequence and it converges.\end{proof} \begin{lemma} \label{lem_bloc_2_2} Let $\alpha \in ]0,1[$. If, for any time $t$, there exists a time $t' > t$ such that $R(t') \leq \alpha R(t)$, then the MM algorithm solves the convergence problem. \end{lemma} \begin{proof} Let $t_0$ be an arbitrary time. $\forall k \geq 0$, we define $t_{k+1} > t_k$ as the first time such that $R(t_{k+1}) \leq \alpha R(t_k)$. By induction, $\forall k \geq 0$, $R(t_k) \leq \alpha^k R(t_0)$. Let $i \in \{1,\dots,d\}$. According to Lemma~\ref{lemshrink2rt}, $\forall k \geq 0$, we have $|X_i(t_{k+1})-X_i(t_k)| \leq 2R(t_k) \leq 2 \alpha^k R(t_0)$. $\forall k \geq 0$, let $u_k = X_i(t_k)/(2R(t_0))$. Then, $\forall k \geq 0$, $|u_{k+1} - u_k| \leq \alpha^k$. According to Lemma~\ref{lemcauchy}, the sequence $(u_k)_k$ converges and so does $(X_i(t_k))_k$. Let $L_i$ be the limit of $(X_i(t_k))_k$, and let $G$ be the point of coordinates $(L_1, L_2,$ $\dots, L_d)$. $R(t_k)$ decreases exponentially with $k$. Then, $\forall \epsilon > 0$, there exists an integer $k$ such that $R(t_k) < \epsilon/2$. According to Lemma~\ref{lem_r_is_dec}, $\forall t > t_k$, $R(t) \geq R(t_k)$. Therefore, the processes are $(G,\epsilon)$-gathered $\forall t \geq t_k$, and the convergence problem is solved.\end{proof} \begin{lemma} \label{lem_convv_poss} If $d = 1$ or $n \leq 5$, the MM algorithm solves the convergence problem. \end{lemma} \begin{proof} If $d = 1$, according to Lemma~\ref{lemd1}, the MM algorithm solves the gathering problem, and thus the convergence problem. Now, suppose that $n \leq 5$. Suppose that, for any time $t$, $|\Omega(t)| \geq 4$. Then, according to Lemma~\ref{lem_bloc_1_2} and Lemma~\ref{lem_bloc_2_2}, the MM algorithm solves the convergence problem. Otherwise, i.e., if $|\Omega(t)| \leq 3$, then according to Lemma~\ref{lem_of_3}, the MM algorithm solves the convergence problem. \end{proof} \begin{lemma} \label{lem_convv_imposs} If $d \geq 2$ and $n \geq 6$, the convergence problem is impossible to solve. \end{lemma} \begin{proof} Assume the opposite: there exists an algorithm that always solves the convergence problem for $d \geq 2$ and $n \geq 6$. First, assume that $\Omega$ contains $3$ points such as described in the proof of Lemma~\ref{lem3pt}. Consider the infinite execution described in the proof of Lemma~\ref{lem3pt}. Let $G$ be the barycenter of these $3$ points. Let $P$ be the following proposition: there exists a constant $D$ such that the distance between $G$ and any of the $3$ points of $\Omega$ is at most $D$. If $P$ is false, then by definition, the convergence problem cannot be solved. We now consider the case where $P$ is true. If $P$ is true, then consider the following case: $\Omega$ contains $6$ points $K_1$, $K_2$, $K_3$, $K_4$, $K_5$ and $K_6$. $K_1$, $K_2$ and $K_3$ are arranged such as described in the proof of Lemma~\ref{lem3pt}, and so are $K_4$, $K_5$ and $K_6$. Let $G$ (resp $G'$) be the barycenter of the triangle formed by $K_1$, $K_2$ and $K_3$ (resp. $K_4$, $K_5$ and $K_6$). Assume that $d(G,G') = 10D$. Now, assume that the points of the two triangles respectively follow the infinite execution described in the proof of Lemma~\ref{lem3pt}. Then, the distance between any two of the $6$ points is always at least $8D$, and the convergence problem cannot be solved.\end{proof} \textbf{Theorem~\ref{th_lb_conv}.} \emph{The convergence problem can be solved if and only if $d = 1$ or $n \leq 5$. When it can be solved, the MM algorithm solves it.} \begin{proof} The result follows from Lemma~\ref{lem_convv_poss} and Lemma~\ref{lem_convv_imposs}. \end{proof} \section{Breaking symmetry} \label{secpos} We showed that the problems were impossible to solve for $n \geq 6$. This is due to particular configurations where a process $p$ has several ``closest neighbors'' (i.e., $|N_p| > 1$). Until now, we assumed that the actual closest neighbor $C(p)$ of $p$ was chosen in $N_p$ by an external adversary. We now assume that, whenever $|N_p| > 1$, $C(p)$ is chosen deterministically, according to an \emph{order} on the positions of processes. Namely, we assume that there exists an order ``$<$'' such that any set of distinct points can be ordered from ``smallest'' to ``largest'' ($A_1 < A_2 < A_3 < \dots < A_k$). Let $L(p)$ be the largest element of $N_p$, that is: $\forall q \in N_p - \{L(p)\}$, $M_q < M_{L(p)}$. We now assume that, for any process $p$, $C(p) = L(p)$. With this new hypothesis, we show the following result. \begin{theorem} \label{th_mm} $\forall n \geq 2$, the MM algorithm solves the gathering problem in $n - 1$ steps, and no algorithm can solve the gathering problem in less that $n - 1$ steps. \end{theorem} \subsection*{Proof} \begin{lemma} \label{lem_lb_mm} $\forall n \geq 2$, no algorithm can solve the gathering problem in less than $n - 1$ steps. \end{lemma} \begin{proof} Suppose the opposite: there exists an algorithm $X$ solving the gathering problem in less than $n - 1$ steps. First, consider a case with two processes, initially at two distinct positions. Then, eventually, the two processes are gathered. Let $t$ be the first time where the two processes are gathered. Let $A$ and $B$ be their position at time $t - 1$, and let $D = d(A,B)$. By symmetry, the two processes should move to $m(A,B)$ at time $t$. Thus, with algorithm $X$, whenever a process $p$ is such that $d(M_p,M_{C(p)}) = D$, $p$ moves to $m(M_p,M_{C(p)})$ at the next step. Let $K(x)$ be the point of coordinates $(x,0,0,\dots,0)$. Now consider $n$ processes, a set $\Omega(0) = \bigcup_{i \in \{0,\dots,n-1\}}$ $\{K(iD)\}$, and an order such that, $\forall x < y$, $K(x) < K(y)$.\footnote{As this is a lower bound proof, our goal here is to exhibit one particular situation where no algorithm can solve the problem in less than $n-1$ steps. Thus, we choose a worst-case configuration with a worst-case order.} Let us prove the following property $P_k$ by induction, $\forall k \in \{0,\dots,n-1\}$: \\$\Omega(k) = \bigcup_{i \in \{0,\dots,n-k-1\}} \{K((i + k/2)D)\}$ \begin{itemize} \item $P_0$ is true, as $\Omega(0) = \bigcup_{i \in \{0,\dots,n-1\}} \{K(iD)\}$. \item Suppose that $P_k$ is true for $k \in \{0,\dots,n-2\}$. Then, according to algorithm $X$, the processes at position $K((n-k-1 + k/2)D)$ moves to $K((n-k-1 + (k-1)/2)D)$, and $\forall i \in \{0,\dots,n-k-2\}$, the processes at position $K((i + k/2)D)$ move to $K((i + (k+1)/2)D)$. Thus, $P_{k+1}$ is true.\end{itemize} Therefore, $\forall t \in \{0,\dots,n-2\}$, $|\Omega(t)| \geq 2$, and the processes are not gathered: contradiction. Thus, the result follows.\end{proof} We now assume that the processes move according to the MM algorithm. \begin{lemma} \label{lem_twoproc} Let $p$ and $q$ be two processes. If there exists a time $t$ where $M_p = M_q$, then at any time $t' > t$, $M_p = M_q$. \end{lemma} \begin{proof} Consider the configuration at time $t$. According to our new hypothesis, $C(p) = C(q)$. Let $K = m(M_p,M_{C(p)}) = m(M_q,M_{C(q)})$. According to the MM algorithm, $p$ and $q$ both move to $K$. Thus, at time $t+1$, we still have $M_p = M_q$. Thus, by induction, the result.\end{proof} \begin{lemma} \label{lem_notgaz} At any time $t$, if the processes are not gathered, there exists two processes $p$ and $q$ such that $M_p \neq M_q$, $p = C(q)$ and $q = C(p)$. \end{lemma} \begin{proof} Let $\delta = \min_{\{A,B\} \subseteq \Omega(t)} d(A,B)$. Let $Z$ be the set of processes $p$ such that $d(M_p,M_{C(p)}) = \delta$. Let $Z' = \bigcup_{p \in Z } \{p, C(p)\}$. Let $A$ be the point of $Z'$ such that, $\forall M \in Z' - \{A\}$, $M < A$. Let $p$ be a process at position $A$. Let $q$ be the largest element of $N_p$, that is: $\forall q' \in N_p - \{q\}$, $M_{q'} < M_q$. By definition, $M_p \neq M_q$. Thus, according to our new hypothesis, $q = C(p)$. Then, note that $p$ is also the largest element of $N_q$: $\forall p' \in N_q - \{p\}$, $M_{p'} < M_p$. Thus, $p = C(q)$. Thus, the result follows. \end{proof} \begin{lemma} \label{lem_indec} At any time $t$, if the processes are not gathered, then $|\Omega(t+1)| \leq |\Omega(t)| - 1$. \end{lemma} \begin{proof} Let $p$ and $q$ be the processes described in Lemma \ref{lem_notgaz}. Let $K = m(M_p,M_q)$. Then, according to Lemma~\ref{lem_notgaz}, the processes at position $M_p$ and $M_q$ both move to position $K$. Let $X = \Omega(t) - \{M_p,M_q\}$. According to Lemma~\ref{lem_twoproc}, the processes occupying the positions of $X$ cannot move to more than $|X|$ new positions. Thus, $|\Omega(t+1)|$ is at most $|\Omega(t)| - 1$. Thus, the result follows.\end{proof} \begin{lemma} \label{lem_pre_th_mm} $\forall n \geq 2$, the MM algorithm solves the gathering problem in at most $n-1$ steps. \end{lemma} \begin{proof} According to Lemma~\ref{lem_indec}, there exists a time $t \leq n-1$ such that $|\Omega(t)| = 1$. Let $A$ be the only point of $\Omega(t)$. Then, according to the MM algorithm, the processes do not move from position $A$ in the following steps. Thus, the result follows. \end{proof} \textbf{Theorem~\ref{th_mm}}. \textit{$\forall n \geq 2$, the MM algorithm solves the gathering problem in $n - 1$ steps, and no algorithm can solve the gathering problem in less that $n - 1$ steps.} \begin{proof} The result follows from Lemma~\ref{lem_lb_mm} and Lemma~\ref{lem_pre_th_mm}. \end{proof} \section{Fault tolerance} \label{secft} We now consider the case of \emph{crash failures}: some processes may lose the ability to move, without the others knowing it. Let $C \subseteq P$ be the set of crashed processes (the other processes are called ``correct''), and let $S_c = \bigcup_{p \in C} \{M_p\}$ (i.e., the set of positions occupied by crashed processes). Let $f = |S_c|$. We prove the two following results. \begin{theorem} \label{th_fault_1} The gathering problem can only be solved when $f = 0$. \end{theorem} \begin{theorem} \label{th_fault_2} The convergence problem can be solved if and only if $f \leq 1$. When $f \leq 1$, the MM algorithm solves it. \end{theorem} \subsection*{Proof} We say that a process $p$ is \emph{attracted} if there exists a sequence of processes $(p_1,\dots,p_m)$ such that $p = p_1$, $p_m \in C$, and $\forall i \in \{1,\dots,m-1\}$, $C(p_i) = p_{i+1}$. A \emph{loop} is a sequence of correct processes $(p_1,\dots,p_m)$ such that $C(p_m) = p_1$ and, $\forall i \in \{1,\dots,m-1\}$, $C(p_i) = p_{i+1}$. A \emph{pair} is a loop with $2$ processes. Let $\Omega' = \bigcup_{p \in P - C} \{M_p\}$ (i.e., the set of positions occupied by \emph{correct} processes). Let $\Omega'(t)$ be the state of $\Omega'$ at time $t$. \begin{lemma} \label{lemft0} Consider an algorithm for which there exists $w$ such that $f_x(w) = w$ and $f_y(w) = 0$. Then, this algorithm cannot solve the gathering nor the convergence problem. \end{lemma} \begin{proof} Assume the opposite. Consider a situation where $\Omega = \{A,B\}$, with $d(A,B) = w$. Then, according to the algorithm, the processes at position $A$ and $B$ switch their positions endlessly, and neither converge nor gather: contradiction. Thus, the result follows. \end{proof} \textbf{Theorem~\ref{th_fault_1}.} \emph{The gathering problem can only be solved when $f = 0$.} \begin{proof} If $f \geq 2$, by definition, the processes cannot be gathered. Now, suppose $f = 1$. Suppose the opposite of the claim: there exists an algorithm solving the gathering problem when $f = 1$. Let $P$ be the following proposition: there exists two points $A$ and $B$ such that all crashed processes are in position $A$, and all correct processes are in position $B$. Consider an initial configuration where $P$ is true. As the algorithm solves the gathering problem, according to Lemma~\ref{lemft0}, the next position of correct processes cannot be $A$. Thus, $P$ is still true at the next time step, with a different point $B$. Therefore, by induction, $P$ is always true, and the processes are never gathered: contradiction. Thus, the result follows. \end{proof} \begin{lemma} \label{lem_exloop} If there exists a process $p$ which is not attracted, then there exists a loop. \end{lemma} \begin{proof} Suppose the opposite: there is no loop. Let $p_1 = p$. $\forall i \in \{1,\dots,n\}$, let $p_{i+1} = C(p_i)$. We prove the following property $P_i$ by induction, $\forall i \in \{1,\dots,n+1\}$: $(p_1,\dots,p_i)$ are $i$ distinct processes. \begin{itemize} \item $P_1$ is true. \item Suppose that $P_i$ is true for some $i \in \{1,\dots,n\}$. As there is no loop, we cannot have $p_{i+1} \in \{p_1,\dots,p_i\}$. Thus, $P_{i+1}$ is true. \end{itemize} Thus, $P_{n+1}$ is true, and there are $n+1$ distinct processes: contradiction. Thus, the result follows.\end{proof} \begin{lemma} \label{lem_loopair} All loops are pairs. \end{lemma} \begin{proof} Let $(p_1,\dots,p_m)$ be a loop. Let $\delta = \min_{i \in \{1,\dots,m\}}$ $d(M_{p_i},M_{C(p_i)})$. Let $Z$ be the set of processes of $\{p_1,\dots,$ $p_m\}$ such that $d(M_{p_i},M_{C(p_i)}) = \delta$. Let $Z' = \bigcup_{p \in Z}$ $\{p,C(p)\}$. Let $p$ be the process such that, $\forall q \in Z'$ such that $M_p \neq M_q$, $M_p > M_q$. Let $q = C(p)$. As $C(q)$ is the closest neighbor of $p$, $C(q) \in Z'$. Then, according to the definition of $p$, $C(q) = p$. Therefore, $(p_1,\dots,p_m)$ is either $(p,q)$ or $(q,p)$. Thus, the result follows. \end{proof} \begin{lemma} \label{lem_omdec} If there exists a pair, then $|\Omega'(t+1)| \leq |\Omega'(t) - 1|$. \end{lemma} \begin{proof} According to the algorithm, two processes at the same position at time $t$ are at the same position at time $t+1$. Let $(p,q)$ be a pair. Then, according to the algorithm, the processes at positions $M_p$ and $M_q$ move to $m(M_p,M_q)$, and $|\Omega'(t+1)| \leq |\Omega'(t) - 1|$. \end{proof} \begin{lemma} \label{lem_t_a} There exists a time $t_A$ such that, for any time $t \geq t_A$, all correct processes are attracted. \end{lemma} \begin{proof} Suppose the opposite. Then, after a finite number of time steps, at least one correct process is not attracted. Thus, according to Lemma~\ref{lem_exloop}, there exists a loop. According to Lemma~\ref{lem_loopair}, this loop is a pair. Then, according to Lemma~\ref{lem_omdec}, $|\Omega'|$ decreases. We can repeat this reasoning $n + 1$ times, and we then have $|\Omega'| < 0$: contradiction. Thus, the result follows. \end{proof} \begin{lemma} \label{lem_l_sur_n} Suppose $f = 1$. Let $p$ be an attracted process, and let $L$ be the distance between $p$ and the crashed processes. Then, $d(M_p,M_{C(p)}) \geq L/n$. \end{lemma} \begin{proof} Suppose the opposite: $d(M_p,M_{C(p)}) < L/n$. As $p$ is attracted, there exists a sequence of processes $(p_1,\dots,$ $p_m)$ such that $p = p_1$, $p_m \in C$, and $\forall i \in \{1,\dots,m-1\}$, $C(p_i) = p_{i+1}$. $\forall i \in \{1,\dots,m-2\}$, we have $d(M_{p_i}, M_{p_{i+1}}) \geq$ \\$d(M_{p_{i+1}}, M_{p_{i+2}})$. Indeed, suppose the opposite. Then, $C(p_{i+1}) = p_{i+2}$, $d(M_{p_{i+1}}, M_{C(p_{i+1})}) > d(M_{p_{i+1}},M_{p_i})$, and $C(p_{i+1})$ is not a closest neighbor of $p_{i+1}$: contradiction. Thus, $d(M_{p_i}, M_{p_{i+1}}) \geq d(M_{p_{i+1}},M_{p_{i+2}})$. Thus, $\forall i \in \{1,\dots,m-1\}$, $d(p_i,p_{i+1}) < L/n$. Therefore, $d(p_1,p_m) \leq (m-1)L/n < L$: contradiction. Thus, the result follows. \end{proof} \begin{lemma} \label{lem_k_n} Let $f = 1$, and let $X$ be the position of crashed processes. Let $L = \max_{p \in P} d(X,M_p)$. Let $L(t)$ be the value of $L$ at time $t$. Suppose that all correct processes are attracted. Then, for any time $t$, $L(t+1) \leq k(n)L(t)$, where $k(n) = \sqrt{1 - 1/(2n)^2}$. \end{lemma} \begin{proof} At time $t + 1$, let $p$ be a process such that $d(X,M_p)$ $= L(t+1)$. Let $K$ be the position of $p$ at $t+1$. Then, according to the algorithm, at time $t$, there exists two processes $q$ and $r$ at position $A$ and $B$ such that $K = m(A,B)$. Let $L' = \max(d(X,A),d(X,B))$. Let $q' \in \{q,r\}$ be such that $d(X,M_{q'}) = L'$. Then, according to Lemma~\ref{lem_l_sur_n}, $d(M_{q'},M_{C(q')}) \geq L'/n$. Let $r'$ be the other process of $\{q,r\}$. Then, the position of $r$ maximizing $d(X,K)$ is such that $d(X,M_{r'}) = L'$. Therefore, according to the Pythagorean theorem, $(L(t+1))^2$ is at most $L'^2 - (L'/(2n))^2$, and $L(t+1) \leq k(n)L' \leq k(n)L(t)$. Thus, the result follows. \end{proof} \begin{lemma} \label{lemconv_f1} If $f = 1$, the MM algorithm solves the convergence problem. \end{lemma} \begin{proof} According to Lemma~\ref{lem_t_a}, there exists a time $t_A$ after which all correct processes are attracted. We now suppose that $t \geq t_A$. Let $\epsilon > 0$. Let $X$ be the position of crashed processes, and let $L = \max_{p \in P} d(X,M_p)$. As $k(n) =$ \\ $\sqrt{1 - 1/(2n)^2} < 1$, let $M$ be such that $k(n)^M L < \epsilon$. Then, according to Lemma~\ref{lem_k_n}, at time $t_A + M$, all processes are at distance at most $\epsilon$ from $X$. Thus, the result follows. \end{proof} \textbf{Theorem~\ref{th_fault_2}.} \emph{The convergence problem can be solved if and only if $f \leq 1$. When $f \leq 1$, the MM algorithm solves it.} \begin{proof} When $f \geq 2$, there exists at least two crashed processes that will stay at the same position forever. Thus, the convergence problem cannot be solved. When $f \leq 1$, according to Lemma~\ref{lemconv_f1}, the MM algorithm solves the convergence problem. Thus, the result follows. \end{proof} \section{Conclusion} \label{sec_conc} In this paper, we revisited the gathering and convergence problems with a minimalist hypothesis on visibility. We showed that this model only allows a small number of processes to converge, but requires an additional symmetry-breaking hypothesis to gather an arbitrarily large number of processes. For the convergence problem, up to one crash failure can be tolerated. This first work can be the basis for many extensions. For instance, we could consider a more general scheduler (e.g. asynchronous). We could investigate how resilient this model is to crash or Byzantine failures. We could also consider the case of voluminous processes, that cannot be reduced to one geometrical point. \section*{Acknowledgments} This work has been supported by the Swiss National Science Foundation (Grant 200021\_169588 TARBDA). \bibliographystyle{plain} \input{biblio.bbl} \end{document}
{'timestamp': '2019-06-17T02:15:42', 'yymm': '1906', 'arxiv_id': '1906.06239', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06239'}
arxiv
\section{Introduction} Forecasting electricity prices is an important task in an energy utility and needed not only for proprietary trading but also for the optimisation of power plant production schedules and other technical issues. A promising approach in power price forecasting is based on a recalculation of the order book using forecasts on market fundamentals like demand or renewable infeed. However, this approach requires extensive statistical analysis of market data. In this paper, we examine if and how this statistical work can be reduced using machine learning. Our paper focuses on two research questions: \begin{itemize} \item How can order books from electricity markets be included in machine learning algorithms? \item How can order-book-based spot price forecasts be improved using machine learning? \end{itemize} \begin{figure}[tb] \includegraphics[width=.49\textwidth]{Preise2018.png} \includegraphics[width=.49\textwidth]{PreiseSep2018.png} \caption{Example electricity price time series on different time scales.} \label{fig:prices} \end{figure} We consider the German/Austrian EPEX spot market for electricity. There is a daily auction for electricity with delivery the next day. All 24 hours of the day are traded as separate products. Figure~\ref{fig:prices} shows auction results on different time scales. The pronounced seasonality of prices is visible as well as their high volatility.\footnote{Another interesting property is that in contrast to price series of other commodities or stocks, electricity prices may become negative.} \begin{figure}[tb] \includegraphics[width=.49\textwidth]{bidaskcurve.png} \includegraphics[width=.49\textwidth]{bidaskcurveZoom.png} \caption{Order book data for a particular hour on different scales.} \label{fig:orderBook} \end{figure} In the following, we shortly explain the idea of order-book-based price forecasts. Each price is the result of an auction, which can be represented as a bid and an ask curve. For a particular hour, those curves are shown in Figure~\ref{fig:orderBook}. The intersection of the bid (purchase, demand) and ask (sell, supply) curve is the market clearing price (MCP). In the magnified figure, it is clearly visible that the bid and ask curves are step functions. Each step width is the cumulated volume which market participants have put in the auction at a certain price. Price levels correspond in fact to the marginal production costs of different power plants. Due to the regulatory environment, in particular renewables bid at negative prices in the auction. Moreover, in contrast to a classical power plant, the produced amount of renewable energy is stochastic and total expected production is sold on the exchange. Relying on those economical circumstances, the order-book-based forecasting modifies the volumes at different price levels in the bid and ask curves. The modifications correspond to the forecasted wind and solar power infeed. An important issue is \textit{which} price levels are influenced by the renewable infeed. Usually, energy utilities use exhaustive statistical analysis on historical data to identify the price levels and the impact of the renewable forecasts. In fact, there are also other fundamental factors which influence the market price, first of all the expected electricity demand. This paper focuses on machine learning methods to reduce the effort for building a forecast model. In the following section we give an overview on existing literature on the economics of electricity markets, order-book-based models and the use of machine learning in price forecasting. In Section~\ref{sec:featureExtraction} we detail our methodology. Section~\ref{sec:results} is devoted to numerical results and a comparison to other models from the literature. Section~\ref{sec:conclusions} concludes. \section{Existing literature on price forecasting and machine learning in electricity markets} Solar and wind energy is playing a more and more prominent role in today's electricity mar\-kets. Empirical studies show that renewable electricity generation is both highly volatile and has a substantial impact on the day-ahead electricity price (\cite{wagner2014}). Using multivariate regression methods, various authors have quantified the influence renewable infeed has on the price (\cite{cludius2014,wuerzburg2013}). This influence can easily be seen graphically, cf. Figure~\ref{fig:windsolarinfluence}. Therefore, we also use expected solar and wind infeed as features for the price forecasts. \begin{figure}[tb] \includegraphics[width=.49\textwidth]{windProfil.png} \includegraphics[width=.49\textwidth]{solarProfil.png} \caption{Influence of wind and solar infeed on price.} \label{fig:windsolarinfluence} \end{figure} There is a vast body of literature on electricity price forecasting, over which \cite{aggarwal2009} give an early overview. Their survey covers 47 papers published between 1997 and 2006 with topics ranging from game theoretic to time series and machine learning models. A more recent extensive literature overview is given by \cite{weron2014}, in which the author distinguishes and describes five model classes for electricity price forecasting, namely game-theoretic, fundamental, reduced-form, statistical and machine learning models. In an empirical study he finds the latter two to yield the best results. The article closes with a discussion of future challenges in the field, including the issues of feature selection, probabilistic forecasts, combined estimators, model comparability and multivariate factor models. Regarding this last aspect, \cite{ziel2018} conduct an empirical comparison of different univariate and multivariate model structures for price forecasting. Comparing a total of 58 models on several datasets, they find that there is no single modelling framework that consistently achieves the best results. Statistical methods which have been applied to price forecasting include, for example, dynamic regression and transfer functions (\cite{nogales2002}), wavelet transformation followed by an ARIMA model (\cite{conejo2005}) and weighted nearest neighbor techniques (\cite{troncoso2007}). There are many applications of machine learning methods in electricity price forecasting.~\cite{amjady2006} compare the performance of a fuzzy neural network with one hidden layer to ARIMA, wavelet-ARIMA, multilayer perceptron and radial basis function network models for the Spanish market.~ \cite{chen2012} also use a neural network with one hidden layer and a special training technique called extreme learning machine on Australian data. On the same market, \cite{mosbah2016} train a multilayer neural network on temperature, total demand, gas price and electricity price data of the year 2005 to predict hourly electricity prices for January 2006. In order to show the superior performance of neural networks compared to time series approaches, \cite{keles2016} conduct an extensive study focussing on the important topics of variable selection and hyperparameter optimisation. They select the most predictive features via a k-nearest neighbor backward elimination approach and employ 6-fold cross-validation to optimise forecasting performance over several hyperparameters of the neural network. The resulting network is found to outperform the benchmark models substantially. Recently, more sophisticated types of neural networks have been used: In a benchmark study, \cite{lago2018} compare feed-forward neural networks with up to 2 hidden layers, radial basis function networks, deep belief networks, convolutional neural networks, simple recurrent neural networks, LSTM and GRU networks to several statistical and also to other machine learning methods like random forests and gradient boosting. Using the Diebold-Mariano test, they show the deep feed-forward, GRU and LSTM network approaches to perform significantly better than most of the other methods on Belgium market data.~ \cite{marcjasz2018} consider a non-linear autoregressive (NARX) neural network-type model which especially accounts for the long-term price seasonality. Also using the Diebold-Mariano test, they show that this approach can improve the accuracy of day-ahead forecasts relative to the corresponding ARX benchmark. Among the features considered in the aforementioned studies historical electricity prices, total demand series, total demand prognoses, renewable infeed forecasts, weather data and calendar information appear on a regular basis. On the other hand, to the best of our knowledge, the first to use supply and demand curves for price prediction are \cite{ziel2016}. Their goal is to fill the gap between time series analysis and structural analysis by setting up a time series model for these curves and then forecasting the future market clearing price as the intersection of the corresponding forecasted curves. They compare multiple time series prediction methods based on this approach. However, they do not investigate whether the performance of their model can be enhanced by machine learning techniques. \section{Methodology} \label{sec:featureExtraction} \paragraph{Data preparation and feature extraction from order book} Our dataset ranges from 1/2/2015 to 18/9/2018 (31823 single auctions) and includes order book data from the EPEX German/Austrian electricity spot market, transparency data from EEX on expected wind and solar power infeed, and expected total demand data from ENTSO-E. To avoid data dredging, $20\%$ (about 9~months) of the available data at the end of the time period are held back for an out-of-sample model evaluation (see Section~\ref{sec:results}). For feature extraction, i.e., translating the order book into a vector of numbers, we use ideas from \cite{coulon2014} and \cite{ziel2016}. Let $\mathbb{P} := \{-500, -499.9, \dots, 2999.9, 3000\}$ be the set of possible prices and $\mathbb{T} := \{t_1, t_2, \dots, t_{T-1}, t_T\}$ the set of time points for which there are data available. Each $t = (d, h)\in\mathbb{T}$ is a tuple consisting of a date $d$ and an hour $h\in\{0, 1, \dots, 23\}$. We represent the supply and demand data at time $t\in\mathbb{T}$ as vectors $\left(V_t^S(P)\right)_{P\in\mathbb{P}}$ and $\left(V_t^D(P)\right)_{P\in\mathbb{P}}$, where $V_t^S(P)$ and $V_t^D(P)$ denote the supply and demand volume, respectively, bid at price level $P\in\mathbb{P}$. The market clearing price at time $t$ is determined by EPEX via the EUPHEMIA algorithm, which also considers complex orders. There is no information about such orders in our dataset, so it would be unreasonable to expect any learning algorithm to incorporate them into its price prediction. Therefore, we calculate the market clearing price that would result from considering only the available supply and demand data and use this as the target value for price prediction. To this end, we define the so-called supply and demand curves \begin{align} S_t(P) &:= \sum\limits_{p\in\mathbb{P}, \, p\leq P} V_t^S(p) \text{ and} \\ D_t(P) &:= \sum\limits_{p\in\mathbb{P}, \, p\geq P} V_t^D(p). \end{align} The MCP $P_t^*$ lies at the intersection of the supply and demand curves. As $S_t$ and $D_t$ are step functions, explicit formulae for $P_t^*$ are quite technical and therefore omitted. We refer to Figure~\ref{fig:orderBook} for a graphical illustration. To reduce the dimensionality, we partition $\mathbb{P}$ into price classes and use the volumes per price class as features. To determine the price classes we use a heuristic which aims to achieve that all price intervals contain the same amount of volume on average. This algorithm ensures that there are more price classes at the interesting parts of the curve, i.e., in the price regions with many bids. We begin by averaging the supply and demand curves over all time points. Then, we fix a volume~$V_*$ that each price class is supposed to contain on average and choose price class boundaries $c_0^S, c_1^S, \dots, c_{M^S}^S$ and $c_0^D, c_1^D, \dots, c_{M^D}^D$ accordingly. \begin{figure}[tb] \centering \includegraphics[scale = 0.7]{averageSupplyDemandPriceIntervalls.png} \caption{Averaged supply curve with $V_* = 1000$, figure taken from \cite{ziel2016}.} \label{fig:priceclasses} \end{figure} Again, the mathematical details are rather technical (see also \cite{ziel2016}). However, the graphical illustration in Figure~\ref{fig:priceclasses} should make the idea intuitively clear. Analogously as with the original supply and demand curves, one can calculate the price that results from the price classes and of course, in general, does not exactly coincide with the actual market clearing price~$P_t^*$. Finally, in order to simplify both implementation and interpretation without losing any essential information, we transform the supply and demand features into a so-called price curve. For this, let $\{c_0^X, c_1^X, \dots, c_{M^X}^X\}$ be the ascendingly ordered union of the supply and demand price class boundaries. Now, we define new price classes \begin{equation} \mathbb{C}_k^X := \begin{cases} [c_{k-1}^X, c_k^X) & \text{for } k = 1, \dots, M^X-1 \\ [c_{k-1}^S, c_k^S] & \text{for } k = M^X \end{cases}, \end{equation} and volume features \begin{equation} V_t^X\left(\mathbb{C}_k^X\right) := \sum\limits_{P\in\mathbb{C}_k^X} \left(V_t^S(P) + V_t^D(P)\right). \end{equation} We use these price curve features and additionally the total demand $D_t(-500)$ as inputs for the price prediction. Figure~\ref{fig:pricecurve} shows an example of such a price curve calculated from given supply and demand curves. \begin{figure}[tb] \includegraphics[width=\textwidth]{meritOrderTrans.png} \caption{Transformed supply and demand curves to price curve (dotted black) and inelastic demand (dotted green).} \label{fig:pricecurve} \end{figure} There is also an economic interpretation for this transformation: In fact, electricity demand is highly price-inelastic, so the constant inelastic demand is the expected total demand for electricity at that hour. The price curve is the so-called merit order, which represents the electricity production units sorted by their variable production costs. For more details, we refer to standard literature on electricity markets like \cite{burger2014}. Note that the price curve still contains the information that is necessary to calculate the resulting price: The MCP lies at the intersection of the cumulative price curve and the constant inelastic demand. In addition to the price curve and inelastic demand, we use renewable infeed and total demand forecasts as features as well as some calendar information, namely \begin{itemize} \item year as a numerical variable, \item a binary variable on daylight saving time, \item type of day as a one-hot-encoded categorical variable with three different values (workday, Saturday/bridge day, Sunday/holiday), \item month, and \item hour. \end{itemize} To account for the periodicity of months and hours, we project these values on a circle and use the two-dimensional projections as features. For example, if date $t\in\mathbb{T}$ lies in month $m\in\{1, \dots, 12\}$, this is encoded as \begin{align} \text{month}_x(t) &:= \sin\left(\frac{2\pi m}{12}\right), \, \text{month}_y(t) := \cos\left(\frac{2\pi m}{12}\right). \end{align} For prediction, we use the price curve features of a preceding day, the so-called reference date $r(d)$. For notational convenience, we write $r(t) := (r(d), h)$. As a reference date for $d$ we use the nearest day before $d$ which is of the same type of day as $d$. This is a simple but efficient technique in energy economics. More sophisticated methods to define a reference date may incorporate similarities in renewable infeed and demand profile. \paragraph{Training of learning algorithms} \label{sec:algorithms} We employ ordinary linear regression, random forests and feed-forward neural networks to predict hourly electricity prices. Note that we use the prices which are implied by the volume features $V_t^X(\mathbb{C}_k^X)$ as target values, which means that the prices we aim to forecast attain the values $c_0^X, c_1^X, \dots, c_{M^X}^X$. On the whole dataset, the absolute difference between these price approximations and the real prices is $2.07$ EUR/MWh on average (corresponding to a median absolute percentage deviation of $4.28\%$). While we assume ordinary linear regression to be well-known, we give a brief description of the machine learning algorithms we consider. In each case, our goal is to approximate the function~$f:\mathbb{R}^N\to\mathbb{R}$ which maps the features described above to the corresponding electricity price. To this end, we assume to be given a set of training data $\{(x_1, y_1), \dots, (x_n, y_n)\}$ where \begin{equation} y_i = f(x_i) + \varepsilon_i, x_i\in\mathbb{R}^N, i = 1, \dots, n, \end{equation} and $\left(\varepsilon_1, \dots, \varepsilon_n\right)$ is a vector of realizations of independent random variables with zero expectation and equal variance. \paragraph{Random forests} Random forests are based on a simpler machine learning method called decision trees (\cite[chapter 9.2]{hastie2001}). While decision trees are easy to understand, they often perform rather poorly because of their high dependence on the training data. Random forests aim to overcome this drawback by averaging the predictions of several decision trees that are trained in a randomized way proceeding from the same data (\cite{breiman2001}). As part of their training process, random forests offer a convenient way to assess the influence of each feature on the output. Therefore, they can deliver a ranking of the features according to their relevance for electricity price prediction. While it is quite interesting in its own right, we also use this ranking for feature selection, i.e., for training a feed-forward neural network only on the $N_F\in\mathbb{N}$ most important features (e.g. $N_F = 10$). \paragraph{Feed-forward neural networks} Feed-forward neural networks can be viewed as a far-reaching non-linear extension to ordinary linear regression. They consist of several \textit{layers}, through which the input is fed via the composition of non-linear activation functions and weighted sums in order to generate the output. The smallest unit (one vector component) of such a layer is called a neuron. A central result in the theory of neural networks states that, using a non-constant, bounded and continuous activation function, a neural network with just one hidden layer can in principle approximate any continuous function arbitrarily well when there are sufficiently many neurons and appropriate weights are chosen (\cite{hornik1991}). In practice, a higher number of layers has been found to improve performance for many applications (\textit{deep learning}). Besides the number of hidden layers and the number of neurons per layer, there are other so-called \textit{hyperparameters} on which forecasting performance can critically depend. For instance, the optimisation algorithm that is used to train the network has to be chosen. Typically, some variant of stochastic gradient descent (SGD) like rmsprop (\cite{tieleman2012}) or Adam (\cite{kingma2015}) is used. Furthermore, SGD-type algorithms work with batches of training data. The \textit{batch size} can be varied in order to improve performance. Other hyperparameters which we consider include the number of epochs, i.e., the number of times the training data are fed into the optimisation algorithm, the activation function (tangens hyperbolicus, rectified linear unit, identity) and whether or not to employ dropout to avoid overfitting (\cite{srivastava2014}) and batch normalization to avoid internal covariate shift (\cite{ioffe2015}). \paragraph{Hyperparameter optimisation via cross-validation} We choose the hyperparameter values for the neural networks and random forests using five-fold cross-validation. First, we define a grid of hyperparameter combinations to be evaluated. Then, for every combination of hyperparameters in the grid, we split our training dataset into five parts or \textit{folds} of equal size, train a model with these values on four of the folds and evaluate its performance on the remaining one. After repeating this five times, each time with a different validation fold, we average performances. Finally, once the whole grid has been evaluated, we choose the hyperparameter combination that performs best on average. Summarising, the features we use to forecast the spot price of a time point $t$ with reference time point $r(t)$ are \begin{itemize} \item the total demand $D_{r(t)}(-500)$ and the price curve features of the same hour on the reference day, i.e., $V_{r(t)}^X(\mathbb{C}_k^X)$, $k=1, \dots, M^X$, \item the solar and wind infeed forecasts as well as the total demand forecast for the time points $t$ and $r(t)$, \item the calendar features year, daylight saving time, type of day, month and hour for the time points $t$ and $r(t)$. \end{itemize} We considered about 100 different parameter combinations for the random forests with the number of trees equal to $10$, $100$, $1000$, $5000$, $10000$ or $50000$. For the neural networks, we tested over 1000 parameter combinations with about 20 different network sizes ranging from one hidden layer with 5 neurons to $100$ hidden layers with 25 neurons each. \section{Results} \label{sec:results} To evaluate model performance, we primarily use the root-mean-square error \begin{equation*} \text{RMSE} :=\left(\frac{1}{n} \sum\limits_{i=1}^n \left(\hat{y}_i-y_i\right)^2 \right)^{1/2}, \end{equation*} where $\hat{y}_i$ are the predictions, $y_i$ are the true target values and $n$ is the number of observations for which a prediction is made. Furthermore, we consider the mean absolute error \begin{equation*} \text{MAE} := \frac{1}{n} \sum\limits_{i=1}^n \left| \hat{y}_i - y_i \right| \end{equation*} as a more interpretable measure of how far off the prediction is on average. The RMSE is the error measure which the machine learning algorithms aim to minimize during training. Accordingly, we select the model architecture that performs best in the 5-fold cross-validation with respect to the RMSE. In the electricity forecasting literature, sometimes the mean absolute percentage error (MAPE) is used. This is unsuitable for the German market, as often the MCP is at or close to zero. Therefore, we report the median absolute percentage error \begin{equation*} \text{MdAPE} := \med \left\{ \frac{| \hat{y}_i - y_i |}{| y_i |}, i=1, \ldots, n \right\} \end{equation*} for comparison. Aside from the methods which were described in Section \ref{sec:algorithms}, we consider two benchmarks. The first one is called the naive benchmark (\cite{nogales2002}). Its forecast for hour $h$ of date $d$ is the price at hour $h$ of the previous day if $d$ is a workday other than Monday and the price at hour $h$ of the same type of day in the previous week otherwise. The second benchmark is based on a different market, the Energy Exchange Austria (EXAA), where the electricity price is fixed two hours before the EPEX auction takes place. Therefore, the EXAA price at a time point $t$ can directly be used as a predictor for the EPEX price at the same time point. In fact, \cite{ziel2015} show this benchmark to be highly competitive. However, note that it is not really appropriate to compare the remaining forecasting methods to the EXAA benchmark because they are based on different information (see also \cite{ziel2016}). Nonetheless, the EXAA benchmark can provide some orientation on how well other models perform and how much improvement could be expected. The best-performing random forest consists of 1000 decision trees where at each step in the training of the underlying decision trees a randomly chosen subset of size 23 (corresponding to $25\%$) of all available features is used and where a tree node is only split further if it contains at least $1\%$ of all training data. We also use the random forest to support feature selection for the following neural network approach. For the neural networks under consideration we use different feature vector realizations: \begin{itemize} \item all available features, \item all but the price curve features of the reference date, \item the 10 most influential features according to the best-performing random forest, \item the 20 most influential features according to the best-performing random forest. \end{itemize} For each case we use different network architectures, which we determine by hyperparameter optimisation as described above. These are reported in Table~\ref{tab:hyperparameters} where each column corresponds to a different set of features and each row corresponds to a hyperparameter. The notation $[5, 5, 5]$ for the network architecture means that a 3-layer network consisting of 5 nodes per layer is used. For the networks that are trained on the selected features, we find a deeper architecture to perform best: $[25]$ * $25$ denotes a $25$-layer network with $25$ nodes per layer. Analogously, in the dropout row, $[0, 0.25, 0]$ means that dropout is employed with a probability of $25\%$ after the second layer and $[0.1]$ * $25$ means that dropout is employed after each of the $25$ layers with a probability of $10\%$. It is noteworthy that the best-performing network when using all features is rather small. Thus, as an additional plausibility check, we also consider the network architectures proposed by \cite{keles2016} (network size $[48, 48]$, sigmoid activation function, no dropout) and \cite{lago2018} (network size $[239, 162]$, relu activation function, no dropout) as a reference. Note that their models do not consider price curve features, i.e., order book data. \begin{table}[ht] \caption{The hyperparameters which were used when training feed-forward neural networks with different features (all, without curve features, only with the 10 or 20 most influential features as chosen by the best-performing random forest).} \centering \begin{tabular}{|l|c|c|c|c|} \hline Hyperparameter & \multicolumn{1}{l|}{All features} & \multicolumn{1}{l|}{\begin{tabular}[c]{@{}l@{}}Without curve \\ features\end{tabular}} & \multicolumn{1}{l|}{\begin{tabular}[c]{@{}l@{}}Selected features \\ ($N_F = 10$)\end{tabular}} & \multicolumn{1}{l|}{\begin{tabular}[c]{@{}l@{}}Selected features \\ ($N_F = 20$)\end{tabular}} \\ \hline \begin{tabular}[c]{@{}l@{}}Network \\ architecture\end{tabular} & [5, 5, 5] & [5, 5] & [25] * 25 & [25] * 25 \\ \hline optimiser & rmsprop & Adam & Adam & Adam \\ \hline \begin{tabular}[c]{@{}l@{}}Number of \\ epochs\end{tabular} & 100 & 100 & 100 & 100 \\ \hline Batch size & 128 & 64 & 128 & 128 \\ \hline \begin{tabular}[c]{@{}l@{}}Activation \\ function\end{tabular} & tanh & relu & relu & relu \\ \hline Dropout & [0, 0.25, 0] & [0, 0.25, 0] & [0.1] * 25 & [0.1] * 25 \\ \hline \begin{tabular}[c]{@{}l@{}}Batch \\ normalization\end{tabular} & no & yes & yes & yes \\ \hline \end{tabular} \label{tab:hyperparameters} \end{table} The results of the chosen model configurations are shown in Table~\ref{tab:results}. The errors we report are measured both on the training set (in-sample error) to evaluate how well the model describes the given data and on the test set (out-of-sample error) to assess model performance on previously unseen data (20\% of our whole dataset). \begin{table}[ht] \caption{Comparison of in-sample and out-of-sample errors in EUR per MWh or $\%$ for various price forecasting techniques.} \centering \begin{tabular}{|l|l|l|l|l|l|l|} \hline \multirow{2}{*}{Forecasting technique} & \multicolumn{3}{l|}{in-sample error} & \multicolumn{3}{l|}{out-of-sample error} \\ \cline{2-7} & RMSE & MAE & MdAPE & RMSE & MAE & MdAPE \\ \hline Naive model & 13.55 & 7.87 & 15.31\% & 12.68 & 7.71 & \bf{11.61\%} \\ \hline Ordinary linear regression & 6.85 & 4.25 & 10.93\% & 9.60 & 7.52 & 16.95\% \\ \hline Random forest & 6.77 & 4.17 & 9.73\% & 11.92 & 9.32 & 19.9\% \\ \hline \begin{tabular}[c]{@{}l@{}}Feed-forward neural network\\ with architecture from \\ \cite{keles2016}\end{tabular} & 6.72 & 4.51 & 11.49\% & 14.87 & 12.81 & 30.63\% \\ \hline \begin{tabular}[c]{@{}l@{}}Feed-forward neural network\\ with architecture from \\ \cite{lago2018}\end{tabular} & 2.27 & 1.65 & 4.45\% & 21.05 & 8.94 & 15.22\% \\ \hline Feed-forward neural network & 5.45 & 3.57 & 8.89\% & 9.59 & \bf{7.08} & 14.18\% \\ \hline \begin{tabular}[c]{@{}l@{}}Feed-forward neural network\\ without curve features\end{tabular} & 6.63 & 4.41 & 11.22\% & 10.11 & 7.85 & 16.12\% \\ \hline \begin{tabular}[c]{@{}l@{}}Feed-forward neural network \\ with feature selection ($N_F = 10$) \end{tabular} & 7.69 & 5.06 & 11.68\% & \bf{9.41} & 7.34 & 15.57\% \\ \hline \begin{tabular}[c]{@{}l@{}}Feed-forward neural network \\ with feature selection ($N_F = 20$) \end{tabular} & 7.71 & 4.95 & 11.27\% & 13.65 & 10.18 & 21.48\% \\ \hline \hline EXAA & 6.47 & 3.53 & 7.56\% & 5.58 & 3.92 & 7.22\% \\ \hline \end{tabular} \label{tab:results} \end{table} \paragraph{Alternative: More sophisticated neural network architectures} Apart from feed-forward neural networks we also analysed recurrent neural networks. As electricity spot prices can be expected to exhibit a strong dependence on previous days' features and prices, it seems reasonable to model them as a multivariate time series. While classical approaches like ARIMA or GARCH models are possible, this also is a typical application for recurrent neural networks because they explicitly incorporate the sequential structure of the inputs. In this case, the goal was to predict the $24$-dimensional vector of spot prices at some date $d$ based on information available up to date $d-1$. For each date $e\leq d-1$ this information consists of the curve features for date $e$ as well as the calendar features and expected renewable infeed and total demand for date $e+1$. We implemented this approach using the \textit{long short-term memory} (LSTM) architecture that allows for efficient training of recurrent neural networks (\cite{hochreiter1997}), but the results were not as convincing as with the other methods. This might be due to the high dimensionality of the multivariate time series under consideration. Therefore, we focused on the random forest and feed-forward neural network approaches where the temporal dependence structure is more explicitly incorporated as a feature by means of the reference day. \section{Conclusion}\label{sec:conclusions} Our results show that neural networks can indeed provide order-book-based price forecasts with competitive results. However, they do not perform significantly better than simpler methods like ordinary linear regression. Whereas the \textit{classical} order-book-based forecasting technique requires a lot of statistical analysis, the network architecture optimisation also demands significant resources. We also found that reducing the number of features generally improves results. In regard to the RMSE, we find that the feed-forward neural network with only 10 features as selected by the random forest performs best. Considering the MAE (a measure directly linked to revenues from financial trading), the feed-forward neural network without feature selection is in the lead. However, the naive model shows good results as well, supporting this traditional and often applied heuristic in energy economics. The neural network architectures from literature show competitive in-sample results, but their performance drops significantly in an out-of-sample analysis. This indicates overfitting. The posed research questions have been answered. We have shown how to incorporate order book features using volume-based partitioning, a transformation to price curves and feature selection based on random forests. We have also shown that machine learning cannot significantly reduce the work effort needed in the model set-up, but gives competitive results. The models do have a lot of potential for improvement. For instance, there are much more accurate wind and solar infeed forecasts available in the market compared to the data from EEX transparency (unfortunately they are not free of charge). We see the largest potential in a daily recalibration of the models including an updated feature selection which allows the model to react to fundamental changes in the market (coal and gas prices, power plant outages, ...). In addition, we also analysed different applications of machine learning on EPEX order books, which are not outlined in detail: We employed neural networks to reconstruct renewable infeed from the order book and used the networks to generate price forward curves. \FloatBarrier \bibliographystyle{apacite}
{'timestamp': '2019-06-28T02:10:40', 'yymm': '1906', 'arxiv_id': '1906.06248', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06248'}
arxiv
\section{Introduction}\label{sec:intro} Ontology design patterns (ODPs) \cite{DBLP:books/ios/HGJKP2016} have been introduced as a means to establish best practices for ontology design as well as a way to provide a set of carefully-designed building blocks for ontologies that can be reused in different contexts. In \cite{DBLP:conf/semweb/Krieg-BrucknerM17}, we have introduced \emph{generic} ontology design patterns (GODPs), using the language Generic \ensuremath{\mathsf{DOL}}\xspace. While simple ODPs usually are just ontologies, GDOPs have \emph{parameters} that can be \emph{instantiated} in different ways, thus leading to an even greater and easier re-use of ODPs. This paper is an update of \cite{DBLP:conf/semweb/Krieg-BrucknerM17}, addressing many of the extensions of Generic \ensuremath{\mathsf{DOL}}\xspace listed there as future work, on which we focus in this paper. To better illustrate the degree of generality provided by the new language extensions, we deliberately decided to present some of the examples used in the cited paper again in their new form. Further examples of GODPs formulated in Generic \ensuremath{\mathsf{DOL}}\xspace{} can be found in \cite{GDOL-BOG19}, in particular a role pattern from the literature, reformulated in a modular and reusable way. \cite{GDOL-BOG19} also gives more motivation and describes the advantages of Generic ODPs over ``classical'' ODPs, i.e. of parameterization over subsumption (parametric polymorphism over subtype polymorphism, resp.). \section{Generic \ensuremath{\mathsf{DOL}}\xspace}\label{sec:gdol} \lstset basicstyle=\small, basicstyle=\ttfamily, stringstyle=\sffamily, showstringspaces=false, numbers=left, numberstyle=\tiny, stepnumber=2, numbersep=5pt, language=dolText,alsolanguage=owl2Manchester} The \emph{Distributed Ontology, Modeling and Specification Language}, \ensuremath{\mathsf{DOL}}\xspace \cite{mossakowski2015distributed}, is a meta-language that enables modular development of ontologies\footnote{We ignore the modeling and specification aspects here and restrict to ontologies only.} and allows specification of intended relationships (e.g. theory interpretation, alignment, properties of extensions) between them. \ensuremath{\mathsf{DOL}}\xspace is supported by the \emph{Heterogeneous Tool Set}, \ensuremath{\mathsf{Hets}}\xspace \cite{conf/tacas/MossakowskiML07}, that provides a parser for \ensuremath{\mathsf{DOL}}\xspace specifications, an implementation of \ensuremath{\mathsf{DOL}}\xspace semantics, and an interface to theorem provers. The language \emph{Generic \ensuremath{\mathsf{DOL}}\xspace} (or \ensuremath{\mathsf{GDOL}}\xspace) was proposed in \cite{DBLP:conf/semweb/Krieg-BrucknerM17} as an extension of \ensuremath{\mathsf{DOL}}\xspace with parameterized ontologies (that we may also call generic ontologies), following generic specifications in CASL \cite{CASL-RM}. Parameters of generic ontologies are ontologies themselves: thus we may require that some abstract properties are expected to hold for the argument ontology provided in an instantiation. This provides important semantic expressivity, going beyond macro approaches such as OTTR \cite{DBLP:conf/semweb/SkjaevelandKL18}, where parameters are just symbols of a certain kind, or lists of these. Moreover, a generic ontology may import ontologies, written after the list of parameters with the keyword \texttt{given}. The semantics is that the symbols of these ontologies are visible in the parameters and the body, but will not be instantiated. \begin{figure}[t] \begin{multicols}{2} \lstinputlisting[firstline=2]{ReflexiveRelation.dol} \lstinputlisting[firstline=2]{InverseRelation.dol} \columnbreak \lstinputlisting[firstline=2]{TransitiveRelation.dol} \lstinputlisting[firstline=2]{SubProp.dol} \end{multicols} \caption{\ontology{ReflexiveRelation}, \ontology{TransitiveRelation}, \ontology{InverseRelation} and \ontology{SubProp}.} \label{fig:simple-patterns} \end{figure} Several simple examples of generic ontologies are presented in Fig.~\ref{fig:simple-patterns}, where we introduce patterns for very basic building blocks for ontologies: \ontology{ReflexiveRelation} adds, for a given object property \texttt{r} and a given class \texttt{C}, axioms stating that \texttt{r} is reflexive, and its domain and range are \texttt{C}; \ontology{TransitiveRelation} adds domain, range and transitivity axioms, given one object property and one class; \ontology{InverseRelation} takes two object properties and two classes, and adds domain and range axioms for them, and an axiom that one object property is the inverse of the other. The ontology \ontology{SubProp} already makes use of a new language construct of Generic \ensuremath{\mathsf{DOL}}\xspace (cf. the next section): it has, as fourth parameter, an ontology that contains two additional axioms. Just like for OWL (and \ensuremath{\mathsf{DOL}}\xspace), the \emph{``Same Name -- Same Thing'' principle} is used, which means that the definition of an entity can be repeated without introducing multiple occurrences of that entity. For Generic \ensuremath{\mathsf{DOL}}\xspace, this means that if the body of a generic ontology declares an entity, the union of multiple instantiations of that generic ontology will contain only one occurrence of that entity. If this was not the intention, the entity should rather become a parameter of the generic ontology, such that each instantiation can assign it a different name. \section{Extensions of Generic \ensuremath{\mathsf{DOL}}\xspace} \label{sec:gdol-ext} \subsection{Sequential Parameters, Local Environments, and Compact Notation for Arguments} It is in the interest of simplicity (of writing and reading) to keep the parameters of generic ontologies as small as needed. The aim is to avoid having to explicitly provide symbol mappings when making instantiations of generic ontologies: if a parameter and its corresponding argument consist each of only one symbol, \ensuremath{\mathsf{Hets}}\xspace will automatically derive the unique way of mapping the one to the other. When such derivations cannot be done automatically, the user must specify how symbols are mapped using a sequence of mapping items, written \texttt{f |-> a} where \texttt{f} and \texttt{a} are symbols of the parameter and argument, respectively. The sequence of mapping items gives rise to a morphism between the parameter and the argument, called \emph{fitting morphism}. To make the notation more compact, the parameters of a generic ontology and the arguments in an instantiation may be written in Generic \ensuremath{\mathsf{DOL}}\xspace{} as a semi-colon separated list, e.g. \texttt{TransitiveRelation[olderThan;Person]} instead of \texttt{TransitiveRe\-lation[olderThan][Person]}.% \footnote{For OWL we can use semicolons as separators between parameters and arguments because they are not used as separators between declarations at the basic level. When this is the case, e.g. for the CASL logic, where one can write \texttt{sort s; op c : s}, we will use curly braces to mark the beginning and the ending of an ontology. Thus, \texttt{G[sort s; sort t]} will be parsed as \texttt{G[\{sort s; sort t\}]} -- an ontology declaring two sorts, while a generic ontology with two sorts as parameters or arguments will be written \texttt{H[\{sort s\};\{sort t\}]}. } The first significant extension of Generic \ensuremath{\mathsf{DOL}}\xspace{} that we introduce is a modification of the semantics of generic ontologies. In the semantics of generics in \cite{DBLP:conf/semweb/Krieg-BrucknerM17,CASL-RM}, each parameter forms its own environment, and sharing between parameters is allowed only if the image of each shared symbol through the fitting morphisms of the parameters where it occurs is the same. \ensuremath{\mathsf{Hets}}\xspace checks this and issues an error message when this condition does not hold for an instantiation. In the context of keeping the parameters small, we decided to allow each parameter to share the environment of all parameters preceding it along a chain of inclusions. We call this \emph{sequential semantics} for parameters of generic ontologies. As an example, the generic ontology \ontology{SubProp} in Fig.~\ref{fig:simple-patterns} takes as parameters an object property \texttt{q}, two classes \texttt{D} and \texttt{R}, and finally an ontology extending the previous parameters with the declaration of an object property \texttt{p} with domain \texttt{D} and range \texttt{R}; its body adds axioms that domain and range of \texttt{q} are also \texttt{D} and \texttt{R}, respectively, and moreover \texttt{q} is a sub-property of \texttt{p}. Note that with the sequential semantics it has become possible to refer to \texttt{D} and \texttt{R} in the axioms for \texttt{p}; the effect of including the domain and range axioms for the parameter \texttt{p} now allows (indeed requires) the checking of these as constraints on its argument in each instantiation, as we shall see below. The semantics of instantiation in \cite{DBLP:conf/semweb/Krieg-BrucknerM17,CASL-RM} imposes a compatibility condition between the fitting morphisms for the different parameters: if a symbol occurs in multiple formal parameters, it must be mapped by the different fitting morphisms in a unique way. This compatibility condition remains in our extension, and the user can rely on it to provide symbol mappings only for the new symbols of a parameter; by compatibility, the way the old symbols are mapped is already defined. To illustrate this, let us assume we want to define the \texttt{isAncestorOf} property between \texttt{Person}s as a transitive relation and with subproperty \texttt{isParentOf} (cf. Fig.~\ref{fig:ancestor}). We first instantiate the pattern \ontology{TransitiveRelation} to obtain that \texttt{isAncestorOf} is transitive and has domain and range \texttt{Person}. We would like to write \texttt{[isAncestorOf]} as a shorthand notation for the argument \texttt{TransitiveRelation[isAncestorOf;Person;Person]}, or, to be fully correct, as this ontology has more than one object property, as a shorthand notation for the even longer form where this is followed by \texttt{fit p |-> isAncestorOf}. \begin{figure}[h] \lstinputlisting[morekeywords={let,in,given,EquivalentWith}]{PersonRels.dol} \caption{Using the patterns for a concrete design.} \label{fig:ancestor} \end{figure} This requires another language extension regarding instantiation of parameters of generic ontologies. Firstly, in the case of some \ensuremath{\mathsf{DOL}}\xspace{} ontology \texttt{O1} followed by an instantiation, written \texttt{O1 then G[AP1]}, the \emph{local environment} \texttt{O1} of previous declarations that is being extended is implicitly added to the argument, i.e. this expands to \texttt{O1 then G[O1 then AP1]}. In the case of ontologies with imports, the local environment of an instantiation will include them. Secondly, we introduce a shorthand notation for the instantiation of those parameters that define only one new symbol (recall that we assume sequential semantics of parameters, thus the symbols of all previous parameters are visible at each step). Consider that the name of this unique new symbol of a parameter is \texttt{N} and its kind (class, object property, etc.) is $k$. For an instantiation of that parameter, in \cite{DBLP:conf/semweb/Krieg-BrucknerM17,CASL-RM} an ontology is required as an argument, which can be given in two forms: \begin{itemize} \item as a named ontology \texttt{O}. Then we must be able to derive uniquely how \texttt{N} is mapped to a symbol of kind $k$ in \texttt{O}, otherwise we must explicitly provide a symbol mapping of the form \texttt{N |-> N'} where \texttt{N'} is a symbol of kind $k$ in \texttt{O}. \item as an anonymous ontology consisting of a sequence of symbol declarations and axioms. A special case is that of a single symbol defined with an explicit kind; then this kind must also be $k$. In such a case, this unique symbol is considered newly declared and acts as an argument, and the symbol mapping is uniquely determined. \end{itemize} We here propose a third option: \begin{itemize} \item the name \texttt{M} of a symbol of kind $k$ from the local environment is passed as an argument. The argument expands to \texttt{E fit N |-> M}. Thus any properties that \texttt{N} must have, as specified in the parameter, are checked for the symbol \texttt{M} in the local environment. \end{itemize} In general, an instantiation \texttt{SubProp[sr;A;B;r]} of \ontology{SubProp} where \texttt{A}, \texttt{B} are classes and \texttt{sr}, \texttt{r} are relations from the local environment, can be done only, if \texttt{r} has domain \texttt{A} and range \texttt{B}. The result is that \texttt{sr} becomes a sub-property of \texttt{r} and moreover it gets domain \texttt{A} and range \texttt{B} (if this was not already available in the local environment). An instantiation \texttt{SubProp[sr;A;B;r]} where \texttt{sr} is not visible in the local environment also requires that \texttt{r} has domain \texttt{A} and range \texttt{B}. The result is that a new relation \texttt{sr} is defined and added to the local environment (again, with domain \texttt{A} and range \texttt{B}, and as a sub-property of \texttt{r}). In our example, we can then write \texttt{isAncestorOf} as an argument for the fourth parameter of \texttt{SubProp}; with the third case listed above, this means that we refer to the symbol declared in the instantiation of \texttt{TransitiveRelation}, and therefore the expected domain and range axioms hold for \texttt{isAncestorOf}. We make use of the simple patterns defined in Fig.~\ref{fig:simple-patterns} to extend a simple order (the transitive \texttt{greater[Val]} relation on a class \texttt{Val}): in Fig.~\ref{fig:order-rel-ext} we define its inverse \texttt{less[Val]}, a \texttt{greaterOrEqual[Val]} and a \texttt{lessOrEqual[Val]} relation that are inverse to each other such that \texttt{less[Val]} is a sub-property of \texttt{lessOrEqual[Val]} and \texttt{greater[Val]} is a sub-property of \texttt{greaterOrEqual[Val]}. \paragraph{Parameterized Names} Here the symbols declared in the two patterns have \emph{parameterized names}, to make explicit that they depend on the names of the parameters. The notation for parameterized names is \texttt{Name[Param1, ..., ParamN]}, if the name of the new symbol depends on \texttt{N} parameters. During instantiation, the names of the arguments are substituted in the parameterized name, e.g. \texttt{greater[Val]} becomes \texttt{greater[Significance]} if the value provided for \texttt{Val} is \texttt{Significance}. \ensuremath{\mathsf{Hets}}\xspace also offers the possibility of \emph{stratifying} these names for the result of an instantiation: the name \texttt{greater[Significance]} is replaced with \texttt{greater\_Significance}, thus obtaining a legal OWL identifier. \begin{figure}[h] \lstinputlisting[firstline=2]{SimpleOrder.dol} \lstinputlisting[firstline=2]{OrderRelationExtension.dol} \caption{\ontology{SimpleOrder} and \ontology{OrderRelationExtension}.} \label{fig:order-rel-ext} \end{figure} As an argument of \ontology{OrderRelationExtension} we could provide any transitive relation, in particular, a strict order. Since OWL does not support transitive and asymmetric relations, the argument would have to be given in a logic where this can be expressed, e.g. OWL with restrictions \cite{DBLP:conf/owled/SchneiderRS13} or first-order logic. The theory presented informally in this paper is actually independent of the underlying formalism used for writing ontologies (OWL in the examples here) and moreover provides support for heterogeneous specifications as in the above example: the parameter can be instantiated with an argument in another logic along an encoding of the logic of the parameter to the logic of the argument. \subsection{Local Sub-Patterns, Optional Parameters, List Parameters, and Recursion} A pattern can be structured into smaller sub-patterns; often we want to make these visible only in the pattern where they are introduced. For this, we allow \emph{local definition of sub-patterns} before the body of a generic ontology, using a \texttt{let} notation. The local sub-patterns share the parameters of the main pattern where they are defined. Note that this considerably abbreviates the notation; in effect, it corresponds to a partial instantiation of a corresponding pattern declared outside of the body (cf. \cite{DBLP:conf/semweb/Krieg-BrucknerM17}). The body of the main pattern may, and in most cases will, make use of instantiations of the local sub-patterns. We may mark parameters as \emph{optional}, written \texttt{?[FP]} (as in OTTR \cite{DBLP:conf/semweb/SkjaevelandKL18}), where \texttt{FP} is a parameter, or \texttt{[ ...; ? FP; ...]} in the notation with semicolons. At instantiation, if an argument is not provided for an optional parameter (written \texttt{[]} or as a whitespace between semicolons \texttt{; ;}), all occurrences of that parameter in the body are replaced with the empty ontology, and all symbols and sentences containing symbols from that parameter are removed. We also introduce language constructs for \emph{list parameters}, in spirit similar to those in OTTR \cite{DBLP:conf/semweb/SkjaevelandKL18}. While OTTR patterns support only iteration and zip over list parameters, we allow recursive calls of patterns over lists in Generic \ensuremath{\mathsf{DOL}}\xspace, which would be considered illegal in OTTR because they introduce cyclic dependencies between patterns. A list is written \texttt{X :: Xs}, where \texttt{X} is an ontology and \texttt{Xs} denotes the tail of the list. If \texttt{X} is an ontology declaring only one symbol of a certain kind, it is assumed that all the ontologies \texttt{Xs} are of the same form. We may refer to such list as a list of symbols of that kind. For example, \texttt{Class: C :: Cs} is a list of ontologies each consisting only of a class declaration. An ontology with such a list as a parameter is written \texttt{ontology G [Class: C :: Cs] = ...}. The empty list is written \texttt{[empty]} and is treated as an empty optional argument. \paragraph{Notations.} In the argument of an instantiation of a generic ontology \texttt{G}, we may write \begin{itemize} \item \texttt{[]} for \texttt{[empty]}, \item \texttt{[X]} for \texttt{[X::empty]}, and \item \texttt{[X$_1$, $\ldots$, X$_n$]} for \texttt{[X$_1$ :: $\ldots$ :: X$_n$ :: empty]}. \end{itemize} \paragraph{Value Sets.} Qualitative values, corresponding to abstractions from quantitative data, occur quite often in practice, cf. grading below. As we know from cognitive science, they are related to the human need for doing away with irrelevant detail (precision in this case); here (and there) they allow us to simplify abstract reasoning (cf. \cite{DBLP:conf/popl/CousotC77}). With the new constructions introduced above, the pattern \texttt{ValSet} (Fig.~\ref{fig:val-set}) has as arguments: a class of values, a list of value individuals, and an optional relation between these values. The sub-pattern \texttt{OrderStep} introduces the fact that a value belongs to the set of values and is optionally greater than the value introduced in the set at the previous step. Once the list \texttt{vS} is empty, the recursion stops. All this is put together in the body of \ontology{ValSet}: the value is created for the first element of the list of value individuals, the relation \texttt{greater} is defined to be a simple order on \texttt{Val}, the iteration creates the rest of the values, and finally the values are declared to be different from each other and the set of values is defined to be the disjoint union of all values. \begin{figure}[t] \lstinputlisting[morekeywords={let,in,given,EquivalentWith},firstline=2]{ValSet.dol} \caption{\ontology{ValSet}.} \label{fig:val-set} \end{figure} The optional parameter for \ontology{ValSet} allows to create instances of this pattern both for the case when the values are ordered (\ontology{ValSet\_Significance} in Fig.~\ref{fig:val-set-insts}), and for the case when the values in the set are not ordered (\ontology{ValSet\_CrustStyle} in Fig.~\ref{fig:val-set-insts}). The expansion of \ontology{ValSet\_Significance} is precisely the ontology \ontology{GradedRelations4Exp} in Fig.~3 of \cite{DBLP:conf/semweb/Krieg-BrucknerM17}. We may also extend the order relation \texttt{greater[Val]} on the value set with its inverse \texttt{less[Val]}, its reflexive version \texttt{greaterOrEqual[Val]} and the inverse of its reflexive version \texttt{lessOrEqual[Val]}, as illustrated in Fig.~\ref{fig:val-set-with-order}. \begin{figure}[t] \begin{multicols}{2} \lstinputlisting[morekeywords={let,in,given,EquivalentWith}]{ValSet_CrustStyle.dol} \columnbreak \lstinputlisting[morekeywords={let,in,given,EquivalentWith}]{ValSet_Significance.dol} \end{multicols} \caption{Instantiations of \ontology{ValSet}.} \label{fig:val-set-insts} \end{figure} \begin{figure}[t] \lstinputlisting[morekeywords={let,in,given,EquivalentWith}]{ValSetWithOrder.dol} \caption{Extending the order on \ontology{ValSet}.} \label{fig:val-set-with-order} \end{figure} \paragraph{Graded Relations.} In \cite{DBLP:conf/semweb/Krieg-BrucknerM17} we introduced a pattern for graded relations with a grade domain with 4 values and stated that analogous patterns must be provided for each number of values. The main idea of the pattern \cite{DBLP:conf/ksem/Krieg-Bruckner16} is to introduce a qualitative metric, arbitrarily fine and usually represented as an ordered set, for an object property. Typical examples include the significance of an ingredient in a recipe, or how much a person is affected by an impairment. Instead of using reification for the ternary relation thus obtained, the solution proposed in \cite{DBLP:conf/ksem/Krieg-Bruckner16} is to encode the grading with a sheaf of relations, one for each grade. The intended meaning is that \begin{center} \texttt{hasTarget(?s,?t,Val)} $\equiv$ \texttt{hasTarget\_Val(?s,?t)} \end{center} \noindent for a ternary relation \texttt{hasTarget} with grade value \texttt{Val} as third argument. Using list parameters and recursive sub-patterns, we can now provide one pattern that covers all necessary numbers of values, as in Fig.~\ref{fig:graded-rels}. The last parameter of \ontology{GradedRels} is a list of ontologies, with the assumption that each of them declares an individual of type \texttt{Val}. The local sub-pattern \ontology{Step} has as parameter a list of ontologies such that each of them declares an individual. In the instantiation \texttt{Step[Val::ValS]}, the first element of the argument list is the ontology obtained by expanding the notation \texttt{Val}, i.e. the local environment, in this case the union of all formal parameters that we denote \texttt{Env}, contains a declaration for the individual \texttt{Val}. The argument expands then to \texttt{Env fit X |-> Val}. By assumption, each element of the list of ontologies \texttt{valS} declares an individual (and an axiom about its type, that is not needed here), so we can use it as an argument for \texttt{xs}, which is a list of ontologies each declaring an individual. \begin{figure}[t] \lstinputlisting[morekeywords={let,in,given,EquivalentWith}]{GradedRels.dol} \lstinputlisting[morekeywords={let,in,given,EquivalentWith}]{GradedRels_Significance.dol} \caption{\ontology{GradedRels} and instantiation \ontology{GradedRels\_Significance}.} \label{fig:graded-rels} \end{figure} \subsection{Template Matching for List Parameters} \begin{figure}[t] \lstinputlisting[morekeywords={let,in,given,EquivalentWith}]{GradedRelsSub.dol} \lstinputlisting[morekeywords={let,in,given,EquivalentWith}]{GradedRelsSub_Significance.dol} \caption{\ontology{GradedRelsSub} and instantiation of \ontology{GradedRelsSub\_Significance}.} \label{fig:graded-rels-sub} \label{fig:graded-rels-insts} \end{figure} We can make use of the list constructor \texttt{::} to give different definitions for the same pattern according to the argument of the list parameter of that pattern. This is a case distinction similar to pattern matching in functional programming, that we call \emph{template matching} here to avoid the overlap with ontology design patterns. In an instantiation, \ensuremath{\mathsf{Hets}}\xspace goes sequentially through the list of all definitions for a pattern and checks whether the argument matches the parameter template. When a match is found, the body given in that definition is used for instantiation. If no match is found, the instantiation is incorrect. As an example, we provide a generic pattern for extending a sheaf of graded relation with subsumption relations, see Fig.~\ref{fig:graded-rels-sub}. The idea is to introduce relations for expressing that a property holds with at least or at most a grade, when the grades can be compared, and to create a subsumption hierarchy between the relations \texttt{p\_G} and \texttt{p\_atLeast\_G}: if a property \texttt{p} holds with a grade at least \texttt{G}, if it holds with grade \texttt{G} or it holds at least with a grade less than \texttt{G}. In this example, the recursion is shown both for a less-or-equal order (\texttt{atLeast}) and a greater-or-equal order (\texttt{atMost}); in the former, an initial step \texttt{AtMostInitial} is needed, while in the latter two cases for the recursion of \texttt{AtLeastStep} have to be distinguished to define a special final step for recursion termination. When \ontology{GradedRelsSub\_Significance} (Fig.~\ref{fig:graded-rels-insts}) has been expanded and the names stratified, we obtain a relation subsumption hierarchy between the graded relations obtained as follows (only the \texttt{atLeast} relations are shown): \begin{verbatim} hasIngredient_atLeast_0Insignificant hasIngredient_0Insignificant hasIngredient_atLeast_1Subordinate hasIngredient_1Subordinate hasIngredient_atLeast_2Essential hasIngredient_2Essential hasIngredient_3Dominant \end{verbatim} \section{Conclusions and Future Work}\label{sec:conclusions} \cite{DBLP:conf/semweb/HitzlerGJKP17} introduces a list of desired capabilities for a language for ODPs. We list the desiderata, and how they are met by Generic \ensuremath{\mathsf{DOL}}\xspace{}, as follows: \begin{enumerate} \item \emph{Compatibility with the OWL standard and OWL supporting tools:} Ontologies generated with Generic \ensuremath{\mathsf{DOL}}\xspace{} are fully compatible with the OWL standard (after stratification). A Prot\'eg\'e plugin for Generic \ensuremath{\mathsf{DOL}}\xspace{} is planned. \item \emph{Support for identification of ODPs as distinct from ontologies, and identification of relevant parts of ODPs:} Patterns are generic (i.e. parameterized) ontologies; the syntax allows a clear distinction between the parameters, the imports and the body of a pattern. \item \emph{Support for representing relevant relationships between patterns (refinement, generalization etc.):} The \emph{views} in \ensuremath{\mathsf{DOL}}\xspace can be used to define refinements between generic ontologies. \item \emph{Support for identification of modules in ontologies generated using an ODP-based approach:} The module mechanisms in \ensuremath{\mathsf{DOL}}\xspace allows the user to write ODPs in a way revealing their modular structure directly. \item \emph{Support for representing relationships between ontology modules and the ODPs that have been used as templates for these modules:} In Generic \ensuremath{\mathsf{DOL}}\xspace{}, this is the relation between a generic ontology and one of its instantiations. Hets displays this relation as a link in the development graph, which is a theory interpretation, semantically. \item \emph{Extensibility of the language by means of community-provided patterns for representing information about patterns and modules:} Extensibility of the language is not supported (a higher-order extension of the language is under consideration). A structured repository and a meta-ontology relating the GODPs in this repository are presently under development. \end{enumerate} An important aspect is how to make the use of GODPs more intuitive for ontology developers. A good GODP would have to provide \begin{itemize} \item a good choice of names for the pattern and for the parameters, \item a documentation part informing the user about the functionality of the pattern, \item an instantiation example. \end{itemize} Ideally, working with GODPs will be done via a GUI that hides the body of the pattern from the ontology developer (providing an appropriate documentation) and makes only those parameters visible, which have to be instantiated. \ensuremath{\mathsf{Hets}}\xspace{} support for the Generic \ensuremath{\mathsf{DOL}}\xspace{} language extensions introduced in this paper is currently in progress. \bibliographystyle{unsrt}
{'timestamp': '2019-06-17T02:16:44', 'yymm': '1906', 'arxiv_id': '1906.06275', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06275'}
arxiv
\subsection{Background} \label{sec:motivation} We first give notations used throughout the paper, and backgrounds on verification and robust optimization. \paragraph{Notation.} We define an $L$-layer neural network recursively as: \begin{align*} f(\bm{x})=z^{(L)} \qquad z^{(l)}&=\W{(l)} h^{(l-1)}+\mathbf{b}^{(l)} \qquad \W{(l)} \in \mathbb{R}^{n_l \times n_{l-1}} \qquad \mathbf{b}^{(l)} \in \mathbb{R}^{n_l} \\ h^{(l)}&=\sigma^{(l)}(z^{(l)}), \quad \forall l \in\{1, \dots, L-1\}, \end{align*} where $h^{(0)}(\bm{x})=\bm{x}$, $n_0$ represents input dimension and $n_L$ is the number of classes, $\sigma$ is an element-wise activation function. We use $z$ to represent pre-activation neuron values and $h$ to represent post-activation neuron values. Consider an input example $\bm{x}_k$ with ground-truth label $y_k$, we consider a set of $S(\bm{x}_k, \epsilon) = \{\bm{x} | \| \bm{x} - \bm{x}_k \|_\infty \leq \epsilon\}$ and we desire a robust network to have the property $y_k = \argmax_{j}[f(\bm{x})]_j$ for all $\bm{x} \in S$. We define element-wise upper and lower bounds for $z^{(l)}$ and $h^{(l)}$ as $\underline{z}^{(l)} \leq z^{(l)} \leq \overline{z}^{(l)}$ and $\underline{h}^{(l)} \leq h^{(l)} \leq \overline{h}^{(l)}$. \paragraph{Verification Specifications.} Neural network verification literature typically defines a specification vector $\bm{c} \in \mathbb{R}^{n_L}$, that gives a linear combination for neural network output: $\bm{c}^\top f(\bm{x})$. In robustness verification, typically we set $\bm{c}_i=1$ where $i$ is the ground truth class label, $\bm{c}_j=-1$ where $j$ is the attack target label and other elements in $c$ are 0. This will represent the margin between class $i$ and class $j$. For an $n_L$ class classifier and a given label $y$, we define a specification matrix $C \in \mathbb{R}^{n_L \times n_L}$ as: \vspace{-6pt}\begin{equation} C_{i,j} = \begin{cases} 1, \quad &\text{if $j=y$, $i \neq y$ (output of ground truth class)} \\ -1, \quad &\text{if $i=j$, $i \neq y$ (output of other classes, negated)} \\ 0, \quad &\text{otherwise (note that the $y$-th row contains all 0)} \end{cases} \end{equation} Importantly, each element in vector $\bm{m} \coloneqq C f(\bm{x}) \in \mathbb{R}^{n_L}$ gives us margins between class $y$ and all other classes. We define the lower bound of $C f(\bm{x})$ for all $\bm{x} \in S(\bm{x}_k, \epsilon)$ as $\underline{\bm{m}}(\bm{x}_k, \epsilon)$, which is a very important quantity. \citet{wong2018provable} showed that for cross-entropy loss we have: \begin{equation} \label{eq:robust_ub} \max_{\bm{x} \in S(\bm{x}_k, \epsilon)} L(f(\bm{x}); y; \theta) \leq L(f(-\underline{\bm{m}}(\bm{x}_k, \epsilon)); y; \theta). \end{equation} \eqref{eq:robust_ub} gives us the opportunity to solve the robust optimization problem~\eqref{eq:adv_training} via minimizing the tractable upper bound of inner-max. Minimizing the upper bound guarantees that $\max_{\bm{x} \in S(\bm{x}_k, \epsilon)} L(f(\bm{x}), y)$ is also minimized. \begin{figure}[t] \centering \includegraphics[width=0.9\textwidth]{augmented.pdf} \caption{ Interval Bound Propagation viewed as training an \emph{augmented neural network} (IBP-NN). The inputs of IBP-NN are two images $\bm{x}_k+\epsilon$ and $\bm{x}_k-\epsilon$. The output of IBP-NN is a vector of lower bounds of margins (denoted as $\underline{\bm{m}}$) between ground-truth class and all classes (including the ground-truth class itself) for all $\bm{x}_k - \epsilon \leq \bm{x} \leq \bm{x}_k + \epsilon$. This vector $\underline{\bm{m}}$ is negated and sent into a regular softmax function to get model prediction. The top-1 prediction of softmax is correct if and only if all margins between the ground-truth class and other classes (except the ground truth class) are positive, i.e., the model is verifiably robust. Thus, an IBP-NN with low standard error guarantees low verified error on the original network.} \label{fig:augmented} \end{figure} \subsection{Analysis of IBP and Linear Relaxation based Verifiable Training Methods} \paragraph{Interval Bound Propagation (IBP)} Interval Bound Propagation (IBP) uses a very simple bound propagation rule. For input layer we have $\bm{x}_L \leq \bm{x} \leq \bm{x}_U$ (element-wise). For an affine layer we have \begin{align} \label{eq:ibp_upper} \overline{z}^{(l)} &= \W{(l)}\frac{\overline{h}^{(l-1)} + \underline{h}^{(l-1)}}{2} + |\W{(l)}|\frac{\overline{h}^{(l-1)} - \underline{h}^{(l-1)}}{2} \\ \label{eq:ibp_lower} \underline{z}^{(l)} &= \W{(l)}\frac{\overline{h}^{(l-1)} + \underline{h}^{(l-1)}}{2} - |\W{(l)}|\frac{\overline{h}^{(l-1)} - \underline{h}^{(l-1)}}{2} \end{align} where $|\W{(l)}|$ takes element-wise absolute value. Note that $\overline{h}^{(0)} = \bm{x}_U$ and $\underline{h}^{(0)} = \bm{x}_L$. And for element-wise monotonic increasing activation functions $\sigma$, \vspace{-5pt}\begin{align} \label{eq:ibp_act} \overline{h}^{(l)} = \sigma(\overline{z}^{(l)}) \qquad \underline{h}^{(l)} = \sigma(\underline{z}^{(l)}). \vspace{-5pt} \end{align} Given a fixed NN, IBP gives a very loose estimation of the output range of $f(\bm{x})$. However, during training, since the weights of NN can be updated, we can equivalently view IBP as an augmented neural network, referred to as IBP-NN (Figure~\ref{fig:augmented}). Unlike an usual network which takes an input $\bm{x}_k$ with label $y_k$, IBP-NN takes two points $\bm{x}_L=\bm{x}_k - \epsilon$ and $\bm{x}_U = \bm{x}_k + \epsilon$ as input (where $\bm{x}_L \leq \bm{x} \leq \bm{x}_U$, element-wise). The bound propagation process can be equivalently seen as forward propagation in a specially structured neural network, as shown in Figure~\ref{fig:augmented}. After the last specification layer $C$ (typically merged into $\W{(L)}$), we can obtain $\underline{\bm{m}}(\bm{x}_k, \epsilon)$. Then, $-\underline{\bm{m}}(\bm{x}_k, \epsilon)$ is sent to softmax layer for prediction. Importantly, since $[\underline{\bm{m}}(\bm{x}_k, \epsilon)]_{y_k} = 0$ (due to the $y_k$-th row in $C$ is always 0), the top-1 prediction of the augmented IBP network is $y_k$ if and only if all other elements of $\underline{\bm{m}}(\bm{x}_k, \epsilon)$ are positive, i.e., the original network will predict correctly for all $\bm{x}_L \leq \bm{x} \leq \bm{x}_U$. \begin{table}[tbp] \centering \scalebox{0.85}{ \begin{tabular}{c|c|c|c} \toprule Dataset & $\epsilon$ ($\ell_\infty$ norm) & IBP verified error & Convex-adv verified error \\ \midrule \multirow{4}{*}{MNIST} & 0.1 & 5.83\% & 8.90\% \\ \cline{2-4} & 0.2 & 7.37\% & 45.37\% \\ \cline{2-4} & 0.3 & 10.68\% & 97.77\% \\ \cline{2-4} & 0.4 & 16.76\% & 99.98\% \\ \midrule Fashion-MNIST & 0.1 & 23.49\% & 44.64\% \\ \midrule \multirow{2}{*}{CIFAR-10} & 2/255 & 58.75\% & 62.94\% \\ \cline{2-4} & 8/255 & 73.34\% & 91.44\% \\ \bottomrule \end{tabular} } \caption{We train robust neural networks on 3 datasets using Pure-IBP. These models have low IBP verified errors but when they are evaluated with a typically much tighter bound (convex adversarial polytope by~\citet{wong2018scaling}) the verified errors increase significantly, and sometimes the model becomes unverifiable. IBP is \emph{not always looser} than linear relaxation based methods; it can sometimes be powerful. We use a small model in this experiment (see Appendix~\ref{sec:model_structure}). See Table~\ref{tbl:result} for full results on verified errors of our proposed method. } \label{tab:ibp_bound_compare} \end{table} When we train the augmented IBP network with ordinary cross-entropy loss and desire it to predict correctly on an input $\bm{x}_k$, we are implicitly doing robust optimization (Eq. \eqref{eq:adv_training}). We attribute the success of IBP in~\citep{gowal2018effectiveness} to the power of non-linearity -- instead of using linear relaxations of neural networks~\citep{wong2018provable} to obtain $\underline{\bm{m}}$, we train a \emph{non-linear} network that learns to gives us a good quality $\underline{\bm{m}}$. Additionally, we also found that a network trained using IBP is not verifiable using linear relaxation based verification methods, including CROWN~\citep{zhang2018crown}, convex adversarial polytope~\citep{wong2018provable} and Fast-Lin~\citep{weng2018towards}. A purely IBP trained network has low IBP verified error but its verified error using convex adversarial polytope~\citep{wong2018provable} or Fast-Lin~\citep{weng2018towards} can be much higher; sometimes the network becomes unverifiable using these typically tighter bounds (see Table~\ref{tab:ibp_bound_compare}). This also indicates that IBP is a \emph{non-linear mechanism} different from linear relaxation based methods. \begin{wrapfigure}[18]{r}{0.4\textwidth} \centering \includegraphics[width=\linewidth]{model2.pdf} \caption{Verified error and 2nd CNN layer's $\ell_\infty$ induced norm for a model trained using~\citep{wong2018scaling} and CROWN-IBP. $\epsilon$ is increased from 0 to 0.3 in 60 epochs.} \label{fig:weights} \end{wrapfigure} However, IBP is a very loose bound during the initial phase of training, which makes training unstable; purely using IBP frequently leads to divergence. \citet{gowal2018effectiveness} proposed to use a \emph{$\epsilon$ schedule} where $\epsilon$ is gradually increased during training, and a mixture of robust cross-entropy loss with regular cross-entropy loss as the objective to stablize training: \begin{equation} \label{eq:natural-ibp} \min_{\theta} \underset{(\bm{x}, y) \in \mathcal{X}}{E} \Big[ \kappa L(\bm{x}; y; \theta) + (1-\kappa) L(-\underline{\bm{m}}_{\text{IBP}}(\bm{x}, \epsilon); y; \theta) \Big], \end{equation} where $\kappa$ starts with 1 and slowly decreases to $0.5$. \paragraph{Issues with linear relaxation based training.} Since IBP hugely outperforms linear relaxation based methods in the recent work~\citep{gowal2018effectiveness} on some datasets, we want to understand what is going wrong with linear relaxation based methods. We found that the models produced by linear relaxation methods such as~\citep{wong2018provable} and~\citep{wong2018scaling} are over-regularized especially at a larger $\epsilon$. In Figure~\ref{fig:weights} we train a small 4-layer MNIST model and we increase $\epsilon$ from 0 to 0.3 in 60 epochs. We plot the $\ell_\infty$ induced norm of the 2nd CNN layer during the training process on models trained using our method and~\citep{wong2018scaling}. We find that when $\epsilon$ becomes larger (roughly at $\epsilon=0.15$, epoch 30), the norm of weight matrix using ~\citep{wong2018scaling} starts to decrease, indicating that the model is forced to learn small norm weights and thus its representation power is severally reduced. Meanwhile, the verified error also starts to ramp up. Our proposed IBP based training method, CROWN-IBP, does not have this issue; the norm of weight matrices keep increasing during the training process, and verifiable error does not significantly increase when $\epsilon$ reaches 0.3. Another issue with current linear relaxation based training or verification methods, including convex adversarial polytope and CROWN~\citep{zhang2018crown}, is their high computational and memory cost, and poor scalability. For the small network in Figure~\ref{fig:weights}, convex adversarial polytope (with 50 random Cauchy projections) is 8 times slower and takes 4 times more memory than CROWN-IBP (without using random projections). Convex adversarial polytope scales even worse for larger networks; see Appendix~\ref{sec:training_time} for a comparison. \subsection{The proposed algorithm: CROWN-IBP} \label{sec:ouralg} We have reviewed IBP and linear relaxation based methods above. IBP has great representation power due to its non-linearity, but can be tricky to tune due to its very imprecise bound at the beginning; on the other hand, linear relaxation based methods give tighter lower bounds which stabilize training, but it over-regularizes the network and forbids us to achieve good accuracy. We propose CROWN-IBP, a new training method for certified defense where we optimize the following problem ($\theta$ represents the network parameters): \begin{equation} \label{eq:adv_training_crown} \min_{\theta} \underset{(\bm{x}, y) \in \mathcal{X}}{E} \Big[ L\big(-( \beta \underline{\bm{m}}_{\text{IBP}}(\bm{x}, \epsilon) + (1-\beta)\underline{\bm{m}}_{\text{CROWN-IBP}}(\bm{x}, \epsilon)); \enskip y; \enskip \theta\big) \Big], \end{equation} where our lower bound of margin $\underline{\bm{m}}(\bm{x}, \epsilon)$ is a combination of two bounds with different natures: IBP, and a CROWN-style bound; $L$ is the cross-entropy loss. CROWN is a tight linear relaxation based lower bound which is more general and often tighter than convex adversarial polytope. Importantly, CROWN-IBP \emph{avoids the high computational cost} of ordinary CROWN (or many other linear relaxation based methods, like convex adversarial polytope), by applying CROWN-style bound propagation on the final specifications only; intermediate layer bounds $\underline{z}^{l}$ and $\overline{z}^{l}$ are obtained by IBP. We start with $\beta=0$ and use the tight bounds to stabilize initial training. Then we ramp up $\beta$ from 0 to 1 while we increase $\epsilon$ from 0 to $\epsilon_{\text{max}}$, until we reach the desired $\epsilon_{\text{max}}$ and $\beta=1$. The network is trained using pure IBP at that point. \paragraph{Benefits of CROWN-IBP.} First, we compute tight linear relaxation based bounds during the early phase of training, thus greatly improve the stability and reproducibility of IBP. Second, we do not have the over-regularization problem as the CROWN-style bound is gradually phased out during training. Third, unlike the approach used in~\citep{gowal2018effectiveness} that mixes regular cross-entropy loss with robust cross-entropy loss (Eq.~\eqref{eq:natural-ibp}) to stabilize IBP, we use the mixture of two lower bounds, which is still a valid lower bound of $\bm{m}$; thus, we are \emph{strictly within the robust optimization framework} (Eq.~\eqref{eq:adv_training}) and also obtain better empirical results. Forth, because we apply the CROWN-style bound propagation only to the last layer, the computational cost is greatly reduced comparing to other methods that purely relies on linear relaxation based bounds. CROWN-IBP consists of IBP bound propagation in a forward pass and CROWN-style bound propagation in a backward pass. We discuss the details of CROWN-IBP below. \paragraph{Forward Bound Propagation in CROWN-IBP.} In CROWN-IBP, we first obtain $\overline{z}^{(l)}$ and $\underline{z}^{(l)}$ for all layers by applying~\eqref{eq:ibp_upper}, \eqref{eq:ibp_lower} and~\eqref{eq:ibp_act}. Then we will obtain $\underline{\bm{m}}_{\text{IBP}}(\bm{x}, \epsilon)=\underline{z}^{(L)}$ (assuming $C$ is merged into $\W{(L)}$). Obtaining these bounds is similar to forward propagation in IBP-NN (Figure~\ref{fig:augmented}). The time complexity of IBP is comparable to two forward propagation passes of the original network. \paragraph{Linear Relaxation of ReLU neurons} Given $\underline{z}^{(l)}$ and $\overline{z}^{(l)}$ computed in previous step, we first check if some neurons are always active ($\underline{z}^{(l)}_k > 0$) or always inactive ($\overline{z}^{(l)}_k<0$), since these neurons are effectively linear and no relaxations are needed. For the remaining unstable neurons, \citet{zhang2018crown,wong2018scaling} give a linear relaxation for the special case of element-wise ReLU activation function: \begin{equation} \label{eq:relu_linear} \alpha_k z^{(l)}_k \leq \sigma(z^{(l)}_k) \leq \frac{\overline{z}^{(l)}_k}{\overline{z}^{(l)}_k - \underline{z}^{(l)}_k} z^{(l)}_k - \frac{\overline{z}^{(l)}_k \underline{z}^{(l)}_k}{\overline{z}^{(l)}_k - \underline{z}^{(l)}_k}, \quad \text{for all $k\in [n_l]$ and $\underline{z}_k^{(l)} < 0 < \overline{z}_k^{(l)}$}, \end{equation} where $0 \leq \alpha_k \leq 1$; \citet{zhang2018crown} proposes to adaptively select $\alpha_k=1$ when $\overline{z}_k^{(l)} > |\underline{z}_k^{(l)}|$ and 0 otherwise, which minimizes the relaxation error. In other words, for an input vector $z^{(l)}$, we effectively replace the ReLU layer with a linear layer, giving upper or lower bounds of the output: \begin{equation} \label{eq:relu_affine} \Dl{(l)} z^{(l)} \leq \sigma(z^{(l)}) \leq \Du{(l)} z^{(l)} + \overline{c}_d^{(l)} \end{equation} where $\Dl{(l)}$ and $\Du{(l)}$ are two diagonal matrices representing the ``weights'' of the relaxed ReLU layer. In the following we focus on conceptually presenting the algorithm, while more details of each term can be found in the Appendix. \paragraph{Backward Bound Propagation in CROWN-IBP.} Unlike IBP, CROWN-style bounds start computation from the last layer, so we refer it as \emph{backward bound propagation} (not to be confused with the back-propagation algorithm to obtain gradients). Suppose we want to obtain the lower bound $[\underline{\bm{m}}_{\text{CROWN-IBP}}(\bm{x}, \epsilon)]_i = \underline{z}^{(L)}_i$ (we assume the specification matrix $C$ has been merged into $\W{(L)}$). The input to layer $\W{(L)}$ is $\sigma(z^{(L-1)})$, which has already been replaced by Eq.~\eqref{eq:relu_affine}. CROWN-style bounds choose the lower bound of $\sigma(z^{(L-1)}_k)$ (LHS of~\eqref{eq:relu_affine}) when $\W{(L)}_{i,k}$ is positive, and choose the upper bound when $\W{(L)}_{i,k}$ is negative. We then merge $\W{(L)}$ and the linearized ReLU layer together and define: \begin{equation} \label{eq:crown_A} \Al{(L-1)}_{i,:} = \W{(L)}_{i,:} \DD{i,(L-1)}, \quad \DD{i,(L-1)}_{k,k} = \begin{cases} \Dl{(L-1)}_{k,k}, \quad & \text{if $\W{(L)}_{i,k} > 0$} \\ \Du{(L-1)}_{k,k}, \quad & \text{if $\W{(L)}_{i,k} \leq 0$} \end{cases} \end{equation} Now we have a lower bound $\underline{z}^{(L)}_i=\Al{(L-1)}_{i,:} z^{(L-1)} + \underline{b}_i^{(L-1)} \leq {z}^{(L)}_i$ where $\underline{b}_i^{(L-1)} =\sum_{k, \W{(L)}_{i,k} < 0} \W{(L)}_{i,k} \overline{c}_k^{(l)} + \mathbf{b}^{(L)}$ collects all terms not related to ${z}^{(L-1)}$. Note that the diagonal matrix $\DD{i,(L-1)}$ implicitly depends on $i$. Then, we merge $\Al{(L-1)}_{i,:}$ with the next linear layer, which is straight forward by plugging in $z^{(L-1)}=\W{(L-1)}\sigma(z^{(L-2)}) + \mathbf{b}^{(L-1)}$: \[ {z}^{(L)}_i \geq \Al{(L-1)}_{i,:} \W{(L-1)}\sigma(z^{(L-2)}) + \Al{(L-1)}_{i,:} \mathbf{b}^{(L-1)} + \underline{b}_i^{(L-1)}. \] Then we continue to unfold the next ReLU layer $\sigma(z^{(L-2)})$ using its linear relaxations, and compute a new $\Al{(L-2)} \in \mathbb{R}^{n_L \times n_{L-2}}$ matrix, with $\Al{(L-2)}_{i,:} = \Al{(L-1)}_{i,:} \W{(L-1)} \DD{i,(L-2)}$ in a similar manner as in~\eqref{eq:crown_A}. Along with the bound propagation process, we need to compute a series of matrices, $\Al{(L-1)}, \cdots, \Al{(0)}$, where $\Al{(l)}_{i,:} = \Al{(l+1)}_{i,:} \W{(l+1)} \DD{i,(l)} \in \mathbb{R}^{n_L \times n_{(l)}}$, and $\Al{(0)}_{i,:}=\Al{(1)}_{i,:} \W{(1)} = \W{(L)}_{i,:} \DD{i,(L-1)} \W{(L-2)} \DD{i,(L-2)} \Al{(L-2)} \cdots \DD{i,(1)} \W{(1)}$. At this point, we merged all layers of the network into a linear layer: ${z}^{(L)}_i \geq \Al{(0)}_{i,:} \bm{x} + \underline{b},$ where $\underline{b}$ collects all terms not related to $\bm{x}$. A lower bound for ${z}^{(L)}_i$ with $\bm{x}_L \leq \bm{x} \leq \bm{x}_U$ can then be easily given as \begin{equation} \label{eq:crown_final} [\underline{\bm{m}}_{\text{CROWN-IBP}}]_i \equiv \underline{z}^{(L)}_i = \Al{(0)}_{i,:} \bm{x} + \underline{b} \geq \sum\nolimits_{k, \Al{(0)}_{i,k} < 0}\Al{(0)}_{i,k} \bm{x}_{U,k} + \sum\nolimits_{k, \Al{(0)}_{i,k} > 0}\Al{(0)}_{i,k} \bm{x}_{L,k} + \underline{b} \end{equation} For ReLU networks, convex adversarial polytope~\citep{wong2018provable} uses a very similar bound propagation procedure. CROWN-style bounds allow an adaptive selection of $\alpha_i$ in~\eqref{eq:relu_linear}, thus often gives slightly better bounds. We give details on each term in Appendix~\ref{sec:crown_exact}. \paragraph{Computational Cost of CROWN-IBP.} In ordinary CROWN~\citep{zhang2018crown} and convex adversarial polytope~\citep{wong2018provable}, the bound propagation process is much more expensive than CROWN-IBP, since it needs to use~\eqref{eq:crown_final} to compute \textit{all intermediate layer's} $\underline{z}^{(m)}_i$ and $\overline{z}^{(m)}_i$ ($m \in [L]$), by considering $\W{(m)}$ as the final layer of the network. In this case, for each layer $m$ we need a different set of $\Al{}$ matrices, defined as $\Al{m,(l)}, l \in \{m-1, \cdots , 0\}$. This causes three computational issues: \begin{enumerate} \item Unlike the last layer $\W{(L)}$, an intermediate layer $\W{(m)}$ has a much larger output dimension ${n_m} \gg n_L$ typically thus all $\Al{m,(l)} \in \{ \Al{m,(m-1)}, \cdots, \Al{m,(0)}\}$ will have large dimensions $\mathbb{R}^{n_m \times n_l}$. \item Computation of all $\Al{m,(l)}$ matrices is expensive. Suppose the network has $n$ neurons for all $L-1$ intermediate and input layers and $n_L \ll n$ neurons for the output layer (assuming $L \geq 2$), the time complexity of ordinary CROWN or convex adversarial polytope is $O(\sum_{l=1}^{L-2} l n^3 + (L-1)n_L n^2) = O((L-1)^2 n^3 + (L-1)n_L n^2)=O(L n^2 (L n + n_L))$. A ordinary forward propagation only takes $O(Ln^2)$ time per example, thus ordinary CROWN does not scale up to large networks for training, due to its quadratic dependency in $L$ and extra $Ln$ times overhead. \item When both $\W{(l)}$ and $\W{(l-1)}$ represent convolutional layers with small kernel tensors $\mathbf{K}^{(l)}$ and $\mathbf{K}^{(l-1)}$, there are no efficient GPU operations to form the matrix $\W{(l)} \DD{(l-1)} \W{(l-1)}$ using $\mathbf{K}^{(l)}$ and $\mathbf{K}^{(l-1)}$. Existing implementations either unfold at least one of the convolutional kernels to fully connected weights, or use sparse matrices to represent $\W{(l)}$ and $\W{(l-1)}$. They suffer from poor hardware efficiency on GPUs. \end{enumerate} In CROWN-IBP, we do not have the first and second issues since we use IBP to obtain intermediate layer bounds, which is only slower than forward propagation by a constant factor. The time complexity of the backward bound propagation in CROWN-IBP is $O((L-1)n_L n^2)$, only $n_L$ times slower than forward propagation and significantly more scalable than ordinary CROWN (which is $L n$ times slower than forward propagation, where typically $n \gg n_L$). The third issue is also not a concern, since we start from the last specification layer $\W{(L)}$ which is a small fully connected layer. Suppose we need to compute $\W{(L)} \DD{(L-1)} \W{(L-1)}$ and $\W{(L-1)}$ is a convolutional layer with kernel $\mathbf{K}^{(L-1)}$, we can efficiently compute $(\W{(L-1)\top} (\DD{(L-1)} \W{(L)\top}))^\top$ on GPUs using the \emph{transposed convolution} operator with kernel $\mathbf{K}^{(L-1)}$. Conceptually, the backward pass of CROWN-IBP propagates a small specification matrix $\W{(L)}$ backwards, replacing affine layers with their transposed operators, and activation function layers with a diagonal matrix product. This allows efficient implementation and better scalability. \section{Hyperparameters in Experiments} \label{sec:model_parameters} All our MNIST, CIFAR-10 models are trained on a single NVIDIA 2080 Ti GPU. In all our experiments, if not mentioned otherwise, we use the following hyperparameters: \begin{itemize} \item For MNIST, we train 100 epochs with batch size 256. We use Adam optimizer and the learning rate is $5\times 10^{-4}$. The first epoch is standard training for warming up. We gradually increase $\epsilon$ linearly per batch in our training process with a $\epsilon$ schedule length of 60. We reduce the learning rate by 50\% every 10 epochs after $\epsilon$ schedule ends. No data augmentation technique is used and the whole 28 $\times$ 28 images are used (normalized to 0 - 1 range). \item For CIFAR, we train 200 epoch with batch size 128. We use Adam optimizer and the learning rate is 0.1\%. The first 10 epochs are standard training for warming up. We gradually increase $\epsilon$ linearly per batch in our training process with a $\epsilon$ schedule length of 120. We reduce the learning rate by 50\% every 10 epochs after $\epsilon$ schedule ends. We use random horizontal flips and random crops as data augmentation. The three channels are normalized with mean (0.4914, 0.4822, 0.4465) and standard deviation (0.2023, 0.1914, 0.2010). These numbers are per-channel statistics from the training set used in~\citep{gowal2018effectiveness}. \end{itemize} For all experiments, we set $\beta=1$ when the $\epsilon$ schedule starts. We decrease $\beta$ linearly to 0 when $\epsilon$ finishes its increasing schedule and reaches $\epsilon_{\text{max}}$. We did not tune the schedule for parameter $\beta$, and it always has the same schedule length as the $\epsilon$ schedule. All verified error numbers are evaluated on the test set, using IBP, since the networks are trained using pure IBP after $\epsilon$ reaches the target. We found that CROWN~\citep{zhang2018crown} or Fast-Lin~\citep{weng2018towards} cannot give tight verification bounds on IBP trained models (some comparison results are given in Table~\ref{tab:ibp_bound_compare}). \section{Model Structure} \label{sec:model_structure} \begin{table*}[bhtp] \vskip 0.15in \begin{center} \begin{adjustbox}{max width=\textwidth} \begin{tabular}{l|l} \toprule Name & Model Structure (all models have a last FC 10 layer, which are omitted) \\ \midrule A (MNIST Only) & Conv 4 $4 \times 4$+2, Conv 8 $4 \times 4$+2, FC 128 \\ B & Conv 8 $4 \times 4$+2, Conv 16 $4 \times 4$+2, FC 256 \\ C & Conv 4 $3 \times 3$+1, Conv 8 $3 \times 3$+1, Conv 8 $4 \times 4$+4, FC 64 \\ D & Conv 8 $3 \times 3$+1, Conv 16 $3 \times 3$+1, Conv 16 $4 \times 4$+4, FC 128 \\ E & Conv 4 $5 \times 5$+1, Conv 8 $5 \times 5$+1, Conv 8 $5 \times 5$+4, FC 64 \\ F & Conv 8 $5 \times 5$+1, Conv 16 $5 \times 5$+1, Conv 16 $5 \times 5$+4, FC 128 \\ G & Conv 4 $3 \times 3$+1, Conv 4 $4 \times 4$+2, Conv 8 $3 \times 3$+1, Conv 8 $4 \times 4$+2, FC 256, FC 256 \\ H & Conv 8 $3 \times 3$+1, Conv 8 $4 \times 4$+2, Conv 16 $3 \times 3$+1, Conv 16 $4 \times 4$+2, FC 256, FC 256 \\ I & Conv 4 $3 \times 3$+1, Conv 4 $4 \times 4$+2, Conv 8 $3 \times 3$+1, Conv 8 $4 \times 4$+2, FC 512, FC 512 \\ J & Conv 8 $3 \times 3$+1, Conv 8 $4 \times 4$+2, Conv 16 $3 \times 3$+1, Conv 16 $4 \times 4$+2, FC 512, FC 512 \\\hline K&Conv 16 $3 \times 3$+1, Conv 16 $4 \times 4$+2, Conv 32 $3 \times 3$+1, Conv 32 $4 \times 4$+2, FC 256, FC 256\\ L&Conv 16 $3 \times 3$+1, Conv 16 $4 \times 4$+2, Conv 32 $3 \times 3$+1, Conv 32 $4 \times 4$+2, FC 512, FC 512\\ M&Conv 32 $3 \times 3$+1, Conv 32 $4 \times 4$+2, Conv 64 $3 \times 3$+1, Conv 64 $4 \times 4$+2, FC 512, FC 512\\ N&Conv 64 $3 \times 3$+1, Conv 64 $4 \times 4$+2, Conv 128 $3 \times 3$+1, Conv 128 $4 \times 4$+2, FC 512, FC 512\\ O(MNIST Only)&Conv 64 $5 \times 5$+1, Conv 128 $5 \times 5$+1, Conv 128 $4 \times 4$+4, FC 512 \\ P(MNIST Only)&Conv 32 $5 \times 5$+1, Conv 64 $5 \times 5$+1, Conv 64 $4 \times 4$+4, FC 512 \\ Q&Conv 16 $5 \times 5$+1, Conv 32 $5 \times 5$+1, Conv 32 $5 \times 5$+4, FC 512 \\ R&Conv 32 $3 \times 3$+1, Conv 64 $3 \times 3$+1, Conv 64 $3 \times 3$+4, FC 512 \\ S(CIFAR Only)& Conv 32 $4 \times 4$+2, Conv 64 $4 \times 4$+2, FC 128 \\ T(CIFAR Only)& Conv 64 $4 \times 4$+2, Conv 128 $4 \times 4$+2, FC 256 \\ \bottomrule \end{tabular} \end{adjustbox} \end{center} \caption{Model structures used in all of our experiments. We use ReLU activations for all models. To save space, we omit the last fully connected layer as its output dimension is always 10. In the table, ``Conv $k\ w\times w+s$'' represents to a 2D convolutional layer with $k$ filters of size $w\times w$ and a stride of $s$.} \label{tb:models} \vskip -0.1in \end{table*} Table~\ref{tb:models} gives the 18 model structures used in our paper. MNIST and Fashion-MNIST use exactly the same model structures. Most CIFAR models share the same structures as MNIST models (unless noted on the table) except that their input dimensions are different. Model A is too small for CIFAR thus we remove it for CIFAR experiments. Models A - J are the ``small models'' reported in Table~\ref{tbl:result}. Models K - T are the ``large models'' reported in Table~\ref{tbl:result}. For results in Table~\ref{tab:ibp_bound_compare}, we use a small model (model structure B) for all three datasets. \section{Reproducibility} \label{sec:reproduce} \input{stabletable} We run CROWN-IBP on 10 small MNIST models, 5 times each, and report the mean and standard deviation of standard and verified errors in Table~\ref{tab:stable}. We can observe that the results from multiple runs are very similar with small standard deviations, so reproducibility is not an issue for CROWN-IBP. \section{Training Stability Experiments on CIFAR} \label{sec:appendix-stability} Similar to our experiments in Section~\ref{sec:stability}, we compare the verified errors obtained by CROWN-IBP, Natural-IBP and Pure-IBP under different $\epsilon$ schedule lengths (30, 90, 120). We present the best, worst and median verified errors over all 17 models for CIFAR-10 in Figure~\ref{fig:cifarepsschedule1} and ~\ref{fig:cifarepsschedule2}, at $\epsilon=\{\frac{2}{255}, \frac{8}{255}\}$. The upper and lower bound of an error bar are the worst and best verified error, respectively, and the lines go through median values. CROWN-IBP can improve training stability, and consistently outperform other methods. Pure-IBP cannot stably converge on all models when $\epsilon$ schedule is short, and verified errors tend to be higher. Natural-IBP is sensitive to $\kappa$ setting; with $\kappa=0.5$ many models have high robust errors (as shown in Figure~\ref{fig:cifarepsschedule2_8-255}). \begin{figure}[htbp] \centering \begin{minipage}[b]{0.45\textwidth} \begin{subfigure}{\linewidth} \includegraphics[width=\textwidth]{new_figs/cifar_cifar_crown_000784.pdf} \caption{$\epsilon=\frac{2}{255}$, best $\mathbf{52.22\%}$ \label{fig:eps02schedule} \end{subfigure} \end{minipage}~~ \begin{minipage}[b]{0.45\textwidth} \begin{subfigure}{\linewidth} \includegraphics[width=\textwidth]{new_figs/cifar_cifar_crown_003137.pdf} \caption{$\epsilon=\frac{8}{255}$, best $\mathbf{70.82\%}$ \label{fig:eps03schedule} \end{subfigure} \end{minipage} \caption{Verified error vs. $\epsilon$ schedule length (30, 90, 120) on 9 small CIFAR models. The upper and lower ends of a vertical bar represent the worst and best verified error, respectively. The dotted lines go through median values. } \label{fig:cifarepsschedule1} \end{figure} \begin{figure}[htbp] \centering \begin{minipage}[b]{0.45\textwidth} \begin{subfigure}{\linewidth} \includegraphics[width=\textwidth]{new_figs/cifar_cifar_crown_large_000784.pdf} \caption{$\epsilon=\frac{2}{255}$, best $\mathbf{52.52\%}$ \label{fig:cifarepsschedule2_2-255} \end{subfigure} \end{minipage}~~ \begin{minipage}[b]{0.45\textwidth} \begin{subfigure}{\linewidth} \includegraphics[width=\textwidth]{new_figs/cifar_cifar_crown_large_003137.pdf} \caption{$\epsilon=\frac{8}{255}$, best $\mathbf{70.61\%}$ \label{fig:cifarepsschedule2_8-255} \end{subfigure} \end{minipage} \caption{Verified error vs. $\epsilon$ schedule length (30, 90, 120) on 8 large CIFAR models. The upper and lower bound of an error bar are worst and best verified error, respectively. The dotted lines go through median values. } \label{fig:cifarepsschedule2} \end{figure} \section{Training Time} \label{sec:training_time} In Table~\ref{tab:time} we present the training time of CROWN-IBP, Pure-IBP and convex adversarial polytope~\citep{wong2018scaling} on several representative models. All experiments are measured on a single RTX 2080 Ti GPU with 11 GB RAM. We can observe that CROWN-IBP is practically 2 to 7 times slower than Pure-IBP (theoretically, CROWN-IBP is up to $n_L = 10$ times slower than Pure-IBP); convex adversarial polytope~\citep{wong2018scaling}, as a representative linear relaxation based method, can be over hundreds times slower than Pure-IBP especially on deeper networks. Note that we use 50 random Cauchy projections for~\citep{wong2018scaling}. Using random projections alone is not sufficient to scale purely linear relaxation based methods to larger datasets, thus we advocate a combination of non-linear IBP bounds with linear relaxation based methods as in CROWN-IBP, which offers good scalability, stability and representation power. We also note that the random projection based acceleration can also be applied to the backward bound propagation (CROWN-style bound) in CROWN-IBP to further speed CROWN-IBP up. \begin{table}[htbp] \centering \scalebox{0.85}{ \begin{tabular}{c|c|c|c|c|c|c|c|c|c|c} \toprule Data&\multicolumn{5}{c|}{MNIST}&\multicolumn{5}{c}{CIFAR}\\\hline Model Name&A&C&G&L&O&B&D&H&S&M\\\hline Pure-IBP (s) & 245 & 264 & 290 & 364 & 1032 & 734 & 908 & 1048 & 691 & 1407\\ CROWN-IBP (s)& 423 & 851 & 748 & 1526 & 7005 & 1473 & 3351 & 2962 & 1989 & 6689\\ Convex adv~\citep{wong2018scaling} (s) & 1708 & 9263 & 12649 & 35518 & 160794 & 2372 & 12688 & 18691 & 6961 & 51145\\ \bottomrule \end{tabular} } \caption{Pure-IBP and CROWN-IBP's training time on different models in seconds. For Pure-IBP and CROWN-IBP, we use a batchsize of 256 for MNIST and 128 for CIFAR. For convex adversarial polytope, we use 50 random Cauchy projections, and reduce batch size if necessary to fit into GPU memory.} \label{tab:time} \end{table} \section{Exact Forms of the CROWN-IBP Backward Bound} \label{sec:crown_exact} CROWN~\citep{zhang2018crown} is a general framework that replaces non-linear functions in a neural network with linear upper and lower hyperplanes with respect to pre-activation variables, such that the entire neural network function can be bounded by a linear upper hyperplane and linear lower hyperplane for all $\bm{x} \in S$ ($S$ is typically a norm bounded ball, or a box region): \[ \underline{\mathbf{A}}x + \underline{\mathbf{b}} \leq f(\bm{x}) \leq \overline{\mathbf{A}}x + \overline{\mathbf{b}} \] CROWN achieves such linear bounds by replacing non-linear functions with linear bounds, and utilizing the fact that the linear combinations of linear bounds are still linear, thus these linear bounds can propagate through layers. Suppose we have a non-linear vector function $\sigma$, applying to an input (pre-activation) vector $z$, CROWN requires the following bounds in a general form: \[ \underline{\mathbf{A}}_\sigma z + \underline{\mathbf{b}}_\sigma \leq \sigma(z) \leq \overline{\mathbf{A}}_\sigma z + \overline{\mathbf{b}}_\sigma \] In general the specific bounds $\underline{\mathbf{A}}_\sigma, \underline{\mathbf{b}}_\sigma, \overline{\mathbf{A}}_\sigma, \overline{\mathbf{b}}_\sigma$ for different $\sigma$ needs to be given in a case-by-case basis, depending on the characteristics of $\sigma$ and the preactivation range $\underline{z} \leq z \leq \overline{z}$. In neural network common $\sigma$ can be ReLU, $\tanh$, $\text{sigmoid}$, $\text{maxpool}$, etc. Convex adversarial polytope~\citep{wong2018scaling} is also a linear relaxation based techniques that is closely related to CROWN, but only for ReLU layers. For ReLU such bounds are simple, where $\underline{\mathbf{A}}_\sigma, \overline{\mathbf{A}}_\sigma$ are diagonal matrices, $\underline{\mathbf{b}}_\sigma = \bm{0}$: \begin{equation} \label{eq:relu_affine_appdix} \Dl{} z \leq \sigma(z) \leq \Du{} z + \overline{c} \end{equation} where $\Dl{}$ and $\Du{}$ are two diagonal matrices: \begin{align} \Dl{}_{k,k} &= \begin{cases} 1, &\text{if $\underline{z}_k > 0$, i.e., this neuron is always active} \\ 0, &\text{if $\overline{z}_k < 0$, i.e., this neuron is always inactive} \\ \alpha, &\text{otherwise, any $0 \leq \alpha \leq 1$} \end{cases} \\ \Du{}_{k,k} &= \begin{cases} 1, &\text{if $\underline{z}_k > 0$, i.e., this neuron is always active} \\ 0, &\text{if $\overline{z}_k < 0$, i.e., this neuron is always inactive} \\ \frac{\overline{z}_k}{\overline{z}_k - \underline{z}_k}, &\text{otherwise} \end{cases} \\ \overline{c}_{k} &= \begin{cases} 0, &\text{if $\underline{z}_k > 0$, i.e., this neuron is always active} \\ 0, &\text{if $\overline{z}_k < 0$, i.e., this neuron is always inactive} \\ \frac{\overline{z}_k \underline{z}_k}{\overline{z}_k - \underline{z}_k}, &\text{otherwise} \end{cases} \end{align} Note that CROWN-style bounds require to know all pre-activation bounds $\underline{z}^{(l)}$ and $\overline{z}^{(l)}$. We assume these bounds are valid for $\bm{x} \in S$. In CROWN-IBP, these bounds are obtained by interval bound propagation (IBP). With pre-activation bounds $\underline{z}^{(l)}$ and $\overline{z}^{(l)}$ given (for $\bm{x} \in S$), we rewrite the CROWN lower bound for the special case of ReLU neurons: \begin{theorem}[CROWN Lower Bound]\label{thm:outputbnd} For a $L$-layer neural network function $f(\bm{x}) : \mathbb{R}^{n_0} \rightarrow \mathbb{R}^{n_L}$, $\forall j \in [n_L], \; \forall \bm{x} \in S$, we have $\underline{f_{j}}(\bm{x}) \leq f_{j}(\bm{x})$, where \begin{equation} \label{eq:f_j_UL} \underline{f_{j}}(\bm{x}) = \Al{(0)}_{j,:} \bm{x} + \sum_{l=1}^{L}\Al{(l)}_{j,:}(\mathbf{b}^{(l)}+\lwbias{j,(l)}), \end{equation} \begin{equation*} \Al{(l)}_{j,:} = \begin{cases} \mathbf{e}^\top_j & \text{if } l = L; \\ \Al{(l+1)}_{j,:} \W{(l+1)} \DD{j,(l)} & \text{if } l \in \{0, \cdots, L-1\}. \end{cases} \end{equation*} and $\forall i \in [n_k]$, we define diagonal matrices $\DD{j,(l)}$, bias vector $\lwbias{(l)}$: \begin{align*} \DD{j,(0)} &= \bm{I}, \quad \lwbias{j,(L)} = \bm{0} \\ \DD{j,(l)}_{k,k} &= \begin{cases} 1 & \text{if } \Al{(l+1)}_{j,:} \W{(l+1)}_{:,i} \geq 0, \overline{z}^{(l)}_k > |\underline{z}^{(l)}_k|, \enskip l \in \{1, \cdots, L-1\}; \\ 0 & \text{if } \Al{(l+1)}_{j,:} \W{(l+1)}_{:,i} \geq 0, \overline{z}^{(l)}_k < |\underline{z}^{(l)}_k|, \enskip l \in \{1, \cdots, L-1\}; \\ \frac{\overline{z}^{(l)}_k}{\overline{z}^{(l)}_k - \underline{z}^{(l)}_k} & \text{if } \Al{(k+1)}_{j,:} \W{(k+1)}_{:,i} < 0, \enskip l \in \{1, \cdots, L-1\}. \end{cases} \\ \lwbias{j,(l)}_{k} &= \begin{cases} 0 & \text{if } \Al{(l+1)}_{j,:} \W{(l+1)}_{:,i} \geq 0; \enskip l \in \{1, \cdots, L-1\} \\ \frac{\overline{z}^{(l)}_k \underline{z}^{(l)}_k}{\overline{z}^{(l)}_k - \underline{z}^{(l)}_k} & \text{if } \Al{(l+1)}_{j,:} \W{(l+1)}_{:,i} < 0 \enskip l \in \{1, \cdots, L-1\}. \end{cases} \end{align*} $\mathbf{e}_j \in \mathbb{R}^{n_{L}}$ is a standard unit vector with $j$-th coordinate set to 1. \end{theorem} Note that unlike the ordinary CROWN~\citep{zhang2018crown}, in CROWN-IBP we only need the lower bound to compute $\underline{\bm{m}}$ and do not need to compute the $\Al{}$ matrices for the upper bound. This save half of the computation cost in ordinary CROWN. Also, $\W{}$ represents any affine layers in a neural network, including convolutional layers in CNNs. In Section~\ref{sec:ouralg}, we discussed how to use transposed convolution operators to efficiently implement CROWN-IBP on GPUs. Although in this paper we focus on the common case of ReLU activation function, other general activation functions (sigmoid, max-pooling, etc) can be used in the network as CROWN is a general framework to deal with non-linearity. For a more general derivation we refer the readers to~\citep{zhang2018crown} and~\citep{salman2019convex}. \subsection{Setup and Models} To discourage hand-tuning on a small set of models, we use 20 different model architectures for a total of \textbf{53 models} for MNIST, Fashion-MNIST and CIFAR-10 datasets, from small $2\times$CNN$+2\times$FC models to wide $4\times$CNN$+3\times$FC models. The models are a mixture of networks with different depths, widths and convolution kernel sizes. Details are presented in Appendix~\ref{sec:model_structure}. We consider $\ell_\infty$ robustness and report both the best and worst verified error achieved over all models, and the median of error. Verified errors are evaluated using IBP on the test set. The median error implies that at least half of models trained are as good as this error. We list hyperparameters in Appendix~\ref{sec:model_parameters}. Since we focus on improving stability and performance of IBP models, in experiments we compare three different variants of IBP\footnote{Our implementations of all IBP variants used in this paper is available at \textcolor{blue}{\url{https://github.com/huanzhang12/CROWN-IBP}}}: \begin{itemize \item \textbf{CROWN-IBP}: our proposed method, using CROWN-style linear relaxations in a backward manner to improve IBP training stability, and a mixture of CROWN and IBP lower bounds in robust cross-entropy (CE) loss, as in Eq.~\eqref{eq:adv_training_crown}. No regular CE loss is used. \item \textbf{Pure-IBP}: using the lower bounds purely from IBP in robust CE loss. No regular CE loss is used. Equivalent to Eq.~\eqref{eq:adv_training_crown} with $\beta$ fixed to 1. \item \textbf{Natural-IBP}-$\kappa$: proposed by~\citep{gowal2018effectiveness}, using the lower bounds provided by IBP in robust CE loss (multiplied by $1 - \kappa$), plus $\kappa$ times a regular CE loss term as in Eq.~\eqref{eq:natural-ibp}. This $\kappa$ is initialized as 1 and is gradually reduced during training. In our experiments we choose two final $\kappa$ values, 0.5 and 0. Note that \citet{gowal2018effectiveness} uses 0.5 as the final $\kappa$ value. \end{itemize} \input{bigtable1} \subsection{Comparisons to IBP based methods} In Table~\ref{tbl:result} we show the verified errors on test sets for CROWN-IBP and the other two IBP baselines. We also include best verified errors reported in literature for comparison. Numbers reported in~\cite{gowal2018effectiveness} use the same training method as Natural IBP with final $\kappa=0.5$, albeit they use different hyperparameters and sometimes different $\epsilon$ for training and evaluation; we always use the same $\epsilon$ value for training and evaluation. CROWN-IBP's best, median, and worst test verified errors are consistently better than all other IBP-based baselines across all models and $\epsilon$'s. Especially, on MNIST with $\epsilon=0.3$ and $\epsilon=0.4$ we achieve 7.46\% and 12.96\% best verified error, respectively, outperforming all previous works and significantly better than convex relaxation based training methods~\citep{wong2018scaling}; a similar level of advantage can also be observed on Fashion-MNIST~\citep{wong2018provable}. For small $\epsilon=\{0.1,0.2\}$ on MNIST, we find that IBP based methods tend to overfit. For example, adding an $\ell_1$ regularization term can decreases verified error at $\epsilon=0.1$ from 5.63\% to 3.60\% (see Section~\ref{sec:small_eps} for more details); this explains the performance gap in Table~\ref{tbl:result} at small $\epsilon$ between CROWN-IBP and convex adversarial polytope, since the latter method provides implicit $\ell_1$ regularization. On CIFAR-10 with $\epsilon=\frac{8}{255}$, CROWN-IBP is better than all other methods except~\citep{gowal2018effectiveness}; however, \cite{gowal2018effectiveness} obtained the best result by using a large network trained for 3200 epochs with a fine-tuned $\epsilon$ schedule on 32 TPUs; practically, the reproduciable verified error by~\cite{gowal2018effectiveness} is around 71\% - 72\% (see notes under table). In contrast, our results can be obtained in reasonable time using a single RTX 2080 Ti GPU. We include training time comparisons in Appendix~\ref{sec:training_time}. \vspace{-0.3cm} \subsection{Training stability} \label{sec:stability} To evaluate training stability, we compare the verified errors obtained by training processes under different $\epsilon$ schedule length (10, 15, 30, 60). We compare the best, worst and median verified errors over all 18 models for MNIST. Our results are presented in Figure~\ref{fig:epsschedulel} (for 8 large models) and Figure~\ref{fig:epsschedule} (for 10 small models) at $\epsilon=0.1,0.2,0.3$. The upper and lower bound of an error bar are the worst and best verified error, respectively, and the lines go through median values. We can see that both Natural-IBP and CROWN-IBP can improve training stability when the schedule length is not sufficient (10, 20 epochs). When schedule length is above 30, CROWN-IBP's verified errors are consistently better than any other method. Pure-IBP cannot stably converge on all models when $\epsilon$ schedule is short, espeically for a larger $\epsilon$. We conduct additional training stability experiments on CIFAR-10 dataset and the observations are similar (see Appendix~\ref{sec:appendix-stability}). Another interesting observation is that at a small $\epsilon=\{0.1,0.2\}$, a shorter $\epsilon$ schedule improves results for large models (Figure~\ref{fig:epsschedulel}). This is due to early stopping which controls overfitting (see Section~\ref{sec:small_eps}). Since we decrease the learning rate by half every 10 epochs after the schedule ends, a shorter $\epsilon$ schedule implies that the learning process stops earlier. To further test the training stability of CROWN-IBP, we run each MNIST experiment (in Table~\ref{tbl:result}) 5 times on 10 small models. The mean and standard deviation of the verified and standard errors on test set are presented in Appendix~\ref{sec:reproduce}. Standard deviations of verified errors are very small, giving us further evidence of good stability. \begin{figure}[tbp] \centering \begin{minipage}[b]{0.32\textwidth} \begin{subfigure}{\linewidth} \includegraphics[width=\textwidth]{new_figs/mnist_crown_large_01.pdf} \caption{$\epsilon=0.1$, best $\mathbf{3.55\%}$ \label{fig:eps02schedulel} \end{subfigure} \end{minipage}~~ \begin{minipage}[b]{0.32\textwidth} \begin{subfigure}{\linewidth} \includegraphics[width=\textwidth]{new_figs/mnist_crown_large_02.pdf} \caption{$\epsilon=0.2$, best $\mathbf{4.98\%}$ \label{fig:eps03schedulel} \end{subfigure} \end{minipage}~~ \begin{minipage}[b]{0.32\textwidth} \begin{subfigure}{\linewidth} \includegraphics[width=\textwidth]{new_figs/mnist_crown_large_03.pdf} \caption{ $\epsilon=0.3$, best $\mathbf{7.46\%}$} \label{fig:eps03schedulel} \end{subfigure} \end{minipage} \caption{Verified error vs. $\epsilon$ schedule length (10, 20, 30, 60) on 8 large MNIST models. The upper and lower ends of a vertical bar represent the worst and best verified error, respectively. The dotted lines go through median values. For a small $\epsilon$, using a shorter schedule length improves verified error due to early stopping, which prevents overfitting. All best verified errors are achieved by CROWN-IBP regardless of schedule length. } \label{fig:epsschedulel} \end{figure} \begin{figure}[tbp] \centering \begin{minipage}[b]{0.32\textwidth} \begin{subfigure}{\linewidth} \includegraphics[width=\textwidth]{new_figs/mnist_crown_01.pdf} \caption{$\epsilon=0.1$, best $\mathbf{4.05\%}$ \label{fig:eps02schedule} \end{subfigure} \end{minipage}~~ \begin{minipage}[b]{0.32\textwidth} \begin{subfigure}{\linewidth} \includegraphics[width=\textwidth]{new_figs/mnist_crown_02.pdf} \caption{$\epsilon=0.2$, best $\mathbf{6.11\%}$ \label{fig:eps03schedule} \end{subfigure} \end{minipage}~~ \begin{minipage}[b]{0.32\textwidth} \begin{subfigure}{\linewidth} \includegraphics[width=\textwidth]{new_figs/mnist_crown_03.pdf} \caption{ $\epsilon=0.3$, best $\mathbf{8.87\%}$} \label{fig:eps03schedule} \end{subfigure} \end{minipage} \caption{Verified error vs. $\epsilon$ schedule length (10, 20, 30, 60) on 10 small MNIST models. The upper and lower ends of a vertical bar represent the worst and best verified error, respectively. All best verified errors are achieved by CROWN-IBP regardless of schedule length. The dotted lines go through median values. } \label{fig:epsschedule} \end{figure} \label{sec:eps_schedule_appdix} \subsection{Overfitting issue with small $\epsilon$} \label{sec:small_eps} We found that on MNIST for a small $\epsilon$, the verified error obtained by IBP based methods are not as good as linear relaxation based methods~\citep{wong2018scaling,mirman2018differentiable}. \citet{gowal2018effectiveness} thus propose to train models using a larger $\epsilon$ and evaluate them under a smaller $\epsilon$, for example $\epsilon_{\text{train}}=0.4$ and $\epsilon_{\text{eval}}=0.3$. Instead, we investigated this issue further and found that many CROWN-IBP trained models achieve very small verified errors (close to 0 and sometimes exactly 0) on training set (see Table~\ref{tab:reg}). This indicates possible overfitting during training. As we discussed in Section~\ref{sec:motivation}, linear relaxation based methods implicitly regularize the weight matrices so the network does not overfit when $\epsilon$ is small. Inspired by this finding, we want to see if adding an explicit $\ell_1$ regularization term in CROWN-IBP training helps when $\epsilon=0.1$ or $0.2$. The verified and standard errors on the training and test sets with and without regularization can be found in Table~\ref{tab:reg}. We can see that with a small $\ell_1$ regularization added ($\lambda=5\times 10^{-5}$) we can reduce verified error on test set significantly. This makes CROWN-IBP results comparable to the numbers reported in convex adversarial polytope~\citep{wong2018scaling}; at $\epsilon=0.1$, the best model using convex adversarial polytope training can achieve $3.67\%$ certified error, while CROWN-IBP achieves $3.60\%$ best certified error on the models presented in Table~\ref{tab:reg}. The overfitting is likely caused by IBP's strong representation power, which also explains why IBP based methods significantly outperform linear relaxation based methods at larger $\epsilon$ values. Using early stopping can also improve verified error on test set; see Section~\ref{sec:stability}. \begin{table}[htbp] \centering \scalebox{0.75}{ \begin{tabular}{c|c|c|c|c|c|c} \toprule $\epsilon$&Model Name&$\lambda$: $\ell_1$ regularization&\multicolumn{2}{c|}{Training}&\multicolumn{2}{c}{Test}\\ &(see Appendix~\ref{sec:model_structure})&&standard error&verified error&standard error&verified error\\\midrule \multirow{4}{*}{0.1}&P &0&0.01\%&0.01\%&1.05\%&5.63\%\\ &P&$5\times 10^{-5}$&0.32\%&0.98\%&1.30\%&\bf 3.60\%\\ &O&0&0.02\%&0.05\%&0.82\%&6.02\%\\ &O&$5\times 10^{-5}$&0.38\%&1.34\%&1.43\%& 4.02\%\\\hline \multirow{4}{*}{0.2}&P&0&0.35\%&1.40\%&1.09\%&6.06\%\\ &P&$5\times 10^{-5}$&1.02\%&3.73\%&1.48\%&\bf 5.48\%\\ &O&0&0.31\%&1.54\%&1.22\%&6.64\%\\ &O&$5\times 10^{-5}$&1.09\%&4.08\%&1.69\%& 5.72\%\\ \bottomrule \end{tabular} } \caption{$\ell_1$ regularized and unregularized models' standard and verified errors on training and test set. At a small $\epsilon$, CROWN-IBP may overfit and adding regularization helps robust generalization; on the other hand, convex relaxation based methods~\citep{wong2018scaling} provides implicitly regularization which helps generalization under small $\epsilon$ but deteriorate model performance at larger $\epsilon$.} \label{tab:reg} \end{table} \section{Introduction} \input{intro.tex} \section{Related Work and Background} \input{related.tex} \section{Methodology} \input{alg.tex} \section{Experiments} \label{sec:exp} \input{exp.tex} \section{Conclusions} \input{con.tex} \bibliographystyle{plainnl} \subsection{Robustness Verification and Relaxations of Neural Networks} Neural network robustness verification algorithms seek for upper and lower bounds of an output neuron for all possible inputs within a set $S$, typically a norm bounded perturbation. Most importantly, the margins of the outputs between the ground-truth class and any other classes determine model robustness. However, it has already been shown that finding the exact output range is a non-convex problem and NP-complete~\citep{katz2017reluplex,weng2018towards}. Therefore, recent works resorted to giving relatively tight but computationally tractable bounds of the output range with necessary relaxations of the original problem. Many of these robustness verification approaches are based on linear relaxations of non-linear units in neural networks, including CROWN~\citep{zhang2018crown}, DeepPoly~\citep{Singh2019robustness}, Fast-Lin~\citep{weng2018towards}, DeepZ~\citep{singh2018fast} and Neurify~\citep{wang2018efficient}. We refer the readers to~\citep{salman2019convex} for a comprehensive survey on this topic. After linear relaxation, they essentially bound the output of a neural network $f(\cdot)$ by linear upper/lower hyperplanes: \begin{equation} \label{eq:linear_relaxation} \A{} \Delta \bm{x} + b_L \leq f(\bm{x}_0 + \Delta \bm{x}) \leq \A{} \Delta \bm{x} + b_U \end{equation} where $\A{} = \W{(L)}\DD{(L-1)}\W{(L-1)}\cdots \DD{(1)}\W{(1)}$ is the product of the network weight matrices $\W{(l)}$ and diagonal matrices $\DD{(l)}$ reflecting the ReLU relaxations; $b_L$ and $b_U$ are two bias terms unrelated to $\Delta x$. Additionally, \citet{dvijotham2018dual,dvijotham18verification,qin2018verification} solve the Lagrangian dual of verification problem; \citet{raghunathan2018certified,raghunathan2018semidefinite} propose semidefinite relaxations which are tighter compared to linear relaxation based methods, but computationally expensive. Bounds on neural network local Lipschitz constant can also be used for verification~\citep{hein2017formal,zhang2018recurjac}. Besides these deterministic verification approaches, random smoothing can be used to increase the robustness of any model in a probabilistic manner~\citep{cohen2019certified,lecuyer2018certified,li2018second,liu2018towards}. \vspace{-0.2cm} \subsection{Robust Optimization and Verifiable Adversarial Defense} To improve the robustness of neural networks against adversarial perturbations, a natural idea is to generate adversarial examples by attacking itself and then use them to augment the training set~\citep{kurakin2016adversarial}. More recently,~\citet{madry2018towards} showed that adversarial training can be formulated as solving a min-max robust optimization problem as in~\eqref{eq:adv_training}. Given a model with parameter $\theta$, loss function $L$, and training data distribution $\mathcal{X}$, the training algorithm aims to minimize the robust loss, which is defined as the max loss within a neighborhood $\{x+\delta|\delta\in S\}$ of each data point $x$, leading to the following robust optimization problem: \begin{equation} \label{eq:adv_training} \min_{\theta} \underset{(x, y) \in \mathcal{X}}{E} \left[ \max_{\delta \in S} L(x + \delta; y; \theta) \right]. \end{equation} To solve this minimax problem,~\citet{madry2018towards} proposed to use projected gradient descent (PGD) attack to approximately solve the inner max and then use the loss on the perturbed example to update the model. Networks trained by this procedure achieve state-of-the-art test accuracy under strong attacks~\citep{athalye2018obfuscated,wang2018mixtrain,zheng2018distributionally}. Despite being robust under strong attacks, models obtained by this PGD-based adversarial training do not have verified error guarantees. Due to the nonconvexity of neural networks, PGD attack can only compute the \emph{lower bound} of robust loss (the inner maximization problem). Minimizing a lower bound of the inner max cannot guarantee~\eqref{eq:adv_training} is minimized. In other words, even if PGD-attack cannot find a perturbation with large verified error, that does not mean there exists no such perturbation. This becomes problematic in safety-critical applications since those models need to be \emph{provably} safe. Verifiable adversarial training methods, on the other hand, aim to obtain a network with good robustness that can be verified. This can be done by combining adversarial training and robustness verification---instead of using PGD to find a lower bound of inner max, certified adversarial training uses a verification method to find an \emph{upper bound} of the inner max, and then update the parameters based on this upper bound of robust loss. Minimizing an upper bound of the inner max guarantees to minimize the robust loss. There are two certified robust training methods that are related to our work and we will describe them in detail below. \subsubsection{Linear Relaxation Based Verifiable Adversarial Training} One of the most popular verifiable adversarial training method was proposed in~\citep{wong2018provable} using linear relaxations of neural networks to give an upper bound of the inner max. Other similar approaches include~\citet{mirman2018differentiable,wang2018mixtrain,dvijotham2018training}. Since the bound propagation process of a convex adversarial polytope is too expensive, several methods were proposed to improve its efficiency, like Cauchy projection~\citep{wong2018scaling} and dynamic mixed training~\citep{wang2018mixtrain}. However, even with these speed-ups, the training process is still slow. Also, this method may significantly reduce the model's standard accuracy (accuracy on natural, unmodified test set). As will be discussed in our experiments in Section~\ref{sec:exp}, we show that this method tends to over-regularize the network during training. Intuitively, regularizing the linear relaxation of the network results in regularizing the $\ell_1$ norm of each row. Since they train the network to make this bound tight, an implicit regularization was added to the $\ell_\infty$ induced norm of weight matrices. \subsubsection{Interval Bound Propagation (IBP)} Interval Bound Propagation (IBP) uses a very simple rule to compute the pre-activation outer bounds for each layer of the neural network. Unlike linear relaxation based methods, IBP does not relax ReLU neurons and does not consider the correlations between different layer weights and treat each layer individually. \citet{gowal2018effectiveness} presented a verifiably robust training method by using IBP to give output bounds. The motivation of~\citep{gowal2018effectiveness} is to speed up the training process of verifiably robust models. However, IBP can be unstable to use in practice, since the bounds can be very loose especially during the initial phase of training, posing a challenging problem to the optimizer. To help with instability, \citet{gowal2018effectiveness} use a mixture of regular and robust cross-entropy loss as the model's training loss, controlled by a parameter $\kappa$; it can be tricky to balance the two losses. Due to the difficulty in parameter tuning, reproducing the results in~\citep{gowal2018effectiveness} is believed to be hard\footnote{\textcolor{blue}{\url{https://github.com/deepmind/interval-bound-propagation/issues/1}}}. Achieving the best CIFAR results reported in~\citep{gowal2018effectiveness} requires training for 3200 epochs with a batch size of 1600 on 32 TPUs.
{'timestamp': '2019-06-17T02:18:14', 'yymm': '1906', 'arxiv_id': '1906.06316', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06316'}
arxiv
\section{Introduction} As a general matter, several authors consider that there is an influence of number of subjects on biometric performance. Jain~\cite{RN1680} has stated: "... that the accuracy estimates of biometric systems are dependent on a number of test conditions, including sensor characteristics, number of subjects in the database,...". No specific examples are cited in this reference however. Similarly, Chan et al.~\cite{RN1682} state "...as the number of subjects increases, it becomes increasingly difficult for the system to accurately classify users." In this case as well, no citations supporting this statement are provided. Jain~\cite{RN1567} discuss numerous approaches to the evalation of biometric performance. Two common approaches that our laboratory employs are the equal error rate (EER) and the rank-1 identification rate. There is evidence that the rank-1 identification rate decreases with increasing numbers of subjects in biometric data sets~\cite{RN64,RN1301}. In the conduct of the present research, although we did not formally study it, we also noted a marked decline in Rank-1 identification rates as a function of the number of subjects in a data set. However, there is little published research on the impact of increasing numbers of subjects on the EER. Although it is well established that increasing the number of subjects will decrease the confidence limits on any ROC curves produced~\cite{RN1645}, this evidence does not imply anything about the central tendency of any estimated error rate. Two earlier papers from out laboratory have addressed the relationship between number of subjects in a database and EER~\cite{RN64,RN1301}. In these studies, biometric authentication was performed using various eye movement features. The goal was to authenticate subjects tested on two occasions. The total sample was either 200~\cite{RN64} or 335 subjects~\cite{RN1301}. For the purpose of evaluating "Database Scaling Performance", the ROC analysis was repeated for randomly drawn subsets of subjects (\textit{N}=50 to 200 or 335). The authors report that "there was no discernable difference in equal error rates produced for a subject pool of 50 or a subject pool of 323". We were interested in in evaluating the influence of changes in numbers of subjects on a much larger scale (\textit{N} = 1,000, 10,000 and 100,000 subjects). For reasons of convenience and availability, we relied in large part on synthetic data sets. However, we were able to replicate our key finding with a real face-recognition data set~\cite{MORPH} In the second section of the manuscript. we present a method for creating synthetic data sets with a number of properties that are helpful for studying biometric performance. Because the data are synthetic, we are able to control the degree of temporal persistence of the features while also ensuring that features are approximately independent of each other and thus provide unique pieces of information for biometric verification. (The concept of "temporal persistence" and the method for its measurement are covered in~\cite{RN1513}. In other contexts, this measure is used to assess the inter-rater reliability of a feature.) We think that having unique pieces of information will allow us to address several theoretical notions relevant to biometric analysis in this and subsequent studies. Also in the second section, we present our methods for biometric assessment. In the third section we present Experiment 1, a study designed to determine the number of features required to get essentially perfect performance (EER <= 0.0001). In the fourth section (Experiment 2), we evaluate the EERs as a function of number of features and temporal persistence of the features. In the fifth section (Experiment 3), we use real data to achieve the same goal as section four. Our discussion is then presented. \section{Creation and Analysis of Synthetic data sets} \label{sec:creation} \subsection{Creation of Synthetic Data} Recall that the intraclass correlation coefficient (ICC) is a measure of the correlation expected for repeated measurements of the same feature on different occasions. Unlike the Pearson r correlation coefficient, which is typically applied as an interclass measure of relative agreement (i.e., two series can be correlated even if they differ substantially in level and spread), the ICC is an intraclass measure of absolute agreement~\cite{RN1513}. Measures from the same set of subjects at two different times are intraclass measurements (same metric and variance). ICC ranges from 0.0 to 1.0 with the latter corresponding to perfect temporal persistence. Our goal is to create synthetic features with a specified target ICC (denoted $ICC_{Target}$). Let $X_{ijm}$ denote the measurement of feature $j$ ($j = 1, \dotsc, k$) on session (occasion) $m$ ($m = 1, \dotsc, s$) for individual $i$ ($i = 1, \dotsc, n$). Although the ICC can be calculated based on many sessions, in our experience, biometric assessment is typically performed comparing only two points in time. Therefore, henceforth we will set $s = 2$. We generate normally distributed features such that the theoretical intraclass correlation of repeated measurements of the same feature on the same subject is $ICC_{Target}$ while the theoretical correlation of measurements of different features on the same individual and the theoretical correlation of measurements from different individuals are zero. In practice when data are simulated there are small variations in the empirical ICCs and there are small intercorrelations between features (and individuals) due to chance. The algorithm that we use is described briefly here and spelled out in Algorithm 1. The starting point is to populate the full set of session one measurements $X_{ij1}$ values with random draws from a standard normal distribution (mean zero and variance one). Then the measurements for the second session are set equal to the value of the given feature from the first session, $X_{ij2} = X_{ij1}$ for ($i = 1, \dotsc, n$). At this point both sessions have the same data and each feature has ICC equal to one (perfect persistence). We obtain the desired ICC by adding a draw from a normal distribution with $\text{mean} = 0$ and $\text{variance} = (1 - ICC_{Target}) / ICC_{Target}$ to each of the measurements. At the end we apply a z-score transform to each feature (with all sessions concatenated together) so that they all have mean 0 and standard deviation one. It can be shown that the resulting measurements have the desired ICC (up to simulation noise). R code to create such synthetic data sets and to assess the resulting ICC is presented publicly available at \href{https://doi.org/10.18738/T8/EVS8AX}{Link to R code and associated output} \begin{algorithm} \SetAlgoLined \caption{\textbf{Algorithm to create synthetic feature sets}} \SetKwInOut{Input}{Input}\SetKwInOut{Output}{Output} \Input{$n$ (subjects), $k$ (features), $ICC_{Target}$} \Output{3-dimensional feature matrix $X_{ijm}$ with desired correlation structure} \begin{enumerate} \item Set $X_{ij1} = Z$ where $Z$ is a random standard normal deviate for $i = 1, \dotsc, n$; $j = 1, \dotsc, k$ \item Set $X_{ij2} = X_{ij1}$ for $i = 1, \dotsc, n$; $j = 1, \dotsc, k$ \item Set $X_{ijm} = X_{ijm} + W$ for $i = 1, \dotsc, n$; $j = 1, \dotsc, k$; $m = 1, 2$; where $W$ is a random \\ normal deviate with mean = 0 and standard deviation = $\sqrt{(1 - ICC_{Target}) / ICC_{Target}}$ \item For each feature $j$, treat $X_{ijm}$ as a single vector of length $n \cdot s$ and apply a z-score \\ transform to ensure mean = 0 and standard deviation = 1 \end{enumerate} \end{algorithm} Using this method, we can create features which are normally distributed, that have specified ICCs, with as many subjects and sessions as we desire. These features all have mean~=~0 and SD~=~1. These features are generally independent, but there are some small intercorrelations between features due to chance. To illustrate the approach, we generated data for 10000~subjects, 1000~features and 2~occasions with $ICC_{Target} = 0.7$. Figure 1(A) shows a histogram of the resulting empirical ICCs. Figure 1(B) shows a histogram of the resulting inter-feature correlations. \begin{figure}[h] \centering \includegraphics[width=0.9\textwidth]{Figures/NewFigures/fig1.pdf} \caption{{(A)~Frequency histogram of ICCs for 1,000~features with an $ICC_{Target} = 0.7$. This is from a synthetic data set with 10,000~subjects. (B)~Frequency histogram of correlations between 1,000~features for 10,000~subjects, two sessions, with an $ICC_{Target} = 0.7$. Note that the median and maximum are of the absolute value of the correlations.}} \label{fig:fig1} \end{figure} \subsection{Creation of Synthetic Sets of Features for (\textbf{Experiment 1})} To study the number of features required to get essentially perfect performance, we generate a synthetic data set with ICCs in the range of 0.8 to 0.9, 500 features, 100,000 subjects and two sessions. \subsection{Creation of Synthetic Sets of Features for (\textbf{Experiment 2})} To study the EERs resulting from a given number of features across multiple ICC Bands, we create 7 different data sets with each data set consisting of 50 features and 100,000 subjects tested twice. The features in each data set have ICC values that vary over a small interval (e.g. 0.6~to~0.7). We denote the data sets as ``Bands'' to indicate that they cover different bands of the range of possible ICCs. Band~3 consists of 50~features simulated to have ICCs between 0.3~and~0.4, Band 4 with ICCs between 0.4 and 0.5 and so on through Band~9 which has ICCs between 0.9~and~1.0. \subsection{Real Face Recognition Data Set (\textbf{Experiment 3})} We would have preferred to find a publicly available data set with 100,000 or more subjects. We were not successful. However, we did find the \textbf{MORPH} Craniofacial Longitudinal Morphological Face Database ~\cite{MORPH} \href{http://www.faceaginggroup.com/morph/}{(Link to \textbf{MORPH} Data Base Description)}. The \textbf{MORPH} data set contains face images for 13,006 subjects. There are at least 2 distinct images per subject, and, in some subjects, many more repeats (up to 53 images of the same person over time). The images are colored (RGB), have various dimensions, include more than just the face, and are not spatially registered. \subsection{Biometric Performance Assessment} The precise details of the biometric assessment are unique for each of the 3 experiments. In general, let's assume that you know in advance which ICC Band data set you want to use, and you know how many features \textit{p} you want to include in the analysis, and you also how many subjects \textit{n} you want to include. If the number of features \textit{P} in the complete data set is greater than the number of features requested \textit{p}, then for each run, a random subset of the features is chosen. If the number of subjects \textit{N} in the complete data set is greater than the number of subjects requested \textit{n}, then for each run, a random subset of the subjects (from each session) is chosen. We employed the cosine distance metric, since we have shown in an earlier report that the best biometric performance is produced with this choice~\cite{RN1675} \href{https://www.doi.org/10.13140/RG.2.2.17510.06727}{(Link to prior report)}. The resulting distance measures were scaled to go from 0~to~1 and then they were reflected ($1 - \text{distance}$) to compute similarity scores. In a typical analysis, a ``genuine'' distribution of similarity scores is constructed from the similarity scores for each subject and his/her self. All other similarity scores are considered impostors. These data are then submitted to a ROC analysis and the EER is computed. Typically, with less than approximately 10,000 subjects, this analysis can be performed in memory. For number of subjects \textit{n}, the number of similarity scores is equal to $n\textsuperscript{2}$. For $n\textsuperscript{5}$ subjects, $n\textsuperscript{10}$ scores are needed. This is too large to run on conventional desktop computers running MATLAB. (On the first author's system, with 16 GB of RAM, the maximum single precision MATLAB array that can be created is 38,000 X 38,000.) To compute similarity scores for 100,000 subjects, special procedures are required. To find the EER, we must find a similarity score threshold where the false acceptance rate (FAR) is equal to the false rejection rate (FRR). Since the difference between FAR and FRR (FAR - FRR) is monotonic, it is appropriate to employ a binary search strategy to find the EER. Similarity scores are computed for a marked subset (e.g., 1000) of all subjects (called a batch), and similarity scores are computed just for a batch at a time. At first, the upper and lower bound similarity thresholds are set to the minimum (0) and maximum (1) possible similarity scores. Then a single threshold - an average between the minimum and maximum, which is 0.5 - is evaluated. For each batch, the number of impostor similarity scores above the threshold is counted as well as the number of genuine similarity scores below or equal to the threshold. These counts are accumulated for each batch through the entire data set, and after each complete pass through the data, the FAR and FRR are calculated. If the FRR is greater than FAR, then on the next iteration, the upper threshold will be set to midpoint between the lower and upper thresholds, and the lower threshold will not change. If the FRR is less or equal to the FAR, then on the next iteration, the lower threshold will be set to midpoint between the lower and upper thresholds, and the upper threshold will not change. This continues until there are only 40 similarity scores between the lower and upper threshold. At this point, iteration through the entire dataset stops and we calculate the values of the difference function (FAR - FRR) for these remaining 40 values. Then intermediate values are linearly interpolated and the threshold level for equal FAR and FRR is chosen as the final threshold, and the error rate (EER) is evaluated at that threshold. As of June 3, 2019, the publicly available Python code that implements this analysis is in preparation and will be available at \href{https://github.com/v-prokopenko/BinSearchEER}{GitHub link to Binary Search Python code} when complete. \section{Experiment 1: Number of Features Required to Obtain Perfect Performance} \subsection{Methods} For this analysis, only Band 8 was employed. This data set consisted of 500 features and 100,000 subjects. The data in Band 8 was processed according to Algorithm 2: \begin{algorithm} \caption{\textbf{Steps to determine the number of features required to achieve various levels of performance (EER)}} \setlength{\leftskip}{0.01cm} \textbf{For N\textunderscore Subjects = [1000;10000;100000]} \setlength{\leftskip}{0.25cm} \textbf{For N\textunderscore Features = 1:100} \setlength{\leftskip}{0.5cm} \textbf{For Repetitions = 1:20} \begin{enumerate} \item Randomly choose N\textunderscore Subjects (for N = 100,000, use all subjects) \item Randomly choose N\textunderscore Features \item Compute EER \end{enumerate} \end{algorithm} These data were processed according to Algorithm 3: \begin{algorithm} \caption{\textbf{Steps in the analysis:}} \textbf{For EER\textunderscore Target = [10.0;5.0;2.5;1.0;0.1;0.01;0.001;0.0001;0.0]:} \setlength{\leftskip}{0.5cm} Find Number of Features which always (over 20 reps) produces EER<=EER\textunderscore Target \end{algorithm} \subsection{Results} The results of this analysis is presented in Figure 2. For EER targets larger than 0.001, approximately the same number of features are required to achieve the target EER across data sets with 1,000, 10,000 and 100,000 subjects. As EER targets decrease from EER <= 0.001 to 0.0, a linear trend appears with more features required to achieve target for 10,000 subjects compared to 1,000 subjects and also for 100,000 subjects compared to 10,000 subjects. \begin{figure}[h] \centering \includegraphics[width=0.9\textwidth]{Figures/NewFigures/NearPerfectAnalysisChart.pdf} \caption{Number of features required to achieve specific EER targets.} \label{fig:fig2} \end{figure} \subsection{Discussion} For most typical cases, with target EERs > 0.01, there is no systematic change in the number of features required. However, as the EER target approaches 0.0, the number of features required increases as the number of subjects in the data sets increase. Note that these effects are extremely unlikely to occur in practice, since few if any real data sets with 10,000 or 100,000 subjects will ever occur with EERs in this extremely small range. \section{Experiment 2: EERs for a Given Number of Features and Data Set Sizes of 1,000, 10,000 and 100,000 Subjects} \subsection{Methods} There are two goals of this experiment. The first is to determine the EER of Band 3 to 8 data sets, all with 10 features, for data set sizes of 1,000 subjects, 10,000 subjects and 100,000 subjects. The second goal is to determine the EER of the Band 9 data set for 7, 8, 9, 10 or 11 features. For this experiment, each of the data sets are created to have 100,000 subjects and 50 features. We will be statistically comparing the mean EER obtained for each band for each target number of features across number of subjects. The first question this analysis presents is: How many EERs to estimate when N= 1,000, 10,000 or 100,000. The steps in this procedure are detailed in algorithm 4, and the resulting number of data sets is presented in Table 1. \begin{algorithm} \caption{\textbf{Determine the number of data sets needed to get stable EER estimates}} \begin{enumerate} \item Compute the standard error for N=100,000, 48 data sets. \item Determine, for N=1,000 and N = 10,000, the number of data sets required to match the standard error for from Step 1. \item Use that number of data sets for all subsequent analyses. \end{enumerate} \end{algorithm} \begin{table} \centering \caption{\textbf{Number of data sets used across Band and number of subjects}} \begin{tabular}{ccccc} \toprule Band Number & Number of Features & 1,000 Subjects & 10,000 Subjects & 100,000 Subjects \\ \midrule 3 & 10 & 106 & 51 & 48 \\ 4 & 10 & 103 & 59 & 48 \\ 5 & 10 & 158 & 68 & 48 \\ 6 & 10 & 83 & 34 & 48 \\ 7 & 10 & 93 & 48 & 48 \\ 8 & 10 & 114 & 55 & 48 \\ 9 & 7 & 61 & 48 & 48 \\ 9 & 8 & 46 & 38 & 48 \\ 9 & 9 & 77 & 45 & 48 \\ 9 & 10 & 64 & 54 & 48 \\ 9 & 11 & 113 & 37 & 48 \\ \bottomrule \end{tabular} \end{table} \subsection{Results} The results for the analysis of Bands 3 to 8, (10 features) are displayed in Figure 3 and Tables 2 and 3. In Figure 3, for each Band, and for 10 features, the EERs across number of subjects looks very stable. This is also evident in the means and SDs presented in Table 2. Statistical results are provided in Table 3. Given that different numbers of data sets were used for each comparison, Welch's t-test, which adjusts for different numbers of observations in each group, was employed. Note that none of the 18 p-values was statistically significant. \begin{figure}[h] \centering \includegraphics[width=0.9\textwidth]{Figures/NewFigures/Bands_3_to_8_NFeat_10_BestFit.pdf} \caption{Relationship between number of subjects and EER for Bands 3 to 8, number of features = 10.} \label{fig:fig3} \end{figure} \begin{table} \centering \caption{\textbf{Means (SDs) for synthetic data - Bands 3 to 8, 10 features}} \begin{tabular}{|cc|cc|cc|cc|} \toprule & Number of &\multicolumn{2}{c|}{N=1,000} & \multicolumn{2}{c|}{N=10,000} & \multicolumn{2}{c|}{N=100,000} \\ \cmidrule(lr){3-4}\cmidrule(lr){5-6}\cmidrule(lr){7-8} Band & Features & Mean EER & SD & Mean EER & SD & Mean EER & SD \\ \midrule 3 & 10 & 28.740 & 0.836 & 28.840 & 0.537 & 28.730 & 0.525 \\ 4 & 10 & 22.880 & 0.795 & 22.980 & 0.545 & 22.870 & 0.505 \\ 5 & 10 & 17.360 & 0.726 & 17.320 & 0.473 & 17.300 & 0.402 \\ 6 & 10 & 11.980 & 0.579 & 12.030 & 0.365 & 12.100 & 0.456 \\ 7 & 10 & 7.100 & 0.526 & 7.210 & 0.426 & 7.270 & 0.424 \\ 8 & 10 & 3.110 & 0.415 & 3.130 & 0.302 & 3.190 & 0.273 \\ \bottomrule \end{tabular} \end{table} \begin{table}[] \centering \caption{\textbf{P-Values for synthetic data - Bands 3 to 8, 10 features}} \begin{tabular}{|c|ccc|ccc|ccc|} \toprule & \multicolumn{3}{c|}{N = 1,000 vs 10,000} & \multicolumn{3}{c|}{N = 1,000 vs 100,000} & \multicolumn{3}{c|}{N = 10,000 vs 100,000} \\ \cmidrule(lr){2-4}\cmidrule(lr){5-7}\cmidrule(lr){8-10} Band & t-value & df & p-value & t-value & df & p-value & t-value & df & p-value \\ \midrule 3 & -0.934 & 142 & 0.352 & 0.05 & 136 & 0.958 & 1.023 & 97 & 0.309 \\ 4 & -0.916 & 155 & 0.361 & 0.10 & 135 & 0.919 & 1.059 & 103 & 0.292 \\ 5 & 0.483 & 189 & 0.629 & 0.67 & 144 & 0.502 & 0.193 & 110 & 0.847 \\ 6 & -0.528 & 95 & 0.598 & -1.34 & 117 & 0.184 & -0.827 & 79 & 0.411 \\ 7 & -1.345 & 114 & 0.181 & -2.03 & 114 & 0.045 & -0.644 & 94 & 0.522 \\ 8 & -0.324 & 141 & 0.746 & -1.43 & 131 & 0.156 & -1.069 & 101 & 0.288 \\ \bottomrule \end{tabular} \end{table} The results for the analysis of Band 9, (7 to 11 features) are displayed in Figure 4 and Tables 4 and 5. Although the changes in EER across subjects look less stable than in Figure 3, note the much lower range of EERs plotted (ordinate). Aside from the data for 7 features, the changes in EER across numbers of subjects appears reasonably stable. The means and SDs are also quite close (Table 4). Statistical results are provided in Table 5. Only 1 p-value, shown in bold, is statistically significant. One of a total of 33 t-tests was statistically significant. With 33 tests, 1.65 comparisons would be statistically significant by chance alone. As a general matter then, these data indicate that EERs do not change across numbers of subjects from 1,000 to 100,000. \begin{figure}[h] \centering \includegraphics[width=0.9\textwidth]{Figures/NewFigures/Band_9_NFeat_7_to_11_BestFit.pdf} \caption{Relationship between number of subjects and EER for Band 9, number of features = 7 to 11} \label{fig:fig4} \end{figure} \begin{table} \centering \caption{\textbf{Means (SDs) for synthetic data, Band 9, 7 to 11 features}} \begin{tabular}{|cc|cc|cc|cc|} \toprule & Number of &\multicolumn{2}{c|}{N=1,000} & \multicolumn{2}{c|}{N=10,000} & \multicolumn{2}{c|}{N=100,000} \\ \cmidrule(lr){3-4}\cmidrule(lr){5-6}\cmidrule(lr){7-8} Band & Features & Mean EER & SD & Mean EER & SD & Mean EER & SD \\ \midrule 9 & 7 & 1.710 & 0.458 & 1.600 & 0.403 & 1.790 & 0.402 \\ 9 & 8 & 1.140 & 0.315 & 1.110 & 0.285 & 1.130 & 0.316 \\ 9 & 9 & 0.720 & 0.250 & 0.730 & 0.177 & 0.800 & 0.182 \\ 9 & 10 & 0.520 & 0.166 & 0.510 & 0.128 & 0.530 & 0.121 \\ 9 & 11 & 0.330 & 0.121 & 0.330 & 0.069 & 0.350 & 0.088 \\ \bottomrule \end{tabular} \end{table} \begin{table} \centering \caption{\textbf{P-Values for synthetic data, Bands 9, 7 to 11 features}} \begin{tabular}{|c|ccc|ccc|ccc|} \toprule Number of & \multicolumn{3}{c|}{N = 1,000 vs 10,000} & \multicolumn{3}{c|}{N = 1,000 vs 100,000} & \multicolumn{3}{c|}{N = 10,000 vs 100,000} \\ \cmidrule(lr){2-4}\cmidrule(lr){5-7}\cmidrule(lr){8-10} Features & t-value & df & p-value & t-value & df & p-value & t-value & df & p-value \\ \midrule 7 & 1.414 & 106 & 0.1602 & -0.915 & 106 & 0.3621 & -2.34 & 94 & \textbf{0.0214} \\ 8 & 0.395 & 81 & 0.6941 & 0.16 & 92 & 0.8735 & -0.238 & 83 & 0.8123 \\ 9 & -0.14 & 115 & 0.8893 & -2.002 & 120 & 0.0476 & -1.934 & 91 & 0.0562 \\ 10 & 0.221 & 115 & 0.8255 & -0.303 & 110 & 0.7622 & -0.575 & 100 & 0.5666 \\ 11 & 0.222 & 110 & 0.8251 & -0.865 & 120 & 0.3889 & -1.077 & 83 & 0.2847 \\ \bottomrule \end{tabular} \end{table} \section{Experiment 3: Analysis with Real Data: Face-Recognition} \subsection{Methods} We wish to note that although we are presenting a face-recognition analysis and we are using a common and reasonable approach, we are doing so in the service of our study of the relationship between numbers of subjects and EER. We are not attempting to develop a state-of-the-art facial recognition analysis with performance competitive with other modern approaches. As noted above, in the \textbf{MORPH} Data Base there are at least 2 distinct images per subject, and, in some subjects, many more repeats. The images are colored (RGB), have various dimensions, include more than just the face, and are not spatially registered. Prior to applying facial recognition analyses to these data, we wanted to transform the original images, for all 13,006 subjects, to 2 grayscale (zscore transformed) images that each have 120 X 100 pixels, with face only (almost). And we wanted these images to be spatially registered. The original database comes in the form of a single directory with 55,134 separate JPG images. They each have file names which include a subject ID code, the repeat number, a gender code and the age of the subject. The steps in the preparation of these raw images into a set of images ready for biometric assessment are provided in Algorithm 5. \begin{algorithm} \caption{\textbf{Steps in the preparation of images for facial recognition}} \begin{enumerate} \item Convert images from color (RGB) to grayscale \item Detect faces in the images using the Viola-Jones algorithm and save the face-only images. \item Z-score transform the images (subtract the mean across all pixels from every pixel and divide by the SD across all pixels.) \item Register the face-only, z-score transformed images using an affine transformation (translation, rotation, scale, and shear). \item Save registered images as 120 X 100 pixels. \item For each subject, correlate each image with each other image \item For each subject, choose the 2 most highly correlated images, and discard all other images. \item Prepare image data for PCA analysis - Take the first image from the first 1,000 subjects and create a file with 1 row and 12,000 columns (120X100 pixels) for each of the images. \item Perform PCA on first 1000 first images and save the PCA coefficients. \item Apply these coefficients to the remaining 12,003 subjects, first and second paired images. \item Drop all but the first 500 PCA components (out of 12,000). \item Normalize the PCA components with a z-score transformation \item Perform biometric assessment \end{enumerate} \end{algorithm} The first 1000 subjects, used to compute the PCA coefficients, were discarded from further analysis. These first 1,000 images can be thought of as a training set. For the remaining 12,003 subjects, biometric assessment proceeded using the first 500 PCA components from the first matched image as session 1 and with the second matched image as session 2. Data subsets were created with a random selection of 1,000 or 10,000 subjects, using either the first 3, 5, 9, 19, or 85 features. Random feature selection was not performed due to the inherent ordered relationship between PCA components. We created 50 subsets for the N=10,000 subsets. The number of subsets created for the N=1,000 subsets was chosen to match the standard error for the N=10,000 subsets. \subsection{Results} The EER results are illustrated in Figure 5 and Tables 6 and 7. It is clear from Figure 5 that there is almost no change in EER for N=1,000 subjects subsets compared to N=10,000 subject subsets. The mean EERs are extremely close (Figure 5 and Table 6). Given this, it is not surprising that none of the t-test comparisions are statistically significant. \begin{figure}[h] \centering \includegraphics[width=0.9\textwidth]{Figures/NewFigures/MORPH_MeansSDsForNFeat_3_5_19_85.pdf} \caption{Relationship between number of subjects and EER for a given number of features - MORPH Data Set} \label{fig:fig5} \end{figure} \begin{table} \centering \caption{Means (SDs) for MORPH Face Database} \begin{tabular}{|c|cccc|cccc|} \toprule Number of & \multicolumn{4}{c|}{N = 1,000 } & \multicolumn{4}{c|}{N = 10,000} \\ Features & Mean EER & SD & SE & N Data Sets & Mean EER 0 & SD 0 & SE 0 & N Data Sets \\ \midrule 3 & 22.85 & 0.656 & 0.0125 & 2737 & 22.85 & 0.088 & 0.0124 & 50 \\ 5 & 16.01 & 0.608 & 0.0117 & 2695 & 16.01 & 0.1 & 0.0141 & 50 \\ 9 & 13.09 & 0.586 & 0.0102 & 3293 & 13.07 & 0.07 & 0.0099 & 50 \\ 19 & 10.03 & 0.505 & 0.0078 & 4188 & 10.04 & 0.056 & 0.0079 & 50 \\ 85 & 5.58 & 0.466 & 0.009 & 2673 & 5.56 & 0.062 & 0.0088 & 50 \\ \bottomrule \end{tabular} \end{table} \begin{table}[] \centering \caption{Statistical results for the MORPH Face Database} \begin{tabular}{|cccc|} \toprule Number of & & & \\ Features & t-value & df & p-value \\ \midrule 3 & -0.224 & 197 & 0.8233 \\ 5 & -0.363 & 139 & 0.7171 \\ 9 & -1.449 & 206 & 0.1489 \\ 19 & 0.388 & 189 & 0.6988 \\ 85 & -1.688 & 203 & 0.093 \\ \bottomrule \end{tabular} \end{table} \section{General Discussion} For EER > 0.01, we have found no evidence that biometric performance, as assessed by the EER, is affected by the number of subjects (N=1,000, 10,000, 100,00). To indicate how small this EER is, we note that the best fingerprint authentication systems have EERs above 2.0~\cite{1542027}. AimBrain, a business enterprise that provides biometric services, recently (2019) proclaimed an EER near 0.03 for their face recognition module \href{https://aimbrain.com/aimface-facial-authentication-record-equal-error-rate-in-nist-analysis/}{AimBrain announcement}. Using both synthetic data and the \textbf(MOPRH) face database, and assuming EER targets > 0.01, we find no evidence for any systematic change in EER as a function of the database size. These observations only apply to the EER, and may well not apply to other measures of performance. For example, evidence indicates that identifications rates do decrease with increasing data set size~\cite{RN64,RN1301}. Our observation regarding EER is consistent with the observations of~\cite{RN64,RN1301}, who studied this issue for from N=50 to N=335 subjects. This evidence suggests that, if one's goal is to estimate the EER of very large data sets (>>1,000), there is no need to collect more than 1,000 subjects. Aside from the theoretical interest of our results, this observation should be of real practical value to the biometric community, when planning biometric modalities at a large scale. However, this stability was violated when the EER target was very close to 0.0 (<0.01). This was only observed in synthetic data. We we were not able to find, nor is there likely to be, a biometric system with more than 1000 subjects that can produce an EER in this near-perfect range. We observed a monotonic increase in the number of features required to achieve near-perfect performance as the number of subjects in the data sets increased from 1,000 to 10,000 to 100,000. We state this observation as a fact, but have no ready explanation for this observation. \section{Acknowledgments} {The study was funded by 3 grants to Dr. Komogortsev: (1)~National Science Foundation, CNS-1250718 and CNS-1714623, www.NSF.gov; (2)~National Institute of Standards and Technology, 60NANB15D325, www.NIST.gov; (3)~National Institute of Standards and Technology, 60NANB16D293. Dr. Stern's contributions were partially funded through Cooperative Agreement \#70NANB15H176 between NIST and Iowa State University, which includes activities carried out at Carnegie Mellon University, University of California Irvine, and University of Virginia.} \bibliographystyle{abbrvnat}
{'timestamp': '2019-06-17T02:16:43', 'yymm': '1906', 'arxiv_id': '1906.06272', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06272'}
arxiv
\section{Introduction} Robots are often equipped with off-the-shelf sensors like cameras which are used for navigation, however, vision is sensitive to extremes in lighting conditions such as shadows or unpredictable changes in intensity as shown in Fig.~\ref{fig:robotic_motivation}. Whilst other on-board sensors like laser range finders can be used in such situations they too are impaired by reflective and absorbing surfaces. Similarly, sensory systems as they occur in nature are subject to impairments, \textit{e.g.,} a rat moving through a maze in ill-lit conditions as illustrated in Fig.~\ref{fig:biological_motivation}. However, through the process of evolution nature has equipped animals to gracefully accommodate such scenarios. Given the coarse vision and challenges of a rodent's natural environment, they are known to rely on tactile feedback derived form whiskers aside from vision to decipher their own location. Considering the example depicted in Fig.~\ref{fig:biological_motivation}, a rat navigates a maze where in certain locations visual or tactile information is ambiguous but combining tactile and visual information can help to discern similar locations. Conventional robots lack such a robust capability to interact with their environment through contact. Thus, biomimetic robots are gaining traction \cite{prescott2009whisking} which has now made it possible to harness visual and tactile sensory modalities for informed decision making. However, it still remains unclear how to best process and combine information from disparate sensory modalities to aid in spatial navigation. \begin{figure}[!htb] \centering \begin{subfigure}[t]{.5\textwidth} \centering \includegraphics[scale=0.25]{light_flash} \caption{Sudden lighting changes.} \label{fig:robotic_motivation} \end{subfigure}% \linebreak \begin{subfigure}[t]{.5\textwidth} \centering \includegraphics[scale=0.25]{maze} \caption{Rat in visually ambiguous maze.} \label{fig:biological_motivation} \end{subfigure} \caption{Multiple sensory modalities can help in situations in which one sensor alone is not sufficient. For example, a sudden flash of sunlight can blind a drone's camera in flight making visual navigation impossible. A rat navigating through a maze sees the same visual scene in multiple locations (marked as $1,2,3$). Corridors and corners in the maze can look the same, especially considering the poor acuity of rodent vision. The blue polygons represent indicative fields of view to highlight this ambiguity. Tactile sensing can help the rat to distinguish ambiguous scenes in these situations.} \label{fig:motivation} \vspace{-0.5cm} \end{figure} Previous works on visuo-tactile sensor fusion like~\cite{alt2014navigation,alt2013haptic} usually combine sensory modalities of varying sensing ranges. The key requirement of these methods was the need to have a redundant field-of-view. Other works in this domain like ~\cite{bhattacharjee2015combining,pinto2016curious,DBLP:journals/ral/CalandraOJLYMAL18} have mainly focused on creating dense haptic object/scene maps. Whilst these methods allow for environmental interactions, they are primarily designed for tactile object exploration and grasping. Although, tactile sensing is increasingly being used in these domains, it remains yet to be applied for performing Simultaneous Localization and Mapping (SLAM). In the context of SLAM, previous works have demonstrated the strengths of a bio-inspired SLAM system and shown its application using single-sensory modalities such as either vision~\cite{ball2013openratslam}, sonar~\cite{steckel2013batslam} or WiFi~\cite{berkvens2014biologically}. However, such methods rely on the uniqueness of the data and are thus susceptible to false-positive place recognition. This problem was previously addressed by fusing information from an array of active sensors each providing rich information~\cite{milford2013brain}. Despite the robustness to illumination changes, this method is not capable of fusing non-unique sensory information. To address the challenges of place recognition in aliased environments using multiple sensors we present our novel method of identifying and preventing false-positive place recognition by combining long-range (unique) vision, with short-range (non-unique) tactile information. Additionally, the proposed method does not rely on sensory redundancy. Our preliminary results presented in \cite{struckmeier2019vita} showed that the method presented herewith is capable of preventing false-positive place recognition from a vision-only SLAM system. Subsequently, a robust sensor fusion algorithm has been developed to integrate information from unique and non-unique sensory modalities such as cameras and whiskers, respectively. Additionally, performance metrics are presented herewith to compare and evaluate model performance against vision or tactile only sensing. \section{Performance metrics} The following metrics were used to evaluate the performance of the proposed ViTa-SLAM against the Visual-SLAM and Tactile-SLAM. \subsubsection{Localization Error Metric (LEM)} The localization error metric (LEM) measures the root mean squared error (RMSE) between the true pose and the estimated pose where the error is calculated separately for position and orientation. Thus, \begin{align} \begin{split} LEM(\cdot) &= \sqrt{\frac{1}{n}\sum_{i=1}^{n}e_i^2} \,,\\ \textrm {where,} \\ e_i &= \hat{(\cdot)} - (\cdot) \end{split} \label{eq:loc_rmse} \end{align} In Eq.~\eqref{eq:loc_rmse}, $\hat{(\cdot)}$ refers to estimated position (orientation) while $(\cdot)$ refers to true position (orientation). \subsubsection{Experience Metric (ExM)} The Experience metric (ExM) introduced in~\cite{salman2016advancing} provides a performance measure for algorithms like RatSLAM that produce semi-metric topological maps with loop closures. The ExM is comprised of the \textit{average rate of re-localization} (ARR) and the \textit{average rate of correct re-localization} (ARCR). The ARR is defined as the ratio of re-localizations to total number of experiences excluding the base set. The \textit{base set} is a set of initial experiences that has to be selected to define the main loop closure and to provide a reference for relocalization with future experiences. The ARCR is defined as the ratio of correct re-localizations to the total number of re-localizations. Higher values (close to $1$) for both factors indicate high certainty in the pose estimate. In order to determine if a re-localization is \textit{correct} or \textit{incorrect}, a threshold is used to compare the accuracy of the estimated pose to the ground truth pose. An experience following an incorrect re-localization is labeled as \textit{invalid} until a correct re-localization occurs. An experience following a correct re-localization is labeled as \textit{valid}. \subsubsection{Energy Metric (EnM)} In \cite{kummerle2009measuring}, energy metric was proposed as a generic metric for evaluation of a variety of SLAM algorithms. The SLAM performance was measured in terms of the energy required to transform the SLAM trajectory to the true trajectory. Let $N$ represent the number of relations between experiences in vita map and their corresponding sample points from the set of collected pose data. Then, $\delta_{i,j} = x_i \ominus x_j$ represents the transformation from node $x_i$ to $x_j$. If $T(\cdot)$ and $R(\cdot)$ represent the translation and rotation operations, then the energy metric (EnM) can be defined as: \begin{equation} EnM = \frac{1}{N} \mathlarger{\mathlarger{\sum}}_{i,j} T(\hat{\delta}_{i,j} \ominus \delta_{i,j})^2 + R(\hat{\delta}_{i,j} \ominus \delta_{i,j})^2 \end{equation} \section{Performance Evaluation} In this section, we compare the performance of \textit{ViTa-SLAM} against Visual and Tactile SLAM approaches using the metrics described above. The experience maps hence obtained are shown in Fig.~\ref{fig:allExpMaps} while the empirical summary of all the metrics is given in Table~\ref{tab:evaluation}.\footnote{Video demonstration available \href{https://www.youtube.com/watch?v=kiJn47GqczA&feature=youtu.be}{here}.} The Energy Metric (EnM) shows that \textit{ViTa-SLAM} requires less energy to transform the trajectory to the ground truth by an order of magnitude. This confirms what can be seen from Fig.~\ref{fig:allExpMaps}, the experience maps of visual and tactile only SLAM are highly skewed as the result of wrong loop closures. To further evaluate the quality of loop closure detection we use the Experience Metric (ExM) with the thresholds for position and angular accuracy set to $0.08$ m and $4.6^\circ$ with the base set defined as the experiences generated during the first full rotation. The ARR and ARCR for \textit{ViTa-SLAM} show that \textit{ViTa-SLAM} is able to re-localize more often and correctly in all cases while the other methods always fail. The reason for this failure becomes evident in Fig.~\ref{fig:ExMa} and \ref{fig:ExMb}. For the visual- and tactile-SLAM methods, false positive re-localizations already occur in the base set as a result of the aliased environment. As opposed to this, \textit{ViTa-SLAM} successfully completes one rotation and correctly closes the loop. The LEM further confirms these findings as the mean pose estimation accuracy of \textit{ViTa-SLAM} is clearly lower than the state-of-the-art methods. \begin{figure*}[!htbp] \centering \begin{subfigure}{.32\textwidth} \centering \includegraphics[scale=0.38]{vision_trajectory} \caption{Visual-SLAM.} \end{subfigure}% \begin{subfigure}{.32\textwidth} \centering \includegraphics[scale=0.38]{tactile_trajectory} \caption{Tactile-SLAM.} \end{subfigure}% \begin{subfigure}{.32\textwidth} \centering \includegraphics[scale=0.38]{vita_trajectory} \caption{ViTa-SLAM.} \end{subfigure} \caption{Experience Map from various approaches.} \label{fig:allExpMaps} \end{figure*} \begin{figure*}[!htbp] \centering \begin{subfigure}{.32\textwidth} \centering \includegraphics[scale=0.38]{vision_ExM} \caption{Visual-SLAM.} \label{fig:ExMa} \end{subfigure}% \begin{subfigure}{.32\textwidth} \centering \includegraphics[scale=0.38]{tactile_ExM} \caption{Tactile-SLAM.} \label{fig:ExMb} \end{subfigure}% \begin{subfigure}{.32\textwidth} \centering \includegraphics[scale=0.38]{vita_ExM} \caption{ViTa-SLAM.} \end{subfigure} \caption{Experience Metric (ExM) for all $3$ SLAM approaches.} \label{fig:ExM} \end{figure*} \begin{table}[!htbp] \caption{Performance Evaluation for RatSLAM, Whisker-RatSLAM, and ViTa-SLAM} \label{tab:evaluation} \centering \resizebox{\columnwidth}{!}{% \begin{tabular}{|c|c|c|c|c|c|} \hline &\textbf{EnM} & \multicolumn{2}{c|}{\textbf{ExM}} & \multicolumn{2}{c|}{\textbf{LEM}} \\ \cline{2-6} \multirow{-2}{*}{\textbf{Method}} & \cellcolor[HTML]{000000} & \textbf{ARR} & \textbf{ARCR} & \textbf{pos (m)} & \textbf{ori (rad)}\\ \hline Visual-SLAM & $4.4024$ &$0.121$ &$0.0$ & $0.9168 \pm 0.6776$ &$1.8872 \pm 8.4155$\\ \hline Tactile-SLAM &$3.8129$ &$0.4643$ &$0.0$ & $1.1739 \pm 1.2901$ &$1.5604 \pm 3.0061$\\ \hline ViTa-SLAM &$0.4311$ &$0.7778$ &$1.0$ & $0.1445\pm0.0474$ &$0.6404 \pm 3.8371$\\ \hline \end{tabular} } \end{table} \section{Experimental Setup} In this section, we describe the operational environment and the robot platform that were used for empirical validation of the proposed ViTa-SLAM algorithm. \subsection{Robot Platform} The robot platform used for this research is called the WhiskEye (Fig.~\ref{fig:real_whiskeye}) the design of which is based on a previous whiskered robot\cite{pearson2013simultaneous}. WhiskEye is composed of a Festo Robotino \textit{body}, a $3$ DoF \textit{neck}, and a $3$D printed \textit{head}. The robot is ROS compatible which allows for candidate control architectures to be developed and deployed on either the physical platform or the Gazebo simulation (shown in Fig.~\ref{fig:sim_whiskeye}) of WhiskEye as used in this study. Mounted on the head are the visual and tactile sensors. Two monocular cameras with a resolution of $640 \times 480$ pixels each provide a stream of RGB images with $5$ frames per second. An array of artificial whiskers consisting of $24$ \textit{macro-vibrissae} whiskers arranged into $4$ rows of $6$ whiskers provides tactile information. Each whisker is equipped with a $2$-axis hall effect sensor to detect $2$D deflections of the whisker shaft measured at its base during, and is actuated using a small BLDC motor to reproduce the active whisking behavior observed in rodents. The tactile data from whiskers is extracted during every whisk cycle, which takes $1$ second to complete. \begin{figure*}[!htbp] \centering \hspace*{-1.3cm} \begin{subfigure}[t]{.32\textwidth} \centering \includegraphics[scale=0.07625]{WhiskEyePhysical} \caption{Physical platform.} \label{fig:real_whiskeye} \end{subfigure}% \hspace*{-0.4cm} \begin{subfigure}[t]{.32\textwidth} \centering \includegraphics[scale=0.1275]{front_side} \caption{Simulated platform.} \label{fig:sim_whiskeye} \end{subfigure} \begin{subfigure}[t]{.32\textwidth} \centering \includegraphics[scale=0.084]{nrp_panel_figure} \caption{Operational environment.} \label{fig:operational_env} \end{subfigure} \caption{WhiskEye robot platform and its operational environment with the trajectory overlaid in magenta.} \label{fig:robot_platform} \end{figure*} \subsection{Operational Environment} As a proof of concept, the algorithm was primarily tested in a simulated aliased environment to test visual-, tactile- and ViTa-SLAM under the challenging conditions a rodent faces in nature including: coarse vision, ill-lit tunnels, ambiguous visual and tactile environments. Fig.~\ref{fig:operational_env} shows the used simulated environment, a $6\times 6$ $m^2$ arena with $4$ wall-mounted visual and $3$ tactile landmarks designed to be qualitatively equivalent to the natural environment. In this setting, the robot was made to revolve around the center of the arena, with a radius of $1$ m whilst facing outwards to the walls. \section{Conclusion and future works} This work demonstrated a novel bio-inspired multi-sensory SLAM mechanism for a robot exploring and interacting with an environment that presents ambiguous cues. While previous attempts had been made to propose bio-inspired multi-sensory fusion, no prior research allowed for either environmental interactions through contact or fusion of unique and non-unique sensory information. To this end, ViTa-SLAM was presented which utilizes long-range visual and short-range whisker (tactile) sensory information for efficient bio-inspired SLAM. When comparing against earlier approaches that use only vision like RatSLAM or only tactile information like the Whisker-RatSLAM, it was shown that visuo-tactile sensor fusion can handle ambiguities that would otherwise lead to false positive loop-closure detection. However, similar to the previous methods, \textit{ViTa-SLAM} depends on hand-crafted features such as intensity profiles, point feature histogram and slope distribution array. Therefore, we plan to improve the generalizability of \textit{ViTa-SLAM} by applying predictive coding to replace the hand-crafted features with learned features. We also plan to improve the robustness and acuity of the whisking behaviour whilst incorporating spatial attention mechanisms as is seen in rats \cite{mitchinson2013whisker}. Additionally, active spatial exploration strategies will be explored to improve the accuracy of localization and speed of mapping. \section{Bio-inspired SLAM} This work draws inspiration from two well-known bio-inspired SLAM frameworks: \textit{RatSLAM,} a rat hippocampal model based visual SLAM architecture \cite{ball2013openratslam}; and \textit{Whisker-RatSLAM,} an extension of RatSLAM aimed primarily at tactile object exploration \cite{salman2018whisker}. This work relies on modified variants of these models referred to as \textit{Visual-SLAM} and \textit{Tactile-SLAM}. In this section these models are summarized and the differences from the works in \cite{ball2013openratslam,salman2018whisker} are shown. Lastly, the proposed \textit{ViTa-SLAM} model is introduced. For each of the models, an overall system architecture is provided using the following convention: nodes represented by right isosceles triangles represent raw sensory data; nodes represented by ellipse(s) represent pre-processing of sensory data before they are converted to input features represented by rounded boxes. The outputs from the models are represented by regular boxes, the pre-processing and feature generation stages are highlighted in light blue and light red blocks, respectively. \subsection{Visual-SLAM} When investigating the way rodents navigate from a bio-inspired perspective, RatSLAM as introduced in \cite{ball2013openratslam,milford2008robot,milford2008mapping,milford2013brain,quigley2009ros}, has been proven to be a capable visual SLAM method. RatSLAM is loosely based on the neural processes underlying navigation in the rodent (primarily rat) brain, more specifically the hippocampus. Fig.~\ref{fig:OpenRatSLAM_Strucutre} shows an overview of the visual-SLAM implementation used in this work. \begin{figure}[!htbp] \centering \resizebox{.5\textwidth}{!}{\input{sections/figures/vanilla_ratslam}} \caption{The overview over the visual-SLAM implementation used in this work.} \label{fig:OpenRatSLAM_Strucutre} \end{figure} During the \textit{preprocessing} phase, the input of a camera (visual data) is downsampled to reduce computational cost and to simulate the coarse vision of rats. In this process the incoming visual data is cropped to remove areas that do not provide unique features, like for example the ground. The cropped image is subsampled and converted to greyscale as shown in Fig.~\ref{fig:view_template}. \begin{figure}[!htbp] \centering \input{sections/figures/lv_flow} \caption{View template pre-processing} \label{fig:view_template} \end{figure} The preprocessed sensory information is now parsed through $3$ major components of the RatSLAM architecture: \begin{itemize} \item Pose Cells \item Local View Cells \item Experience Map \newline \end{itemize} The \textit{pose cells} \cite{ball2013openratslam} encode the robot's current best pose estimate. Pose cells are represented by a \textit{Continuous Attractor Network} (CAN) \cite[Ch.~4]{milford2008robot}, the posecell network, to resemble the \textit{grid cells} as introduced in \cite{hafting2005microstructure}. The grid cells are neurons found in many mammals and are shown to be used in navigation. In the $3$D posecell network, the robot's pose estimate ($x, y$ position and heading angle $\gamma$) is encoded as a energy packet that is moved through energy injection based on odometry and place recognition. The \textit{local view (LV) cells} are an expandable array of units used to store the distinct visual scenes as a \textit{visual template} in the environment using a low resolution subsampled frame of pixels. The visual template generated from the current view is compared to all existing view templates by shifting them relative to each other. If the current view is novel, a local view cell is linked with the centroid of the dominant activity package in the pose cells at the time when a scene is observed. When a scene is seen again, the local view cell injects activity into the pose cells. The \textit{experience map} is a semi-metric topological representation of the robot's path in the environment generated by combining information from the pose cells and local view cells into \textit{experiences}. Each experience is related to the pose cell and local view cell networks via the following 4-tuple: $<x,y,\gamma,V>$ where $x,y,\gamma$ represent the location of the cell in the PC network while $V$ corresponds to the view associated with the LV cell that relates to the queried experience \cite{milford2005experience}. Initially the robot relies on odometry which is subject to an accumulating error. When loop closure events happen, meaning a scene has been seen already, the pose estimate based on the odometry is compared to the pose of the experience and graph relaxation is applied~\cite{milford2005experience}. The following differences to RatSLAM have been introduced in the visual-SLAM implementation: first, we use odometry from the robot instead of visual odometry as was originally done to determine the translational and rotational speeds of the robot. Second, the method of template matching and generation has been modified to account for multiple sensory modalities. Third, the posecell network (PC) is now capable of handling a wider range of robot motion such as moving sideways. \subsection{Tactile-SLAM} Whisker-RatSLAM is a $6$D tactile SLAM algorithm inspired by RatSLAM. Instead of taking input from a camera, it uses a tactile whisker-array mounted on a robot as its only sensor \cite{Pipe2016,pearson2013simultaneous}. The whisker-array consists of $6 \times 4$ whiskers, each capable of measuring the point of whisker contact in $3$D space, and the $2$D deflection force at their base \cite{sullivan2012tactile}. Whisker-RatSLAM \cite{salman2018whisker} has been demonstrated for mapping objects and localizing the whisker array relative to the surface of an object. Similar to RatSLAM, Whisker-RatSLAM generates a semi-metric topological map, the \textit{object exploration map}, which contains complex $6$DOF experience nodes. In \cite{salman2018whisker}, the authors proposed combining these object exploration maps with simple $3$DOF experience map generated using RatSLAM with the whisker-input resulting in a topological terrain exploration map with two different types of experience nodes. Fig. \ref{fig:6dof_ratslam} shows an overview of the Whisker-RatSLAM algorithm. The tactile data acquired by whisking encompasses $3$D contact point cloud of the object ($3$D Cts.) and the deflection data (Defl.). The point cloud is used to generate the \textit{Point Feature Histogram (PFH)} while the deflection data is used to generate \textit{Slope Distribution Array (SDA)}. Both PFH and SDA are then fused to obtain a $6$D Feature Cell (FC). Similar to the RatSLAM experience map, the pose grid cells and FC that were active at a specific 6D pose of the whisker-array are associated with each other and combined into \textit{experience nodes}. The experience in this case is defined as the 7-tuple: $<x,y,z,\alpha,\beta,\gamma,F>$ where $x,y,z,\alpha,\beta,\gamma$ represents the 6D pose including euler angles for orientation and $F \gets \{PFH \cup SDA \}$ represents the features associated with that experience. The experience node form the \textit{object exploration map (Obj. Expl. Map)}. In order to adapt the activation of the pose cell in accord with the robot motion, the odometry information is also used in the pose grid. The tactile-SLAM implementation is based on Whisker-RatSLAM, but instead of a $6$D posecell network this work uses the same $3$D posecell network as the visual-SLAM implementation to allow compatibility and to reduce computation cost for navigation in $3$D space. Furthermore, the tactile-SLAM implementation used in this work does not use feature cells, but instead combines the SDA and PFH data into $3$D tactile template that are used in a similar way as $3$D visual templates. Fig. \ref{fig:6dof_ratslam} shows an overview of the tactile-SLAM algorithm. The tactile data acquired by whisking encompasses $3$D contact point cloud of the object ($3$D Cts.) and the deflection data (Defl.). The point cloud is used to generate the \textit{Point Feature Histogram (PFH)} while the deflection data is used to generate \textit{Slope Distribution Array (SDA)}. Both PFH and SDA are then fused to obtain a tactile template (T). Similar to the RatSLAM experience map, the pose grid cells and T that were active at a specific pose of the whisker-array, are associated with each other and combined into \textit{experience nodes}. The experiences are, opposed to the 7-tuple used in Whisker-RatSLAM, defined as a 4-tuple: $<x,y,\gamma,T>$ and $T \gets \{PFH \cup SDA \}$ represents the tactile template associated with that experience. The experience nodes also form a semi-metric experience map similar to the visual-SLAM method. Similar to the visual-SLAM method, the robot's odometry information is also used to move the pose grid. To generate tactile information using whiskers, one challenge is how to control the whisker-array in order to improve the quality of the sensory information. Previous research on rats \cite{grant2009active} has identified a number of whisking strategies that rodents use to potentially improve the sensory information they obtain. One of these strategies is called \textit{Rapid Cessation of Protraction} (RCP) and refers to the rapid reduction in motor drive applied to the whisker when it makes contact with an object during the protraction phase of exploratory whisking \cite{mitchinson2007feedback}. This effectively reduces the magnitude of bend of the whisker upon contact which in artificial arrays, such as shown in \cite{salman2016advancing}, improves the quality of sensory information by constraining the range of sensory response to a region best suited for signal processing. Furthermore, damage to the whiskers from contact is significantly reduced. \begin{figure}[!htbp] \centering \resizebox{.5\textwidth}{!}{\input{sections/figures/6dof_ratslam}} \caption{The overview over the tactile-SLAM implementation used in this work.} \label{fig:6dof_ratslam} \end{figure} As opposed to full $6$D pose estimation in Whisker-RatSLAM, the modified tactile-SLAM estimates only the $3$D pose ($x,y,\gamma$) to maintain compatibility with the visual-SLAM model. This also helps to reduce the computational overhead of maintaining a $6$D posecell network which is not required for navigation on a mobile robot platform. \subsection{ViTa-SLAM} In this section, we present the details of our novel visuo-tactile SLAM algorithm which we refer to as \textit{ViTa-SLAM}. The overall system architecture for \textit{ViTa-SLAM} is shown in Fig.~\ref{fig:vitaslam_architecture}: $3$ kinds of raw sensory data: tactile, visual, and odometry are now utilized simultaneously. Tactile and visual data are converted into visuo-tactile templates (T, V), respectively and hence, need to be pre-processed. A $3$D pose cell network is maintained. The experience in this approach is now defined as a $5$-tuple: $<x,y,\gamma,V,T>$ where $V$ is a visual template and $T$ is a tactile template at the 3D pose given by $x, y$ and $\gamma$. The experience map in this case will be referred to as \textit{vita map}. In contrast with the conventional experience map, the vita map's nodes contain visual and tactile data. The nodes are termed \textit{sparse} node if the tactile data is empty and \textit{dense} node otherwise. As an example, when the whiskers do not make contact, the whisker tactile information is not providing any information while the camera can still acquire novel scene information. When the whiskers are whisking a wall/landmark, both the camera and whiskers yield features that allow the creation of informative dense nodes which greatly help visuo-tactile SLAM. The properties of a vita-map node (dense or sparse) are stored in the vita-map but not further used. \begin{figure}[!htbp] \centering \resizebox{.5\textwidth}{!}{\input{sections/figures/vita_slam}} \caption{Overview of the \textit{Vita-SLAM} architecture.} \label{fig:vitaslam_architecture} \end{figure} \input{sections/vita-slam} Algorithm \ref{alg:vita-slam} describes \textit{ViTa-SLAM} in more detail. The visual and tactile processes are running continuously in parallel to the \textit{ViTa-SLAM} node, as shown by the $\bm\circlearrowleft$-symbol and store the current visual and tactile templates $V_{cur}$ and $T_{cur}$. The \textbf{visual process} follows the same steps as shown in Fig.~\ref{fig:view_template}. The resulting visual template is called $V_{cur}$. Similarly, the \textbf{Tactile process} is pre-processing the input data consisting of the xy-deflection angles and the whisker contact points in world frame. In line \ref{line:PFH}, the point feature histogram ($PFH$) is generated by creating a $N$-dimensional histogram of the contact points with $B$ bins per dimension. The resulting histogram is then flattened into a $N^B$ histogram. For each whisker, the slope of the xy-deflection between the initial contact to the maximum contact during one whisk cycle\footnote{One whisk cycle is defined as completing one full protraction/retraction cycle.} is computed. The result is the slope distribution array ($SDA$). The current tactile template containing $PFH$ and $SDA$ is saved as $T_{cur}$. The two components can be extracted as $[t]_{PFH}$ and $[t]_{SDA}$. In the \textbf{ViTa-SLAM} process, if a whisk cycle has been completed, the data stored in the visual and tactile processes, $V_{cur}$ and $T_{cur}$, is extracted. In line \ref{line:compare}, $V_{cur}$ and $T_{cur}$ are matched against all old visual and tactile templates and the id with the closest match $m$ and the corresponding error $\epsilon$ are returned. Finally, the error $\epsilon$ is used to determine if a novel template has been detected or a match with an old template has occurred. In either case, energy is injected at the template with match id $m$. After this process, the current visual and tactile templates are appended to the memory and the template match ID is published for experience map generation. The \textbf{template matching} function computes $\epsilon$ by comparing the current template to all visual and tactile templates in the memory. The visual error $V_{err}$ is computed as the pairwise sum of absolute differences between $V_{cur}$ and all visual templates in the memory. For the tactile data similarly, the PFH and SDA are treated separately and the respective errors ($PFH_{err}$ and $SDA_{err}$) are computed. A weighted sum of all obtained error terms yields the error $\epsilon_{cur}$ between the current visuo-tactile templates and the ones in the memory as: \begin{equation} \begin{split} \epsilon_{cur} &= \alpha~|V_{cur}-v|_{L_1} + \beta~|PFH_{cur}-[t]_{PFH}|_{L_1}\\ &+ \gamma~|SDA_{cur}-[t]_{SDA}|_{L_1}\\ \textrm{where,}\\ \alpha &= \frac{1}{\sigma_V}\\ \beta &= \frac{1}{\sigma_{PFH}}\\ \gamma &= \frac{1}{\sigma_{SDA}}\\ \end{split} \label{eq:combinederror} \end{equation} In Eq.~\eqref{eq:combinederror}, $|\cdot|_{L_1}$ represents the L1 norm between the corresponding terms. $\alpha, \beta$ and $\gamma$ are scaling factors for the respective errors which represent the standard deviations of the raw sensory data. Finally, the returned match ID ($m$), is the ID of the combined template with the lowest $\epsilon$.
{'timestamp': '2019-08-16T02:08:29', 'yymm': '1906', 'arxiv_id': '1906.06422', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06422'}
arxiv
\section{Introduction}\label{sec:intro} Quantifying the importances of nodes through the calculation of `centrality' measures is a central topic in the study of networks \cite{newman2010}. It is important in numerous and diverse applications, including identification of influential people \cite{bonacich1972,faust1997centrality,borgatti1998network,kempe2003}, ranking web pages in searches \cite{Brin1998conf,pagerank,kleinberg1999}, ranking teams and individual athletes in sports \cite{monthly,saavedra2010,chartier2013}, identification of critical infrastructures that are susceptible to congestion or failure \cite{holme2003congestion,guimera2005worldwide}, quantifying impactful judicial documents \cite{leicht-citation2007,fowler2007b,fowler2008} and scientific publications \cite{bergstrom2008eigenfactor}, revealing drug targets in biological systems \cite{jeong2001lethality}, and much more. Because most networks change in time \cite{holme2012temporal,holme2013,holme2015}, there is much interest in extending centralities to temporal networks \cite{liao2017ranking}. Past efforts have generalized quantities such as betweenness centrality \cite{tang2010,kim2012b,williams2015,alsayed2015,fenu2015}, closeness centrality \cite{tang2010,pan2011,kim2012b,williams2015}, Bonacich and Katz centrality \cite{lerman2010centrality,Grindrod_Higham_2014}, win/lose centrality \cite{motegi2012}, communicability \cite{grindrod2011communicability,estrada2013,Grindrod_Higham_2013,fenu2015,chen2016dynamic,arrigo2017sparse}, dynamic sensitivity \cite{huang2017dynamic}, coverage centrality \cite{taro2015}, PageRank \cite{walker2007ranking,Mariani2016,you2015distributed,rossi2012,mariani2015}, and eigenvector centrality \cite{praprotnik2015spectral,huang2017centrality,flores2018eigenvector}. {A common feature of these extensions is that they illustrate the importance of using methods that are designed explicitly for temporal networks, as opposed to various alternatives: aggregating the temporal network into a single `time-independent' network; independently analyzing the network at different instances in time; or binning the network into time windows and analyzing those independently. In the first case, it is not even possible to study centrality trajectories (i.e., how centrality changes over time).} Because one can derive many centralities by studying walks on a network, some of the above temporal generalizations of centrality involve the analysis of so-called `time-respecting paths' \cite{kossinets2008structure,kostakos2009temporal}. There are multiple ways to define a time-respecting path, including the possibility of allowing multiple edge traversals per time step for a discrete-time temporal network. There are also multiple ways to quantify the length of a time-respecting path \cite{williams2015}, because such a path can describe the number of edges that are traversed by the path, latency between the initial and terminal times of a path, or a combination of these ideas. In particular, it is necessary to make choices even to define a notion of a `shortest path' (from which one can formulate several types of centrality). Consequently, some of the diversity in the various temporal generalizations of centrality measures arises from the diversity in defining and measuring the length of a time-respecting path. In the present work, we examine a notion \emph{supracentrality} \cite{taylor2017eigenvector,taylor2019tunable}, which one can calculate by representing a temporal network as a sequence of network layers and coupling those layers to form a multilayer network (specifically, a multiplex network \cite{kivela2014,whatis2018}). See Fig.~\ref{fig:toy1} for illustrative examples. The sequence of network layers, which constitute \emph{time layers}, can represent a discrete-time temporal network at different time instances or a continuous-time network in which one bins (i.e., aggregates \cite{taylor2017super}) the network's edges to form a sequence of time windows with interactions in each window. This approach is motivated by the use of multiplex-network modeling to detect communities in temporal networks through maximization of multilayer modularity \cite{muchaporter2010,bassett2013,weir2017post,roxana2019}. We note in passing that there is also widespread interest in generalizing centrality measures to multilayer networks more generally \cite{magnani2011ml,de2013b,battiston2014structural,tavassoli2016most,magnani2013combinatorial,sole2014centrality,chakraborty2016cross,sole2016random,spatocco2018new,rahmede2017centralities,tudisco2018node,sola2013eigenvector,deford2017new,deford2017multiplex,ng2011multirank,Halu_Mondragon_Panzarasa_Bianconi_2013,ding2018centrality}. \begin{figure}[t] \centering{ \includegraphics[width=.9\linewidth]{tempo_toy.pdf}} \vspace{-.2cm} \caption{{\bf Multiplex-network representations of a discrete-time temporal network.} Given a temporal network with $N=4$ nodes and $T=6$ times, we represent the network at each time by a `time layer' with adjacency matrix ${\bf A}^{(t)} \in\mathbb{R}^{N\times N}$ for $t\in\{1,\dots,T\}$. (A,B) We represent the network as a multiplex network by coupling the layers with `interlayer edges' (gray edges) that we encode in an interlayer-adjacency matrix $\tilde{\bm{A}} \in\mathbb{R}^{T\times T}$. Panel (A) illustrates interlayer coupling in the form of an undirected chain, and panel (B) depicts directed coupling between layers. In panels (C) and (D), we show visualizations of the networks that are associated with $\tilde{\bm{A}}$ for panels (A) and (B), respectively. In panel (D), there are directed interlayer edges between consecutive time layers, so these interlayer edges respect the direction of time. Additionally, we construct connections of weight $\gamma>0$ between corresponding nodes from all pairs of layers to ensure that $\tilde{\bm{A}}$ corresponds to a strongly connected network, which in turn ensures that the centralities are positive and unique. By analogy to `node teleportation' in PageRank \cite{gleich2014}, we refer to this coupling as `layer teleportation'. } \label{fig:toy1} \end{figure} {Our supracentrality framework generalizes a family of centralities for time-independent networks called \emph{eigenvector-based} centralities, which are defined by the property of calculating centralities as the entries of an eigenvector (the so-called `dominant' eigenvector) that corresponds to the largest-magnitude eigenvalue (the `dominant' eigenvalue) of a \emph{centrality matrix} ${C}(\mathbf{A})$, which one defines by some function of a network adjacency matrix $\mathbf{A}$. Different choices for the centrality matrix recover some of the most popular centrality measures, including eigenvector centrality (by using ${C}(\mathbf{A}) = \mathbf{A}$) \cite{bonacich1972}, hub and authority scores (by using ${C}(\mathbf{A}) = \mathbf{A}\mathbf{A}^T$ for hubs and $\mathbf{A}^T\mathbf{A}$ for authorities) \cite{kleinberg1999}, and PageRank \cite{pagerank} (see Sec.~\ref{sec:eig_central}).} Given a discrete-time temporal network in the form of a sequence of adjacency matrices ${\bf A}^{(t)} \in\mathbb{R}^{N\times N}$ for $t\in\{1,\dots,T\}$, where $A_{ij}^{(t)}$ denotes a directed edge from entity $i$ to entity $j$ in time layer $t$, examining supracentralities involves two steps: \begin{enumerate} \item Construct a {supracentrality matrix} $\mathbb{C}(\omega)$, which couples centrality matrices ${C}({\bf A}^{(t)})$ of the individual time layers $t=1$, $t = 2$, $t = 3$, \ldots \item Compute and interpret the dominant eigenvector of $\mathbb{C}(\omega)$. \end{enumerate} For a temporal network with $N$ nodes and $T$ time layers, $\mathbb{C}(\omega)$ is a square matrix of size $NT\times NT$. We require the set of nodes to be the same for all time layers. However, it is easy to accommodate the appearance and disappearance of nodes by including extra instances of the entities in layers in which they otherwise do not appear (but without including any associated intralayer edges). The parameter $\omega$ scales the weights of the interlayer coupling to control the strength of the connection between time layers. It thus provides a `tuning knob' to control how rapidly centrality trajectories can change over time. An important aspect of the first step is that one must choose a topology to couple layers to each other. To do this, we define an interlayer-adjacency matrix $\tilde{\bm{A}} \in\mathbb{R}^{T\times T}$, where the entry $\tilde{{A}}_{tt'}$ encodes the coupling from time layer $t$ to time layer $t'$. In Fig.~\ref{fig:toy1}, we illustrate two possible choices for coupling the time layers. In the upper row, $\tilde{\bm{A}} \in\mathbb{R}^{T\times T}$ encodes an undirected chain, which couples the time layers with \emph{adjacent-in-time} coupling but neglects the directionality of time. In the lower row, by contrast, we couple the time layers by a directed chain that reflects the directionality of time. In addition to the directed, time-respecting edges, Fig.~\ref{fig:toy1} also illustrates that we include weighted, undirected edges between corresponding nodes in all pairs of layers. This implements `layer teleportation', which is akin to the well-known `node teleportation' of the PageRank algorithm \cite{gleich2014}. Similar to the motivation for node teleportation, layer teleportation ensures that supracentralities are well-behaved (specifically, that they are positive and unique). The second step of our supracentrality framework involves studying the dominant right eigenvector of the supracentrality matrix $\mathbb{C}(\omega)$, which characterizes the \emph{joint centrality} of each node-layer pair $(i,t)$---that is, the centrality of node $i$ in time layer $t$---and thus reflects the importances of both node $i$ and layer $t$. From the joint centralities, one can calculate \emph{marginal centralities} for only the nodes (or only the time layers). One can also calculate \emph{conditional centralities} that measure a node's centrality at time $t$ relative only to the other nodes' centralities in that particular time layer $t$. These concepts, which are inspired by ideas from probability theory, allow one to develop a rich characterization for how node centralities change over time. In this chapter, we describe the supracentrality framework that we developed in \cite{taylor2017eigenvector,taylor2019tunable} and extend these papers with further numerical explorations of how interlayer coupling topology affects supracentralities. We apply this approach to a data set, which we studied in \cite{taylor2017eigenvector} and is available at \cite{MGP_data}, that encodes the graduation and hiring of Ph.D. recipients between mathematical-sciences doctoral programs in the United States. We focus our attention on five top universities and examine how they are affected by the value of $\omega$ and the choice of $\tilde{\bm{A}}$. Specifically, we compare the two strategies for interlayer coupling in Fig.~\ref{fig:toy1}, and we explore the effect of reversing the directions of all directed edges. Our experiments reveal how to use $\omega$ and $\tilde{\bm{A}}$ to tune the extent to which centrality trajectories of nodes are influenced by the oldest time layers, the newest time layers, and the direction of time. \section{Background Information}\label{sec:back} Our supracentrality framework involves representing a temporal network as a multiplex network (see Sec.~\ref{sec:mux}). In Sec.~\ref{sec:eig_central}, we review eigenvector-based centrality measures. \subsection{Analysis of Temporal Networks with Multiplex-Network Representations}\label{sec:mux} We study discrete-time temporal networks, for which we provide a formal definition. \begin{definition}[Discrete-Time Temporal Network]\label{def:time} A \emph{discrete-time temporal network} consists of nodes $\mathcal{V}=\{1,\dots,N\}$ and sets $\mathcal{E}^{(t)}$ of weighted edges that we index (using $t$) in a sequence of network layers. We denote such a network either as $\mathcal{G}(\mathcal{V},\{\mathcal{E}^{(t)}\})$ or by the sequence $\{\mathbf{A}^{(t)}\}$ of adjacency matrices, where ${A}_{ij}^{(t)}=w^t_{ij}$ if $(i,j,w^t_{ij})\in\mathcal{E}^{(t)}$ and $ {A}_{ij}^{(t)}=0$ otherwise. \end{definition} As we illustrated in Fig.~\ref{fig:toy1}, we represent a discrete-time temporal network as a multiplex network with weighted and possibly directed coupling between the time layers. We restrict our attention to the following type of multiplex network. \begin{definition}[Uniformly and Diagonally-Coupled (i.e., Layer-Coupled) Multiplex Network]\label{def:mux} Let $\mathcal{G}(\mathcal{V},\{\mathcal{E}^{(t)}\},\tilde{\mathcal{E}})$ be a $T$-layer multilayer network with node set $\mathcal{V}=\{1,\dots,N\}$ and interactions between node-layer pairs that are encoded by the sets $\{\mathcal{E}^{(t)}\}$ of weighted edges, where $(i,j,w^t_{ij})\in\mathcal{E}^{(t)}$ if and only if there is an edge $(i,j)$ with weight $w^t_{ij}$ in layer $t$. The set $\tilde{\mathcal{E}}=\{(s,t,\tilde{w}_{st})\}$ encodes the topology and weights for coupling separate instantiations of the same node between a pair of layers, $(s,t)\in\{1,\dots, T\}\times \{1,\dots, T\}$. Equivalently, one can encode a multiplex network as a set $\{\mathbf{A}^{(t)}\}$ of adjacency matrices, such that $ {A}_{ij}^{(t)}=w^t_{ij}$ if $(i,j,w^t_{ij})\in\mathcal{E}^{(t)}$ and $ {A}_{ij}^{(t)}=0$ otherwise, along with an interlayer-adjacency matrix $\tilde{\bm{A}}$ with components $\tilde{A}_{st} = \tilde{w}_{st}$ if $(s,t,\tilde{w}_{st}) \in \tilde{\mathcal{E}}$ and $\tilde{A}_{st}^{(t)}=0$ otherwise. \end{definition} The coupling in Definition \ref{def:mux} is `diagonal' in that the only interlayer edges are ones that couple a node in one layer with that same node in another layer. It is `uniform' in that the coupling between two layers is identical for all nodes in those two layers. A multilayer network with both conditions is called `layer-coupled' \cite{kivela2014}. As we illustrate in Fig.~\ref{fig:toy1}, we focus our attention on two choices for coupling time layers: (A) $\tilde{\bm{A}}$ encodes an undirected chain: \begin{equation}\label{eq:undir} \tilde{A}_{tt'} = \left\{\begin{array}{rl} 1\,,& \, |t'-t|= 1\,, \\ 0 \,,& \, \text{otherwise} \,; \\ \end{array} \right. \end{equation} (B) $\tilde{\bm{A}}$ encodes a directed chain with layer teleportation: \begin{equation}\label{eq:tele} \tilde{A}_{tt'} = \left\{\begin{array}{rl} 1+\gamma\,,& \, t'-t= 1\,, \\ \gamma \,,& \, \text{otherwise} \,, \\ \end{array} \right. \end{equation} where $\gamma>0$ is the \emph{layer-teleportation probability}. In Sec.~\ref{sec:data}, we compare the effects on centrality trajectories of these two choices for $\tilde{\bm{A}}$. \subsection{Eigenvector-Based Centrality for Time-Independent Networks}\label{sec:eig_central} Arguably the most notable---and certainly the most profitable---type of centrality is PageRank, which provided the mathematical foundation for the birth of the web-search algorithm of the technology giant Google \cite{Brin1998conf,pagerank,gleich2014}. PageRank quantifies the importances of nodes in a network (e.g., a directed network that encodes hyperlinks between web pages) by computing the dominant eigenvector of the `PageRank matrix' (or `Google matrix' \cite{langville2006}) \begin{align} \label{eq:google} \mathbf{C}^{(PR)} &= {\sigma} \mathbf{A}^T\mathbf{D}^{-1} + (1-{\sigma})N^{-1}\mathbf{1}\mathbf{1}^T\,, \end{align} where $N$ is the number of nodes, $\mathbf{1}=[1,\dots,1]^T$ is a length-$N$ vector of $1$ entries, and $\mathbf{A}$ is an adjacency matrix in which each entry $A_{ij}$ encodes a directed (and possibly weighted) edge from node $i$ to node $j$. The matrix $\mathbf{D}=\text{diag}[d_1^{\mathrm{out}},\dots,d_N^{\mathrm{out}}]$ is a diagonal matrix that encodes the node out-degrees $d_i^{\mathrm{out}} = \sum_j A_{ij}$. The PageRank matrix's dominant right eigenvector is a natural choice for ranking nodes, as it encodes a random walk's stationary distribution (which estimates the fraction of web surfers on each web page in the context of a web-search engine\footnote{ PageRank has had intellectual impact well beyond web searches \cite{gleich2014}.}). The term $\mathbf{A}^T\mathbf{D}^{-1}$ is a transition matrix that operates on column vectors that encode the densities of random walkers \cite{masuda2017}. The term $N^{-1}\mathbf{1}\mathbf{1}^T$ is a \emph{teleportation matrix}; it represents a transition matrix in a network with uniform all-to-all coupling between nodes. The \emph{teleportation parameter} $\sigma\in(0,1)$ implements a linear superposition of the two transition matrices and yields an irreducible matrix, even when the transition matrix $\mathbf{A}^T\mathbf{D}^{-1}$ is reducible. Because we introduced the concept of layer teleportation in Sec.~\ref{sec:mux}, we henceforth refer to the traditional teleportation in PageRank as `node teleportation'. It is common to define the PageRank matrix as the transpose of Eq.~\eqref{eq:google}; in that case, one computes the dominant left eigenvector instead of the dominant right one. However, we use the right-eigenvector convention to be consistent with a broader class of centrality measures called {eigenvector-based centralities}, in which one encodes node importances in the elements of the dominant eigenvector of some {centrality matrix}. In addition to PageRank, prominent examples of eigenvector-based centralities include (vanilla) eigenvector centrality \cite{bonacich1972} and hub and authority (i.e., HITS) centralities \cite{kleinberg1999}. We provide formal definitions below. { % \begin{definition}[Eigenvector-Based Centrality] \label{def:EigenBased} Let $\mathbf{C}=C(\mathbf{A})$ be a centrality matrix, which we obtain from some function $C:\mathbb{R}^{N\times N}\mapsto \mathbb{R}^{N\times N}$ of the adjacency matrix $\mathbf{A}$, of a network $\mathcal{G}(\mathcal{V},\mathcal{E})$. Consider the dominant right eigenvector $\mathbf{u}$, which satisfies \begin{equation}\label{eq:eigen_1} \mathbf{C} \mathbf{u} = \lambda_{\rm{max}} \mathbf{u} \,, \end{equation} where $\lambda_{\rm{max}} \in\mathbb{R}_{+}$ is the largest eigenvalue of $\mathbf{C}$. (Note that this eigenvalue is guaranteed to be positive.) The $i$th entry $u_i$ specifies the \emph{eigenvector-based centrality} of node $i\in\mathcal{V}$ that is associated with the function $C$. \end{definition} \begin{definition}[PageRank \cite{pagerank,gleich2014}]\label{def:PageRank} When $\mathbf{C}$ is given by Eq.~\eqref{eq:google}, we say that Eq.~\eqref{eq:eigen_1} yields \emph{PageRank} centralities $\{u_i^{(\mathrm{PR})}\}$. \end{definition} \begin{remark} It is also common to compute PageRank centralities from a left eigenvector \cite{gleich2014}. In the present paper, we use a right-eigenvector formulation to be consistent with the other eigenvector-based centralities. One can recover the other formulation by taking the transpose of Eq.~\eqref{eq:eigen_1}. \end{remark} } \section{Supracentrality Framework}\label{sec:method} We now describe the supracentrality framework that we presented in \cite{taylor2019tunable}. This formulation generalizes our formulation of supracentrality from \cite{taylor2017eigenvector}, which required that interlayer coupling take the form of an undirected chain. (See the top row of Fig.~\ref{fig:toy1}.) To aid our presentation, we summarize our mathematical notation in Table~\ref{table:notation}. \begin{table}[h] \caption{Summary of our mathematical notation for objects with different dimensions.} {\centering \begin{tabular}{c c c} \hline Typeface & Class & Dimensionality \\ [0.5ex] \svhline $\mathbb{M}$ & matrix & $NT\times NT$ \\ $\mathbf{M}$ & matrix & $N\times N$ \\ $\bm{M}$ & matrix & $T\times T$ \\ $\mathbbm{v}$ & vector & $NT\times 1$ \\ $\mathbf{v}$ & vector & $N\times 1$ \\ $\bm{v}$ & vector & $T\times 1$ \\ $M_{ij}$ & scalar & 1 \\ $v_i$ & scalar & 1 \\ [1ex] \hline \end{tabular}\\ \label{table:notation}} \end{table} \subsection{Supracentrality Matrices}\label{sec:supra} We first describe a supracentrality matrix from \cite{taylor2019tunable}. \begin{definition}[Supracentrality Matrix]\label{def:Supracentrality} Let $\{{\bf C}^{(t)}\}$ be a set of $T$ centrality matrices for a discrete-time temporal network with a common set $\mathcal{V}=\{1,\dots,N\}$ of nodes; and assume that ${C}^{(t)}_{ij} \ge 0 $. Let $\tilde{\bm{A}}$, with entries $\tilde{A}_{ij}\ge 0$, be a $T\times T$ interlayer-adjacency matrix that encodes the interlayer couplings. We define a family of \emph{supracentrality matrices} $\mathbb{C}(\omega)$, which are parameterized by the interlayer-coupling strength $\omega \ge 0$, of the form \begin{align} {\mathbb{C}} (\omega) &= \hat{\mathbb{C}} + \omega \hat{\mathbb{A}}\, = \left[ \begin{array}{cccc} \mathbf{C}^{(1)} & {\bf 0} & {\bf 0}&\dots\\ {\bf 0} & \mathbf{C}^{(2)} & {\bf 0}& \dots\\ {\bf 0} & {\bf 0} & \mathbf{C}^{(3)} &\ddots\\ \vdots& \vdots & \ddots&\ddots\\ \end{array} \right] + \omega \left[ \begin{array}{cccc} \tilde{A}_{11} \mathbf{I}~& \tilde{A}_{12} \mathbf{I} ~& \tilde{A}_{13} \mathbf{I} &\dots \\ \tilde{A}_{21} \mathbf{I} ~& \tilde{A}_{22} \mathbf{I} ~& \tilde{A}_{23} \mathbf{I}& \dots \\ \tilde{A}_{31} \mathbf{I} ~& \tilde{A}_{32} \mathbf{I} ~& \tilde{A}_{33} \mathbf{I} ~&\dots\\ \vdots & \vdots&\vdots&\ddots\\\\ \end{array} \right] \, , \label{eq:supracentrality} \end{align} where $\hat{\mathbb{C}} = \text{\rm diag}[ \mathbf{C}^{(1)},\dots, \mathbf{C}^{(T)}]$ and $\hat{\mathbb{A}}=\tilde{\bm{A}}\otimes \bf{I}$ is the Kronecker product of $\tilde{\bm{A}}$ and $\bf{I}$. \end{definition} For layer $t$, the matrix ${\bf C}^{(t)}$ can represent any matrix whose dominant eigenvector is of interest. In our discussion, we focus on PageRank {(see Definition \ref{def:PageRank}), but one can alternatively choose eigenvector centrality \cite{bonacich1972}, hub and authority centralities \cite{kleinberg1999}, or something else.} The $NT\times NT$ supracentrality matrix $\mathbb{C}(\omega) $ encodes the effects of two distinct types of connections: the layer-specific centrality entries $\{ {C}^{(t)}_{ij}\}$ in the diagonal blocks relate centralities between nodes in layer $t$; and entries in the off-diagonal blocks encode coupling between layers. The form $\hat{\mathbb{A}}=\tilde{\bm{A}}\otimes \bf{I}$ implements uniform and diagonal coupling. The matrix $\bf{I}$ encodes diagonal coupling; and any two layers $t$ and $t'$ are uniformly coupled, because all interlayer edges between them have the identical weight $\omega\tilde{A}_{tt'}$. \subsection{Joint, Marginal, and Conditional Centralities}\label{sec:joint} As we indicated earlier, we study the dominant right eigenvalue equation for the supracentrality matrix. That is, we solve the eigenvalue equation \begin{equation} \label{eq:eig_eq} \mathbb{{C}}(\omega)\mathbbm{v}(\omega) = \lambda_{\rm{max}}(\omega)\mathbbm{v}(\omega)\,, \end{equation} and we interpret entries in the dominant right eigenvector $\mathbbm{v}(\omega)$ as scores that measure the importances of node-layer pairs $\{(i,t)\}$. Because the vector $\mathbbm{v}(\omega)$ has a block form---its first $N$ entries encode the joint centralities for layer $t=1$, its next $N$ entries encode the joint centralities for layer $t=2$, and so on---it is useful to reshape $\mathbbm{v}(\omega)$ into a matrix. \begin{definition}[Joint Centrality of a Node-Layer Pair \cite{taylor2017eigenvector}]\label{def:joint} Let $\mathbb{C}(\omega)$ be a supracentrality matrix given by Definition~\ref{def:Supracentrality}, and let $\mathbbm{v}(\omega)$ be its dominant right eigenvector. We encode the \emph{joint centrality} of node $i$ in layer $t$ via the $N\times T$ matrix ${\bf W}(\omega)$ with entries \begin{equation} W_{it}(\omega) = \mathbbm{v}_{N(t-1) + i}(\omega)\, . \label{eq:joint2} \end{equation} We refer to $W_{it}(\omega)$ as a `joint centrality' because it reflects the importance both of node $i$ and of layer $t$. \end{definition} \begin{definition}[Marginal Centralities of Nodes and Layers \cite{taylor2017eigenvector}]\label{def:marg} Let ${\bf W}(\omega) $ encode the joint centralities given by Definition \ref{def:joint}. We define the \emph{marginal layer centrality} (MLC) and \emph{marginal node centrality} (MNC), respectively, by \begin{align} {x}_{t}(\omega) &= \sum_{i}W_{it}(\omega)\,,\nonumber\\ \hat{x}_{i}(\omega) &= \sum_{t} W_{it}(\omega) \, . \label{eq:marg2} \end{align} \end{definition} \begin{definition}[Conditional Centralities of Nodes and Layers \cite{taylor2017eigenvector}]\label{def:cond} Let $\{W_{it}(\omega)\}$ be the joint centralities given by Definition \ref{def:joint}, and let $\{{x}_{t}(\omega) \}$ and $\{\hat{x}_{t}(\omega) \}$, respectively, be the marginal node and layer centralities given by Definition \ref{def:marg}. We define the \emph{conditional centralities} of nodes and layers by \begin{align} Z_{it} (\omega)&= W_{it}(\omega)/ {x}_t(\omega)\,, \nonumber\\ \hat{Z}_{it}(\omega) &= W_{it}(\omega)/\hat{x}_i(\omega)\,, \label{eq:cond} \end{align} where $Z_{it} (\omega)$ gives the centrality of node $i$ conditioned on layer $t$ and $\hat{Z}_{it} (\omega)$ gives the centrality of layer $t$ conditioned on node $i$. The quantity $Z_{it}(\omega)$ indicates the importance of node $i$ relative just to the other nodes in layer $t$. \end{definition} We ensure that the supracentralities are well-defined (i.e., unique, positive, and finite) by the following theorem. \begin{theorem}[Uniqueness and Positivity of Supracentralities \cite{taylor2019tunable}] \label{thm:unique} Let $\mathbb{C}(\omega)$ be a supracentrality matrix given by Eq.~\eqref{eq:supracentrality}. Additionally, suppose that $\tilde{\bm{A}}$ is an adjacency matrix for a strongly connected graph and that $\sum_t \mathbf{C}^{(t)}$ is an irreducible, nonnegative matrix. It then follows that $\mathbb{C}(\omega)$ is irreducible, nonnegative, and has a simple largest positive eigenvalue $\lambda_{\rm{max}}(\omega)$, with corresponding left eigenvector $\mathbbm{u}(\omega)$ and right eigenvector $\mathbbm{v}(\omega)$ that are each unique and positive. The centralities $\{W_{it}(\omega)\}$, $\{x_i(\omega)\}$, $\{\hat{x}_t(\omega)\}$, $ \{Z_{it}(\omega)\}$, and $ \{\hat{Z}_{it}(\omega)\}$ are then positive and finite. If we also assume that $\mathbb{C}(\omega)$ is aperiodic, it follows that $\lambda_{\rm{max}}(\omega)$ is a unique dominant eigenvalue. \end{theorem} In Fig.~\ref{fig:centralities_toy1}, we show the joint and marginal centralities for the network in the top row of Fig.~\ref{fig:toy1}. We have normalized the vector $\mathbbm{v}(\omega)$ in 1-norm. \begin{figure}[h] \centering \includegraphics[width=.5\linewidth]{peda_1a.pdf} \caption{Joint centralities $\{W_{it}(\omega)\}$ of Definition~\ref{def:joint} (white cells), with corresponding marginal layer centralities (MLC) $\{{x}_{t}(\omega)\}$ and marginal node centralities (MNC) $\{\hat{x}_{i}(\omega)\}$ of Definition~\ref{def:marg} (gray cells) for the network in the top row of Fig.~\ref{fig:toy1} with $\omega=1$. The centrality matrices of the layers are PageRank centrality matrices (see Eq.~\eqref{eq:google}) with a node-teleportation parameter of $\sigma=0.85$. } \label{fig:centralities_toy1} \end{figure} \section{Application to a Ph.D. Exchange Network}\label{sec:data} We apply our supracentrality framework to study centrality trajectories for a temporal network that encodes the graduation and hiring of mathematicians between $N=231$ mathematical-sciences doctoral programs in the United States during the period $\{1946,\dots, 2010\}$ \cite{taylor2017eigenvector}. Each edge $A_{ij}^{(t)}$ in the temporal network encodes the number of Ph.D. recipients who graduated from university $j$ and subsequently supervised a Ph.D. student at university $i$ who graduated in year $t$. The edge directions, where $A_{ij}^{(t)}$ is an edge from university $i$ to university $j$, point in the opposite direction to the flow of the people who earned their Ph.D. degrees. We define edge directions in this way to indicate that university $i$ effectively selects the output of university $j$ when they hire someone who received their Ph.D. from $j$ \cite{burris2004,myers2011,clauset2015}. With this convention for the direction of edges, $\{{\bf C}^{(t)}\}$ encodes the PageRank matrices of the layers; and the highest-ranking universities are the ones that are good sources for the flow of Ph.D. recipients. The network, which we constructed using data from the Mathematics Genealogy Project \cite{mgp}, is available at \cite{MGP_data}. {We focus our discussion on five U.S. universities: Harvard, Massachusetts Institute of Technology (MIT), Princeton, Stanford, and University of California at Berkeley. They have the largest PageRank centralities (using a node-teleportation parameter of $\sigma=0.85$) for a temporally aggregated network with adjacency matrix $\sum_t \bm{A}^{(t)}$.} In all of our experiments, we assume that the layers' centrality matrices are given by PageRank matrices, as defined in Eq.~\eqref{eq:google}. As in our previous explorations \cite{taylor2017eigenvector,taylor2019tunable}, we vary the interlayer coupling strength $\omega$ to adjust how rapidly centralities change over time. In the present work, our primary focus is investigating the effects on supracentralities of undirected and directed interlayer coupling. See Eq.~\eqref{eq:undir} and Eq.~\eqref{eq:tele} for the definitions of these interlayer-coupling schemes; and see Fig.~\ref{fig:toy1} for visualizations of these two types of interlayer coupling. \begin{figure}[t] \includegraphics[width=1\linewidth]{fig_undir_chain.pdf} \caption{{\bf Trajectories of node centralities using undirected interlayer coupling for mathematical-sciences programs at five top universities.} The top and bottom rows illustrate joint and conditional node centralities, respectively, that we compute with layer centrality matrices based on PageRank with a node-teleportation parameter of $\sigma=0.85$ and undirected interlayer coupling $\tilde{\bm{A}}$ given by Eq.~\eqref{eq:undir} with $\omega\in\{1,10,100,1000\}$. The dotted black curve in the upper-right panel is the result of an asymptotic approximation that we present in Section \ref{sec:asym}. } \label{fig:undir} \end{figure} \begin{figure}[t] \includegraphics[width=1\linewidth]{directed_A.pdf} \caption{{\bf Trajectories of node centralities using directed interlayer coupling for mathematical-sciences programs at five top universities.} This figure is similar to Fig.~\ref{fig:undir}, except that the interlayer-adjacency matrix $\tilde{\bm{A}}$ is now given by Eq.~\eqref{eq:tele}, which corresponds to a directed chain with layer teleportation with rate $\gamma$. Panels (A), (B), and (C) show results for $\gamma = 0.0001$, $\gamma = 0.001$, and $\gamma = 0.01$, respectively. The dotted black curves in the upper-right panels are the result of an asymptotic approximation that we present in Section \ref{sec:asym}. For sufficiently large $\omega$ and sufficiently small $\gamma$, observe that the joint centralities decrease with time. } \label{fig:dir1} \end{figure} \begin{figure}[t] \includegraphics[width=1\linewidth]{directed_B.pdf} \caption{{\bf Trajectories of node centralities using reversed directed interlayer coupling for mathematical-sciences programs at five top universities.} This figure is identical to Fig.~\ref{fig:dir1}, except that $\tilde{\bm{A}}$ is now given by the transpose of the matrix from Eq.~\eqref{eq:tele}, such that the directed chain points backwards in time. For sufficiently large $\omega$ and sufficiently small $\gamma$, observe that the joint centralities now increase with time. } \label{fig:dir2} \end{figure} We first consider undirected interlayer coupling, so we define $\tilde{\bm{A}}$ by Eq.~\eqref{eq:undir}. In Fig.~\ref{fig:undir}, we plot the joint and conditional centralities for the five universities. The columns show several results for interlayer-coupling strengths $\omega\in\{1,10,10^2,10^3\}$. In the bottom row, we see that that progressively larger values of $\omega$ yield progressively smoother conditional-centrality trajectories. In the top row, we observe that as one increases $\omega$, the joint centrality appears to limit to one arc of a sinusoidal curve. We prove this result in Sec.~\ref{sec:asym}. The most striking results occur in the bottom row of the third column. Based on node conditional centrality, we see that MIT becomes the top-ranked university in the 1950s and then remains so in our data set. Stanford and UC Berkeley develop gradually larger conditional centralities over the 64 years in the data set, whereas those of Princeton and Harvard decrease gradually over this period. When considering all universities, these five universities have among the top 10 node conditional centralities throughout all years of the data set. This is consistent with our results in \cite{taylor2017eigenvector,taylor2019tunable}. We now examine directed interlayer coupling, and we take $\tilde{\bm{A}}$ to correspond to a directed chain with layer teleportation. See Eq.~\eqref{eq:tele} for the specific formula and the bottom row of Fig.~\ref{fig:toy1} for an associated visualization. In each panel of Fig.~\ref{fig:dir1}, we plot the joint centralities and conditional node centralities. The columns give results for interlayer coupling strengths of $\omega\in\{0.1,1,10,100\}$, and the three panels indicate different choices for the layer-teleportation probabilities: (A) $\gamma=0.0001$; (B) $\gamma=0.001$; and (C) $\gamma=0.01$. The dotted black curves in the right column indicate large-$\omega$ asymptotic approximations that we will present in Section \ref{sec:asym}. To understand the main effect of directed interlayer coupling, we first compare the joint centralities in Fig.~\ref{fig:dir1} to those in Fig.~\ref{fig:undir}. To help our discussion, we focus on the rightmost column of both figures. Comparing Fig.~\ref{fig:dir1} to Fig.~\ref{fig:undir}, we observe that the joint-centrality trajectories tend to decay with time for directed interlayer coupling, whereas they are peaked and attain their largest values near $t\approx 1978$ for undirected interlayer coupling. Therefore, directed interlayer coupling tends to ``boost'' the joint centralities of earlier time layers in comparison to undirected coupling. Comparing panels (A)--(C) in Fig.~\ref{fig:dir1} (and again focusing on the rightmost column), we observe that the rate of decay is fastest for $\gamma=0.0001$ (panel (A)) and slowest for $\gamma=0.01$ (panel (C)). The conditional centralities are also affected by directed interlayer coupling. Consider $\omega=10$ in Fig.~\ref{fig:undir}, and observe that the conditional centrality of Princeton decreases monotonically in time. By contrast, observe in Fig.~\ref{fig:dir1}(A,B) for $\omega=10$ that the conditional centrality of Princeton now decreases from $t=1946$ to $t \approx 1988$, but then it increases. For our last experiment, we examine how reversing the direction of interlayer edges changes the results of our supracentrality calculations. Specifically, we repeat the previous experiment with directed interlayer edges, except that now we set $\tilde{\bm{A}}$ to be the transpose of the matrix that we defined by Eq.~\eqref{eq:tele}. One motivation is that for some applications, the most recent time layers are more important than the earliest time layers; and one can incorporate this idea into our supracentrality framework by reversing the direction of interlayer edges. In Fig.~\ref{fig:dir2}, we plot the same quantities as in Fig.~\ref{fig:dir1}, except that now we take the directed interlayer edges to have the opposite direction (so we have reversed the arrow of time). Observe that the joint centralities now tend to increase with time, as opposed to Fig.~\ref{fig:dir1}, where they tended to decrease with time. These trends are most evident in the rightmost columns. We also observe differences for the conditional centralities. For example, focusing on $\omega=10$ in the third column of Fig.~\ref{fig:dir2}, we see that Princeton never has the largest conditional centrality. By contrast, for $\omega=10$ in Fig.~\ref{fig:undir} and Fig.~\ref{fig:dir1}(A,B), Princeton has the largest conditional centrality for the earliest time steps (specifically, for $t\in\{1946,\dots,1954\}$). Understanding how the weights, topologies, and directions of interlayer coupling affect supracentralities is essential to successfully deploying supracentrality analysis to reveal meaningful insights. The above experiments highlight that one can tune the weights and topology of interlayer coupling to emphasize either earlier or later time layers. Specifically, one can adjust the parameters $\omega$ and $\gamma$, as well as the direction of interlayer edges, to cater a study to particular data sets and particular research questions. We investigate both the case in which $\tilde{\bm{A}}$ is given by Eq.~\eqref{eq:tele} and that in which it is given by the transpose of the matrix that we determine from Eq.~\eqref{eq:tele}. It is worth considering how these different choices of interlayer edge directions are represented in the supracentrality matrix $\mathbb{C}(\omega)$ and the resulting effects of these choices. Specifically, each layer's PageRank matrix ${\bf C}^{(t)}$ is defined in Eq.~\eqref{eq:google} using the transpose of the layer's adjacency matrix ${\bf A}^{(t)}$, yet when coupling the centrality matrices, we do not take the transpose of $\tilde{\bm{A}}$ when defining $\mathbb{C}(\omega)$ in Eq.~\eqref{eq:supracentrality}. Accordingly, one may worry that the matrix $\mathbb{C}(\omega)$ effectively acts in the forward direction for the intralayer edges, but in the opposite direction for the interlayer edges. However, this does not lead to any inherent contradiction, as the meanings of the directions in these two types of edges are fundamentally different: the direction of intralayer edges dictates the flow of random walkers, whereas the direction of interlayer edges couples the centralities of the different layers. In other applications, it may be necessary to encode the directions of the interlayer and intralayer edges in the same way, but there is no reason why one cannot encode directions of interlayer and intralayer edges in different ways in a supracentrality formalism. As we have demonstrated by considering both $\tilde{\bm{A}}$ and its transpose --- and thus by treating the effect of the interlayer edges in opposite ways in these two calculations --- both uses are meaningful. They also probe different aspects of the temporal data. \section{Asymptotic Behavior for Small and Large Interlayer-Coupling Strength $\omega$}\label{sec:asym} In this section, we summarize the asymptotic results from \cite{taylor2019tunable} that reveal the behavior of supracentralities in the limit of small and large $\omega$. In our present discussion, we focus on dominant right eigenvectors. To motivate our asymptotic analysis, consider the top-right subpanels in each panel of Figs.~\ref{fig:undir}, \ref{fig:dir1}, and \ref{fig:dir2}. In each of these subpanels, we plot (in dotted black curves) the results of asymptotic analysis of the dominant right eigenvector $\tilde{{\bf v}}^{(1)}$ of $\tilde{\bm{A}}$ for the joint centrality of MIT in the limit of large $\omega$. We observe excellent agreement with our numerical calculations. Therefore, for sufficiently large $\omega$, one can understand the effects of both undirected and directed interlayer couplings (as encoded in an interlayer-adjacency matrix $\tilde{\bm{A}}$) by examining the dominant right eigenvector of $\tilde{\bm{A}}$. For large values of $\omega$, this eigenvector captures the limit of the joint centralities as a function with a peak for undirected coupled (see Fig.~\ref{fig:undir}), decay in time for directed coupling (see Fig.~\ref{fig:dir1}), and growth in time for directed coupling when reversing the arrow of time (see Fig.~\ref{fig:dir2}). \subsection{Layer Decoupling in the Limit of Small $\omega$} We begin with some notation. Let $\tilde{\mu}_1$ be the dominant eigenvalue (which we assume to be simple) of $\tilde{\bm{A}}$, and let $\tilde{\bm{u}}^{(1)}$ and $\tilde{\bm{v}}^{(1)}$ denote its corresponding left and right eigenvectors. Given a set $\{\mathbf{C}^{(t)}\}$ of centrality matrices, we let $\mu^{(t)}_1$ be the dominant eigenvalue (which we also assume to be simple) of $\mathbf{C}^{(t)}$; and ${\bf u}^{(1,t)}$ and ${\bf v}^{(1,t)}$ are the corresponding left and right eigenvectors. Let $\{\mu^{(t)}_1\}$ denote the set of spectral radii, where $\lambda_{\rm{max}}(0) = \max_t \mu^{(t)}_1$ is the maximum eigenvalue over all layers. (Recall that $\lambda_{\rm{max}}(\omega)$ is the dominant eigenvalue of the supracentrality matrix $\mathbb{C}(\omega)$.) Let $\mathcal{P} = \{t : \mu_1^{(t)} = \lambda_{\rm{max}}(0) \}$ denote the set of layers whose centrality matrices achieve the maximum. When the layers' centrality matrices $\{\mathbf{C}^{(t)}\}$ are PageRank matrices given by Eq.~\eqref{eq:google}, it follows that $\mu_1^{(t)} =1$ for all $t$ (i.e., $\mathcal{P}=\{1,\dots,T\}$), the corresponding left eigenvector is ${\bf u}^{(1,t)} =[1,\dots,1]^T/N$, and $ {\bf v}^{(1,t)}$ is the PageRank vector for layer $t$. Furthermore, for each $t$, we define the length-$NT$ ``block'' vector ${\mathbbm{v}}^{(1,t)} = {{\bf e}}^{(t)} \otimes {\bf v}^{(1,t)}$, which consists of $0$ entries except for block $t$, which equals ${\bf v}^{(1,t)}$. (The vector ${{\bf e}}^{(t)}$ is a length-$T$ unit vector that consists of $0$ entries except for entry $t$, which is $1$.) We now present a theorem from \cite{taylor2019tunable}, although we restrict our attention to the part that describes the right dominant eigenvector. \begin{theorem}[Weak-Coupling Limit of Dominant Right Eigenvector \cite{taylor2019tunable}] \label{thm:uncoupled2} Let $\mathbbm{v} (\omega)$ be the dominant right eigenvector of a supracentrality matrix that is normalized using the $1$-norm and satisfies the assumptions of Thm.~\ref{thm:unique}. Additionally, let $\mathcal{P} = \{t : \mu_1^{(t)} = \lambda_{\rm{max}}(0) \}$ denote the set of indices associated with the eigenvalues of $\mathbf{C}^{(t)}$ that equal the largest eigenvalue $\lambda_{\rm{max}}(0)$ of $\mathbb{C}(0)$. We assume that each layer's dominant eigenvalue $\mu_1^{(t)}$ is simple. It then follows that the $\omega \to 0^+$ limit of $\mathbbm{v} (\omega)$ is \begin{align}\label{eq:lim_uv} \mathbbm{v} (\omega) \to \sum_{t\in\mathcal{P}} \alpha_{t} \mathbbm{v}^{(1,t)}\,, \quad \end{align} where the vector $\bm{\alpha} = [\alpha_{1},\dots,\alpha_{T}]^T$ has nonnegative entries and is the unique solution to the dominant eigenvalue equation \begin{align}\label{eq:baah} \bm{X} \bm{ \alpha} &= \lambda_{1} \bm{ \alpha}\,. \end{align} The eigenvalue $\lambda_{1}$ needs to be determined, and the entries of $\bm{X}$ are \begin{align}\label{eq:Xtt} {X}_{tt'} &= \tilde{ {A}}_{t,t'} \frac{ \langle {\bf u}^{(1,t)} , {\bf v}^{(1,t')} \rangle}{\langle{\bf u}^{(1,t)}, {\bf v}^{(1,t)} \rangle } \chi(t)\chi(t') \,, \end{align} where $\chi(t)=\sum_{t'\in\mathcal{P}} \delta_{tt'}$ is an indicator function: $\chi(t)=1$ if $t\in\mathcal{P}$ and $\chi(t)=0$ otherwise. The vector $\bm{\alpha} $ must also be normalized to ensure that the right-hand side of Eq.~\eqref{eq:lim_uv} is normalized (i.e., by setting $\|\bm{\alpha} \|_p=1$ for normalization with a $p$-norm). \end{theorem} \subsection{Layer Aggregation in the Limit of Large $\omega$}\label{sec:strong} To study the $\omega\to\infty$ limit, it is convenient to divide Eq.~\eqref{eq:eig_eq} by $\omega$ and define $\epsilon=1/\omega$ to obtain \begin{equation}\label{eq:newC} \tilde{\mathbb{C}}(\epsilon) = \epsilon \mathbb{C}(\epsilon^{-1}) = \epsilon\hat{\mathbb{C}} + \hat{\mathbb{A}}\,, \end{equation} which has right eigenvectors $\tilde{\mathbbm{v}}(\epsilon)$ that are identical to those of $\mathbb{C}(\omega) $ (specifically, $\tilde{\mathbbm{v}}(\epsilon)={\mathbbm{v}}(\epsilon^{-1})$). Its eigenvalues $\{ \tilde{\lambda}_i\}$ are scaled by $\epsilon$, so $ \tilde{\lambda}_i(\epsilon) = \epsilon\lambda_i(\epsilon^{-1})$. Before presenting results from \cite{taylor2019tunable}, we define a few additional concepts. Let $\tilde{\mathbbm{v}}^{(1,j)}=\tilde{{\bf e}}^{(j)} \otimes \tilde{\bm{ v}}^{(1)}$ denote a block vector that consists of $0$ entries, except for block $j$, which equals the dominant right eigenvector $\tilde{\bm{ v}}^{(1)}$ of $\tilde{\bm{A}}$. (The vector $\tilde{{\bf e}}^{(j)}$ is a length-$N$ unit vector that consists of $0$ entries except for entry $j$, which is $1$.) We also define the stride permutation matrix \begin{equation}\label{eq:stride} [\mathbb{P}]_{kl} = \left\{ \begin{array}{rl} 1\,,& \,\,l=\lceil k/N\rceil+T\,[(k-1)\bmod N]\,, \\ 0\,,& \,\,\textrm{otherwise} \, , \end{array} \right. \end{equation} where the ceiling function $\lceil \theta \rceil$ denotes the smallest integer that is at least $\theta$, and `$\bmod$' denotes the modulus function (i.e., $a \bmod b= a - b \lceil a/b -1\rceil$). \begin{theorem}[Strong-Coupling Limit of Dominant Eigenvectors \cite{taylor2019tunable}] \label{thm:singular_limit} Let $\tilde{\bm{A}}$, $\tilde{\mu}_1$, $\tilde{\bm{u}}^{(1)}$, and $\tilde{\bm{v}}^{(1)}$ be defined as above, with the same assumptions as in Theorem~\ref{thm:unique}. It then follows that the dominant eigenvalue $\tilde{\lambda}_{\rm{max}}(\epsilon)$ and the associated eigenvector $\mathbbm{v}^{(1)}(\epsilon)$ of $\mathbb{C}(\epsilon)$ converge as $\epsilon \to 0^+$, such that \begin{align} \tilde{\lambda}_{\rm{max}}(\epsilon) &\to\tilde{ \mu}_1 \,,~~ \nonumber \\ \tilde{\mathbbm{v}}^{(1)}(\epsilon) &\to \sum_j \tilde{\alpha}_{j} \mathbb{P}\tilde{\mathbbm{v}}^{(1,j)} \,, \label{eq:conver2} \end{align} where the constants $\{\tilde{\alpha}_i\}$ solve the dominant eigenvalue equation \begin{equation}\label{eq:alpha_beta} \tilde{\mathbf{X}} \tilde{\bm{\alpha}} = \tilde{\mu}_1 \tilde{\bm{\alpha}}\,, \end{equation} with \begin{align} \tilde{X}_{ij} &= \sum_{t} {C}^{(t)}_{ij} \frac{\tilde{u}_t^{(1)} \tilde{v}_t^{(1)}}{\langle \tilde{\bm{u}}^{(1)}, \tilde{\bm{v}}^{(1)} \rangle} \,. \label{eq:M1star_0_q} \end{align} Note that we normalize the vector $\tilde{\bm{\alpha}} $ to ensure that the right-hand side of Eq.~\eqref{eq:conver2} is normalized. \end{theorem} Equation~\eqref{eq:M1star_0_q} indicates that the strong-coupling limit effectively aggregates the centrality matrices $\{ {\bf C}^{(t)} \}$ across time via a weighted average, with weights that depend on the dominant left and right eigenvectors of $\tilde{\bm{A}}$. When $\tilde{\bm{A}}$ encodes an undirected chain from Eq.~\eqref{eq:undir} (see the top row of Fig.~\ref{fig:toy1}), it follows that \cite{taylor2017eigenvector} \begin{equation}\label{eq:sin} \tilde{\mathbf{X}} = \sum_{t} \mathbf{C}^{(t)} \frac{\sin^2\left( \frac{\pi t}{T+1}\right)}{\sum_{t=1}^T \sin^2\left( \frac{\pi t}{(T+1)}\right)}\,. \end{equation} The dotted black curve in the top-right subpanel of Fig.~\ref{fig:undir} shows a scaled version of $ \tilde{\bm{v}}^{(1)} $, which is defined by the normalized sinusoidal weightings in Eq.~\eqref{eq:sin}. The dotted black curves in the top-right subpanels of Figs.~\ref{fig:dir1} and \ref{fig:dir2} also show $ \tilde{\bm{v}}^{(1)} $ (specifically, when $\tilde{\bm{A}}$ is given by Eq.~\eqref{eq:tele} or by the transpose of the matrix that we obtain from Eq.~\eqref{eq:tele}, respectively), which we scale so to normalize the joint centralities. \section{Discussion} We have presented a supracentrality framework to study how the importances of nodes in a temporal network change over time. Our approach involves representing a temporal sequence of networks as time layers in a multiplex network and using the strength and topology of coupling between time layers to tune centrality trajectories. A key feature of our approach is that it simultaneously yields the centralities of all nodes at all times by computing the dominant right eigenvector of a supracentrality matrix. Inspired by ideas from probability theory, we examined three types of eigenvector-based supracentralities: \begin{enumerate} \item[(i)] the joint centrality for a node-layer pair $(i,t)$; this captures the combined importance of node $i$ and time layer $t$; \item[(ii)] the marginal centrality of node $i$ or time $t$; these captures separate importances of a node or time layer; and \item[(iii)] the conditional centrality of a node $i$ at time $t$; this captures the importance of a node relative only to other nodes at that particular time. \end{enumerate} Because our approach involves analyzing the dominant eigenvector of a centrality matrix, it generalizes eigenvector-based centralities --- such as PageRank, hub and authority centralities, and (vanilla) eigenvector centrality --- from network analysis of graphs. Naturally, it is desirable to extend supracentralities for the analysis of networks that are both temporal and multiplex \cite{kivela2014}. Another important generalization of centrality analysis is to study continuous-time temporal networks and streaming network data \cite{Grindrod_Higham_2014,walid2018}, and it would be insightful to extend our supracentrality framework to such situations. \section*{Acknowledgements} We thank Petter Holme and Jari Saram{\"a}ki for the invitation to write this chapter. We thank Deryl DeFord, Tina Eliassi-Rad, Des Higham, Christine Klymko, Marianne McKenzie, Scott Pauls, and Michael Schaub for fruitful conversations. DT was supported by the Simons Foundation under Award \#578333. PJM was supported by the James S. McDonnell Foundation 21st Century Science Initiative --- Complex Systems Scholar Award \#220020315. \bibliographystyle{spphys}
{'timestamp': '2019-06-18T02:01:41', 'yymm': '1906', 'arxiv_id': '1906.06366', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06366'}
arxiv
\section*{Wishlist and Notes} \begin{enumerate} \item FT GUIDE LMT LOTUS M5’ MLRT MOB SUPPORT are all possible tree algorithms that fit linear leaves. Some of them are not open source, and none of them is in C++ afaik. It would be nice to compare them to our tree algorithm. \item can we reproduce the wager et al. argument for confidence interval. using the infinitesimal jacknife we should be able to get CI fast and given our trees with less bias, we should be able to getbetter inferece. \item \cite{abadie2011bias} Bias-corrected matching estimators for average treatment effects. local regression adjustment to correct for potential misalignment between a test point and its neighborhood, % % % % % % \item To show the difference between this splitting function and ours, we simulate $x_1, \ldots, x_n$ from a $N(0, 5)$ distribution and we create $y$ by $$y = |x_1 - 1| + \varepsilon, \quad \varepsilon \sim N(0,1).$$ The left-hand side of Figure ?? shows the performance of the different estimators for one and 5000 trees. We can see that our \texttt{forestry} algorithm describes the true behavior very well already for one tree. The right-hand side of the figure shows one of the best performing trees in the forest algorithms as measured by the OOB-error. We can see that this best performing tree is extremely shallow and it is therefore very interpretable compared to the best performing CART tree that has more than 60 levels. \begin{enumerate} \item Use for prediction intervals. In each tree, take a weighted mean of indicator for observations below observation, aggregate across the forest \end{enumerate} \item Breiman's original formulation goes through all splits. \item We then show that the ideas we used can be done for many aggregation functions as long as they allow a fast online update. \end{enumerate} } \end{comment} \section{Introduction} Classification and Regression Trees (CART) \citep{morgan1963problems, breiman1984classification} have long been used in many domains. Their simple structure makes them interpretable and useful for statistical inference, data mining, and visualizations. The Random Forests (RF) \citep{breiman2001random} algorithm and the Gradient Boosting Machine (GBM) \citep{friedman2001greedy} build on these tree algorithms. They are less interpretable and more laborious to visualize than single trees, but they often perform better in predictive tasks and lead to smoother estimates \citep{buhlmann2002analyzing, svetnik2003random, touw2012data}. As these tree-based algorithms predict piece-wise constant responses, this leads to (a) weaker performance when the underlying data generating process exhibits smoothness, (b) relatively deep trees that are harder to interpret, and (c) bias that makes valid inference and confidence interval estimation difficult. To address these weaknesses, we study regression trees with a linear aggregation function implemented in the leaves. Specifically, we introduced three core changes to the classical CART algorithm: \begin{enumerate} \item Instead of returning for each leaf the mean of the corresponding training observations as in the classical CART algorithm, we fit a ridge regression in each leaf. That is, for a unit that falls in a leaf $S$, the tree prediction is \begin{equation} \label{eq:linearRet} \hat \mu(x_{\mbox{\tiny new}}) = x_{\mbox{\tiny new}}^t (X_S^t X_S + \lambda I)^{-1} X_S^t Y_S, \end{equation} where $Y_S$ is the vector of $y$-values of the training observations that fall in leaf $S$, $X_S$ is the corresponding design matrix for these observations, and $\lambda \in \mathbb{R}^+$ is a regularization parameter.\footnote{In a more elaborate version of the algorithm, the observations in leaf $S$ are a subset that is independent of the subset of training observations used to create the skeleton of the trees.} \item Crucial to the success of such an aggregation function, we take the fact that we fit a regularized linear model in the leaves into account when constructing the tree by following a greedy strategy that finds the \textit{optimal}\footnote{We define what we mean by \textit{optimal} in Section \ref{section:Algorithm}.} splitting point at each node. That is, for each candidate split that leads to two child nodes $S_L$ and $S_R$, we take the split such that the total MSE after fitting an $\ell_2$-penalized linear model on each child is minimized. This is very difficult, and we believe that one of our main contributions is that we found a very efficient way to find this optimal splitting point. We discuss in detail how the optimal splitting point is calculated in Section \ref{section:Algorithm}. \item Furthermore, we use a cross-validation stopping criteria that determines when to continue splitting as opposed to when to construct a leaf node. After selecting the optimal split, the improvement in $R^2$ that is introduced by the potential split is calculated. If the potential split increases the $R^2$ by less than a predetermined stopping value, then the splitting procedure is halted and a leaf node is created. This leads to trees that can create large nodes with smooth aggregation functions on smooth parts of data, while taking much smaller nodes which mimic the performance of standard CART aggregation on separate subsets of the response surface. This adaptivity over varying degrees of smoothness is displayed below in Figure \ref{fig:classicalVSlinearCART} and explored in greater detail in Section \ref{section:simulationstudies}. \end{enumerate} These changes improve the \textbf{predictive performance} of such Linear Regression Trees (LRT) substantially, and---as we see in Section \ref{section:simulationstudies}---it compares favorably on real-world examples when used in a Linear Random Forests (LRF) ensemble. We also connect it with an effective tuning algorithm, and we find that it can behave like both a regularized linear model and a CART/RF estimator depending on the chosen hyperparameters. This adaptivity as an estimator is explored in a set of experiments in Section \ref{section:simulationstudies}. The linear response functions in turn lead to much shallower trees without losing predictive performance. This improves the \textbf{interpretability} of the trees substantially---a direction which has always been a major motivation for studying regression trees with linear aggregation functions \citep{karalivc1992employing}. In Section \ref{section:interpretability}, we illustrate the advantages for interpretability using a large dataset measuring the treatment effect of several treatments on voter turnout \citep{GerberGreenLarimer}. We adapt the S-Learner with random forests as implemented in causalToolbox \citep{kunzel2019metalearners} to use the linear aggregation function of linear regression trees. We then use the plot function from the \textbf{\textit{forestry}}\xspace package to visualize several trees in Figure \ref{fig:RRFforSLearner} and the regression coefficients of their leaves. This allows us to identify groups of potential voters with similar voting behavior, make inference on their future voting propensity, and see the effects different mailers have on future voter turnout. \begin{figure} \centering \includegraphics[width=\linewidth]{001_IntroFigure_v2.pdf} \caption{ Comparison of the classical CART and LRT. The top of the figure shows the Linear Regression Trees and the classical CART, and the lower part shows the density of the training set. } \label{fig:classicalVSlinearCART} \end{figure} \subsection{Literature} Studying regression trees with linear aggregation functions has a long history. The earliest reference we are aware of is by \cite{breiman1976general} which precedes the original CART publication \citep{breiman1984classification}. The algorithm can be interpreted as a tree algorithm: At each node, the algorithm attempts to introduce a new split along a randomly oriented plane. It then fits a linear model in both children, and it accepts the split if it sufficiently reduces the residual sum of squares as captured by an F-ratio test. If the split is not accepted, the algorithm attempts more splits a limited number of times before declaring the node a leaf node. There has been much research that builds on this first algorithm, and many different variants of it have been proposed. Apart from a few exceptions \citep{zhu2015reinforcement}, the trees are constructed in a recursive strategy and the main differences between the algorithms are, how the splits are generated---the splitting criteria---and when splitting is halted for a node to be defined as a leaf---the stopping criteria. For the splitting criteria, there have been many different suggestions. \cite{Torgo:1997} spans the trees similar to the standard CART algorithm without adaptations to the new aggregation function. \cite{chaudhuri1994piecewise} and \cite{li2000interactive}, on the other hand, fit a linear model, or more generally, a polynomial model, on all units in the current node and then suggest a split by looking at the residuals of the fitted model. \cite{zeileis2008model} and \cite{rusch2013gaining}, in turn, use a two-step procedure to find a good split. In the first step, the algorithms also fit a linear model on all units in the current node, and they then screen for good splitting covariates using a test statistic that can be computed relatively fast. In a second step, the algorithm then exhaustively searches through all possible splits along the selected features. While it is possible to grow trees until there is only one observation left in each leaf, it is useful to have tree structures with more than one observation per leaf. This is particularly important when using a linear aggregation function. However, the exact number of observations which should be in each leaf is much harder to determine. Early stopping and pruning of the trees after they have been trained have both been used for regression trees with linear aggregation functions. For example, \cite{quinlan1992learning} and \cite{gama2004functional} build linear models in the pruning phase of each leaf, while \cite{chaudhuri1994piecewise} use a stopping criterion that is based on cross-validation and attempts to estimate whether a further split sufficiently improves the mean squared error. While it is always possible to bootstrap these algorithms and combine them with ideas introduced in Random Forests \citep{breiman2001random}, these ideas were mainly studied as regression trees, even though one would expect better predictive power and smoother prediction surfaces in the bagged versions \citep{buhlmann2002analyzing}. Additionally, some of these algorithms would be computationally too expensive to be used in a bagged version. However, there has been some work done combining RF and bagged trees with linear models. \cite{bloniarz2016supervised} followed ideas by \cite{hothorn2004bagging}, \cite{lin2006random}, and \cite{meinshausen2006quantile} to interpret random forests as an adaptive potential nearest neighbor method. Their method, SILO (Supervised Local modeling), uses the random forests algorithm to provide a distance measure, $w$, based on the proximity distance of random forests, and it then defines the random forests prediction, $\hat g(x)$, as a local linear model \citep{stone1977consistent} via the following two step process: \begin{equation} \label{eq:RFLocalModel} \begin{aligned} \hat f_x(\cdot) &= \argmin_{f \in \mathcal{F}} \sum_{i=1}^N w(x_i, x) (y_i - f(x_i - x))^2,\\ \hat g(x) &= \hat f_x(0), \end{aligned} \end{equation} where $\mathcal{F}$ is some set of functions. In their paper, they focused in particular on linear models and demonstrated its superior performance over other local models such as LOESS \citep{cleveland1988locally} and untuned RF. In a very recent paper, \cite{friedberg2018local} also combined random forests with linear models. Their work is similar to that of \cite{bloniarz2016supervised} in the sense that they also use the proximity weights of random forests to fit a local linear model. Specifically, they focus on linear models, and they fit a ridge regularized linear model, \begin{equation}\label{loss} \begin{pmatrix} \hat{\mu}(x) \\ \hat{\theta}(x) \end{pmatrix} = \argmin_{\mu,\theta} \left\{ \sum_{i=1}^n w(x_i, x) (y_i - \mu - (x_i - x)^t\theta)^2 + \lambda ||\theta||_2^2 \right\}, \end{equation} and use $\hat \mu(x)$ as the estimate for $\mathbb{E}[Y|X = x]$. Similar to \cite{chaudhuri1994piecewise}, they adapt the splitting function to account for the fitting of such local models. When evaluating a split on a parent node P, the split is adapted by fitting a ridge regression in each parent node P to predict $\hat{Y}_{P,Ridge}$ from $X_{P}$ and then the standard CART splitting procedure on the residuals $Y_P - \hat{Y}_{P,Ridge}$ is used to select a splitting point. This results in a fast splitting algorithm which utilizes the residuals to model for local effects in forest creation and optimize for the fitted models which are later used for regression. \subsection{Our contribution} Our main contribution is to develop a fast algorithm to find the best partition for a tree with a ridge regularized linear model aggregation function. To our knowledge, we are the first to develop and analyze this algorithm, even though there are software packages that have not publicized their source code that might use a similar idea. In Section \ref{section:Algorithm}, we explain the algorithm and we show that its run time is $\mathcal{O}(m*(n*\log(n) + n * p^2))$ where $n$ is the number of observations in the current node, $p$ is the number of dimensions that is fit with a linear model, and $m$ is the number of potential splitting covariates. In Section \ref{section:simulationstudies}, we use the splitting algorithm with random forests, and we show that it compares favorably on many data sets. Depending on the chosen hyperparameters, the LRF algorithm can then behave and perform similarly to either the default RF algorithm or a ridge regularized linear model. Because the algorithms can be trained relatively fast, we were able to connect them with a tuning algorithm, and show how it can quickly adapt to the underlying smoothness levels in different datasets. In Section \ref{section:interpretability}, we then apply a simple LRT to a real data set to show how its simple structure lead to a deeper understanding of the underlying processes. \subsection{Software example} An implementation of this algorithm is used in the \textbf{\textit{forestry}}\xspace package and can, for example, be used in random forests using the \lstinline[columns=fixed]{linear = TRUE} option. \begin{lstlisting} forest <- forestry(x = iris[,-1], y = iris[,1], linear = TRUE, overfitPenalty = 2) predict(forest, feature.new = iris[,-1]) \end{lstlisting} \section{The Splitting Algorithm} \label{section:Algorithm} Random forests are based on a regression tree algorithm, which is in turn based on a splitting algorithm. This splitting algorithm is used in most tree-based algorithms to recursively split the space into subspaces which are then encoded in a binary regression tree. In this section, we first motivate and describe the new splitting algorithm and then discuss its asymptotic runtime. To setup the notation, assume that we observe $n$ observations, $(X_i, Y_i)_{i = 1}^{n}$. $X_i \in \mathbb{R}^d$ is the $d$-dimensional feature vector and $Y_i \in \mathbb{R}$ is the dependent variable of unit $i$. For a feature $\ell \in \{0, \ldots, d\}$, the goal is to find a splitting point $s$ to separate the space into two parts, \begin{align} L := \{x \in \mathbb{R}^d : x[\ell] < s\},& &R := \{x \in \mathbb{R}^d : x[\ell] \ge s\}. \end{align} We call $L$ and $R$ the left and right sides of the partition respectively. In many tree-based algorithms, including CART, RF, and GBM, the splitting point $s^*$ is a point that minimizes the combined RSS when fitting a constant in both parts of the space, \begin{equation}\label{eq:meanSplittingProblem} s^* \in \argmin_{s} \sum_{i : X_i \in L} \Big(Y_i - \bar Y^L\Big)^2 + \sum_{i : X_i \in R} \Big(Y_i - \bar Y^R\Big)^2. \end{equation} Here $\bar Y^L$ is the mean of all units in the left partition and $\bar Y^R$ is the mean of all units in the right partition. Note that $L$ and $R$ are functions of $s$. We generalize this idea to Ridge regression. We want to find $s^*$ that minimizes the overall RSS when- in both partitions- a Ridge-regularized linear model is fitted instead of a constant value. \begin{equation}\label{eq:ridgeSplittingProblem} s^* \in \argmin_s \sum_{i : X_i \in L} \Big(Y_i - \hat Y^L_i\Big)^2 + \sum_{i : X_i \in R} \Big(Y_i - \hat Y^R_i\Big)^2. \end{equation} Now $\hat Y^L_i$ is the fitted value of unit $i$ when a Ridge regression is fit on the left part of the split, and similarly, $Y^R_i$ is the fitted value of unit $i$ when a Ridge regression is fit on the right part of the split. To find an $s^*$ that satisfies (\ref{eq:ridgeSplittingProblem}), it would be enough to exhaustively search through the set $S = \{X_i[\ell] : 1 \le i \le n\}$. However, if feature $\ell$ is continuous, then there are $n$ potential splitting points. Fitting a ridge regression in both parts and computing the RSS for each potential splitting point thus requires at least $n^2$ steps. This is too slow for most data sets, since the splitting algorithm is applied up to $d n$ times when constructing a single regression tree. \subsection{Fast and exact ridge splitting algorithm} In the following section, we describe an algorithm that computes the exact solution of (\ref{eq:ridgeSplittingProblem}) in quasilinear time by using an online update for the RSS after fitting a ridge regularized linear model. Specifically, the algorithm first sorts the realized values of feature $\ell$ in ascending order. To simplify the notation, let us redefine the ordering of the units in such a way that $$ X_1[\ell] < X_2[\ell] < \cdots < X_n[\ell]. $$ Such a sorting can be done in $\O( n \log n)$.\footnote{We assume here that $X_i[\ell] \neq X_j[\ell]$ for all $j \neq j$. We refer to our implementation in \textbf{\textit{forestry}}\xspace \citep{forestry} for the general case.} The algorithm then checks the $n-1$ potential splitting points that lie exactly between two observations, $$ s_k := \frac{X_k[\ell] + X_{k + 1}[\ell]}{2}, \mbox{ for } 1\le k \le n-1. $$ We define \begin{align} L(k) := \{x \in \mathbb{R}^d : x[\ell] < s_k\},& &R(k) := \{x \in \mathbb{R}^d : x[\ell] \ge s_k\}, \end{align} and the RSS when splitting at $s_k$ as $\mbox{RSS}(k)$, \begin{equation}\label{eq:RSS(k))} \mbox{RSS}(k) := \sum_{i : X_i \in L(k)} \Big(Y_i - \hat Y^{L(k)}_i\Big)^2 + \sum_{i : X_i \in R(k)} \Big(Y_i - \hat Y^{R(k)}_i\Big)^2. \end{equation} Once again, $\hat Y^{L(k)}_i$ is the fitted value of unit $i$ when a Ridge regression is fit on the left part of the split, and similarly, $Y^{R(k)}_i$ is the fitted value of unit $i$ when a Ridge regression is fit on the right part of the split. We are interested in finding \begin{equation}\label{eq:minimizing_for_k} k^* = \argmin_k \mbox{RSS}(k). \end{equation} \subsubsection{Decomposition of the RSS} Let us first state the ridge-regression for the left partition \citep{hoerl1970ridge}. For a given $\lambda > 0$ and leaf, $L$, we want to find $(\hat \beta, \hat c)$ that minimize the ridge penalized least squares equation, \begin{equation} (\hat \beta, \hat c) = \argmin_{(\beta, c)} \sum_{i : X_i \in L} \left(Y_i - X_i^T \beta - c\right)^2 +\lambda \|\beta\|_2^2. \end{equation} A closed form solution of this problem can be derived by setting the gradient of this loss function equal to zero, \begin{align} &\begin{bmatrix}\hat \beta \\ \hat c\end{bmatrix} = \left({\sum_{i = 1}^n \begin{bmatrix}X_i \\1 \end{bmatrix} \begin{bmatrix}X_i^T&1\end{bmatrix} + \lambda \begin{bmatrix} \mathcal{I}_d & 0 \\ 0 & 0 \end{bmatrix}}\right)^{-1} \sum_{i = 1}^n Y_i \begin{bmatrix} X_i \\ 1 \end{bmatrix}. \end{align} For a set $H \subset \mathbb{R}^d$, define \begin{align*} A_H&:= \sum_{i : X_i \in H} \begin{bmatrix}X_i \\1 \end{bmatrix} \begin{bmatrix}X_i^T&1\end{bmatrix} + \lambda \begin{bmatrix} \mathcal{I}_d & 0 \\ 0 & 0 \end{bmatrix}\\ S_H &:= \sum_{i : X_i \in H}Y_i \begin{bmatrix} X_i \\ 1\end{bmatrix},\\ G_H &:= \sum_{i : X_i \in H}\begin{bmatrix} X_i \\ 1\end{bmatrix} \begin{bmatrix} X_i^T & 1\end{bmatrix}. \end{align*} With this notation, we can decompose $\mbox{RSS}(k)$, \begin{align*} \mbox{RSS}(k) &= \sum_{i : X_i \in L(k)}\left(Y_i - \begin{bmatrix} X_i^T & 1\end{bmatrix} A_{L(k)}^{-1} S_{L(k)}^{\phantom{-}}\right)^2 \\&+ \sum_{i : X_i \in R(k)}\left(Y_i - \begin{bmatrix} X_i^T & 1\end{bmatrix} {A_{R(k)}^{-1}} S_{R(k)}^{\phantom{-}}\right)^2 \\ &= \Phi_{L(k)} + \Phi_{R(k)} + \sum_{i = 1}^n Y_i ^2. \end{align*} Here, we used the definition that for a set $H \subset \mathbb{R}^d$, \begin{equation} \label{eq:PhiDecomp} \Phi_H := S_{H}^T A_{H}^{-1} G_{H}^{\phantom{-}} A_{H}^{-1} S_{H}^{\phantom{-}} - 2 S_{H}^T A_{H}^{-1} S_{H}^{\phantom{-}}. \end{equation} As $\sum_{i = 1}^n Y_i ^2 $ is constant over $k$, it can be discarded when considering the optimization problem and thus, \begin{equation} \label{eq:RSSequivalent} \argmin_k~\mbox{RSS}(k) = \argmin_k ~ \Phi_L(k) + \Phi_R(k). \end{equation} \subsubsection{Update Step from \texorpdfstring{$k$ to $k + 1$}{k to k +1}} In order to have a manageable overall runtime for a split, we need to quickly find the minimizer of (\ref{eq:minimizing_for_k}) by looping through from $k = 1$ to $k = n$. \begin{enumerate} \item The algorithm first computes $S_{L(1)}$, $A_{L(1)}^{-1}$, $G_{L(1)}$, $S_{R(1)}$, $A_{R(1)}^{-1}$, and $G_{R(1)}$, and computes the $\mbox{RSS}(1)$. \item The algorithm now computes the $\mbox{RSS}(k)$ for $k \ge 2$ in an iterative way: \begin{enumerate} \item $S_{L(k)}$, $G_{L(k)}$, $S_{R(k)}$, and $G_{R(k)}$ can be directly computed from $S_{L(k - 1)}$, $G_{L(k - 1)}$, $S_{R(k - 1)}$, and $G_{R(k - 1)}$ by a simple addition or subtraction. \item For $A_{L(k)}^{-1}$ and $A_{R(k)}^{-1}$, we use the Sherman-Morrison Formula: \begin{align} A_{L(k)} &= A_{L(k - 1)}^{-1} - \frac{ A_{L(k - 1)}^{-1}\begin{bmatrix}x_{k} \\1\end{bmatrix}\begin{bmatrix}x_{k}^T &1\end{bmatrix}A_{L(k - 1)}^{-1} }{ 1+\begin{bmatrix}x_{k}^T &1\end{bmatrix}A_{L(k - 1)}^{-1}\begin{bmatrix}x_{k} \\1\end{bmatrix} }, \\ A_{R(k)} &= A_{R(k - 1)}^{-1} + \frac{ A_{R(k - 1)}^{-1}\begin{bmatrix}x_{k} \\1\end{bmatrix}\begin{bmatrix}x_{k}^T &1\end{bmatrix}A_{R(k - 1)}^{-1} }{ 1-\begin{bmatrix}x_{k}^T &1\end{bmatrix}A_{R(k - 1)}^{-1}\begin{bmatrix}x_{k} \\1\end{bmatrix} }. \end{align} \end{enumerate} \end{enumerate} An explicit implementation of the split algorithm can be found in Algorithm \ref{algo:RSSonlineContinuous}. \begin{algorithm} \hspace*{\algorithmicindent} \textbf{Input:} Features: $X \in \mathbb{R}^{n\times d}$, \\\hspace*{\algorithmicindent}\hphantom{\textbf{Input: }}~ Dependent Outcome: $Y \in \mathbb{R}^{n}$, \\\hspace*{\algorithmicindent}\hphantom{\textbf{Input: }}~ overfitPenalty (regularization for split): $\lambda \in \mathbb{R}^+$,\\ \hspace*{\algorithmicindent} \textbf{Output:} Best Split point k \begin{algorithmic}[1] \Procedure{FindBestSplitRidge}{} \item[] \item[] Initialization: \State $A^{-1}_{L1} \leftarrow \left(\begin{bmatrix} X_1 \\ 1\end{bmatrix} \begin{bmatrix} X_1^T & 1\end{bmatrix} + \lambda\begin{bmatrix}\mathcal{I}_d & 0 \\0 & 0\end{bmatrix}\right)^{-1}$ \State $A^{-1}_{R1} \leftarrow \left(\sum_{i = 2}^{n} \begin{bmatrix} X_i \\ 1\end{bmatrix} \begin{bmatrix} X_i^T & 1\end{bmatrix} + \lambda \begin{bmatrix}\mathcal{I}_d & 0 \\0 & 0\end{bmatrix}\right)^{-1}$ \State $S_{L1} \leftarrow Y_1 \begin{bmatrix} X_1 \\ 1\end{bmatrix}$ \State $S_{R1} \leftarrow \sum_{i = 2}^n Y_i \begin{bmatrix} X_i \\ 1\end{bmatrix}$ \State $G_{L1} \leftarrow \begin{bmatrix} X_1 \\ 1\end{bmatrix} \begin{bmatrix} X_1^T & 1\end{bmatrix}$ \State $G_{R1} \leftarrow \sum_{i = 2}^n \begin{bmatrix} X_i \\ 1\end{bmatrix} \begin{bmatrix} X_i^T & 1\end{bmatrix}$ \State Compute the RSS sum: \begin{align*} \mbox{RSS}_1 \leftarrow &S_{L1}^T A^{-1}_{L1} G_{L1} A^{-1}_{L1} S_{L1} - 2 S_{L1}^T A_{L1}^{-1} S_{L1} \\+~ &S_{R1}^T A^{-1}_{R1} G_{R1} A^{-1}_{R1} S_{R1} - 2 S_{R1}^T A_{R1}^{-1} S_{R1}. \end{align*} \For{$k = 2, \ldots, n$} \State $A^{-1}_{L(k)} \leftarrow \text{Update\_A\_inv}(A^{-1}_{L(k-1)}, X_k, \text{leftNode} = TRUE)$ \State $A^{-1}_{R(k)} \leftarrow \text{Update\_A\_inv}(A^{-1}_{R(k-1)}, X_k, \text{leftNode} = FALSE)$ \State $S_{L(k)} \leftarrow S_{L(k-1)} + Y_k \begin{bmatrix} X_k \\ 1\end{bmatrix}$ \State $S_{R(k)} \leftarrow S_{R(k-1)} - Y_k \begin{bmatrix} X_k \\ 1\end{bmatrix}$ \State $G_{L(k)} \leftarrow G_{L(k-1)} + \begin{bmatrix} X_k \\ 1\end{bmatrix} \begin{bmatrix} X_k^T & 1\end{bmatrix}$ \State $G_{R(k)} \leftarrow G_{R(k-1)} - \begin{bmatrix} X_k \\ 1\end{bmatrix} \begin{bmatrix} X_k^T & 1\end{bmatrix}$ \State Compute the RSS sum for the current split: \begin{align*} \mbox{RSS}_k \leftarrow &S_{L(k)}^T A^{-1}_{L(k)} G_{L(k)} A^{-1}_{L(k)} S_{L(k)} - 2 S_{L(k)}^T A_{L(k)}^{-1} S_{L(k)}) \\+~ &S_{R(k)}^T A^{-1}_{R(k)} G_{R(k)}) A^{-1}_{R(k)} S_{R(k)} - 2 S_{R(k)}^T A_{R(k)}^{-1} S_{R(k)}. \end{align*} \EndFor \State \Return $(\argmin_{k} \mbox{RSS}_k)$ \EndProcedure \end{algorithmic} \caption{Find Split to Minimize Sum of RSS} \label{algo:RSSonlineContinuous} \algcomment{Update\_A\_inv is defined in Algorithm \ref{algo:updateA}} \end{algorithm} \begin{algorithm} \hspace*{\algorithmicindent} \textbf{Input:} $A^{-1}_{k-1}\in \mathbb{R}^{(d+1)\times (d+1)}$, \\\hspace*{\algorithmicindent}\hphantom{\textbf{Input: }}~ $X_k \in\mathbb{R}^d$, \\\hspace*{\algorithmicindent}\hphantom{\textbf{Input: }}~ leftNode (indicator whether this updates $A_{L(k)}^{-1}$ or $A_{R(k)}^{-1}$)\\ \hspace*{\algorithmicindent} \textbf{Output:} Updated matrix $A^{-1}_{k}$ \begin{algorithmic}[1] \Procedure{Update\_A\_inv}{} \State $z_{k} \leftarrow A_{k-1}^{-1} \begin{bmatrix}X_{k}\\1\end{bmatrix}$ \If{leftNode} \State $g_{k} \leftarrow\dfrac{-z_{k}z_{k}^{T}}{1+\begin{bmatrix}X_{k}^{T} & 1 \end{bmatrix} z_{k}}$ \Else \State $g_{k} \leftarrow\dfrac{z_{k}z_{k}^{T}}{1-\begin{bmatrix}X_{k}^{T} & 1 \end{bmatrix} z_{k}}$ \EndIf \State \Return $A_{k-1}^{-1} + g_{k}$ \EndProcedure \end{algorithmic} \caption{Update the $A^{-1}$ Component of the RSS} \label{algo:updateA} \end{algorithm} \subsection{Runtime Analysis of Finding Split Points} The ability to use an online update for calculating the iterated RSS at each step is crucial for maintaining a runtime that can scale in quasilinear runtime. Here we will provide a detailed breakdown of the runtime for calculating the best split point on a given feature. As we have several steps for updating the RSS components, the runtime depends on both the number of observations, as well as the number of features and therefore may be affected by either. We begin each split by sorting the current split feature taking $\O(n \log n)$ time. Within the split iterations, we iterate over the entire range of split values once, however, at each step we must update the RSS components. While updating the $A^{-1}$ component, as we use the Sherman-Morison Formula to update the inverse of the sum with an outer product, we must compute one matrix vector product ($\O(d^2)$), one vector outer product ($\O(d^2)$), one vector inner product ($\O(d^2)$), division of a matrix by scalars and addition of matrices (both $\O(d^2)$). While updating the $G$ component, we need to both add and subtract an outer product (both $\O(d^2)$), and while updating the $S$ component, we need to add and subtract a vector ($\O(d)$). At each step of the iteration, we must evaluate the RSS of the right and left models. To do this, we need 8 matrix vector products, each of which is $\O(d^2)$, and 4 vector inner products, each of which is $\O(d)$. Putting these parts together gives us a total run time of $\O(n \log n + n d^2)$ to find the best split point for a given node with $n$ observations and a $d$-dimensional feature space. \subsection{Early Stopping} \label{sec:earlystopping} As we will see in Section \ref{section:simulationstudies}, early stopping can prevent overfitting in the regression tree algorithm and the RF algorithm. Furthermore, as we discuss in Section \ref{section:interpretability}, it leads to well performing yet shallow trees that are much easier to understand and interpret. We use a one step look-ahead stopping criteria to stop the trees from growing to deep. Specifically, we first compute a potential split as outlined in the algorithm above. We then use cross validation to compute the $R^2$ increase of this split and only accept it, if the increase of the split is larger than the specified \lstinline[columns=fixed]{minSplitGain} parameter. A larger \lstinline[columns=fixed]{minSplitGain} thus leads to smaller trees. The precise description of this parameter can be found in Algorithm \ref{algo:EarlyStopping}. \begin{algorithm} \hspace*{\algorithmicindent} \textbf{Input:} Features: $X \in \mathbb{R}^{n\times d}$, \\\hspace*{\algorithmicindent}\hphantom{\textbf{Input: }}~ Dependent Outcome: $Y \in \mathbb{R}^{n}$, \\\hspace*{\algorithmicindent}\hphantom{\textbf{Input: }}~ Indexes of potential left Child: $L \subset \{1, \ldots, n\}$, \\\hspace*{\algorithmicindent}\hphantom{\textbf{Input: }}~ minSplitGain: $m \in \mathbb{R}$, \\\hspace*{\algorithmicindent}\hphantom{\textbf{Input: }}~ number of folds: $k \in \{2, \ldots, n\}$, \\\hspace*{\algorithmicindent}\hphantom{\textbf{Input: }}~ overfit penalty: $\lambda > 0$ \\ \hspace*{\algorithmicindent} \textbf{Output:} Boolean: TRUE if split should be implemented, FALSE otherwise \begin{algorithmic}[1] \Procedure{Check\_split}{} \State Partition $\{1, \ldots, n\}$ into $k$ disjoint subsets: $\{S_1, \ldots, S_k\}$. \For{$i$ in $\{1, \ldots, k\}$} \item[] \Comment{Predict the outcome without the split:} \State For $j \in S_i$ set \begin{align*} \hat Y^p_j = \begin{bmatrix}X_j \\1 \end{bmatrix} \left({\sum_{k \in \bar S_i} \begin{bmatrix}X_k \\1 \end{bmatrix} \begin{bmatrix}X_k^T&1\end{bmatrix} + \lambda \begin{bmatrix} \mathcal{I}_d & 0 \\ 0 & 0 \end{bmatrix}}\right)^{-1} \sum_{k \in \bar S_i} Y_k \begin{bmatrix} X_k \\ 1 \end{bmatrix}. \end{align*} \Comment{Predict the outcome with the split:} \State For $j \in S_i \cap L$ set \begin{align*} \hat Y^c_j = \begin{bmatrix}X_j \\1 \end{bmatrix} \left({\sum_{k \in \bar S_i\cap L} \begin{bmatrix}X_k \\1 \end{bmatrix} \begin{bmatrix}X_k^T&1\end{bmatrix} + \lambda \begin{bmatrix} \mathcal{I}_d & 0 \\ 0 & 0 \end{bmatrix}}\right)^{-1} \sum_{k \in \bar S_i\cap L} Y_k \begin{bmatrix} X_k \\ 1 \end{bmatrix}. \end{align*} \State For $j \in S_i \cap \bar L$ set \begin{align*} \hat Y^c_j = \begin{bmatrix}X_j \\1 \end{bmatrix} \left({\sum_{k \in \bar S_i\cap \bar L} \begin{bmatrix}X_k \\1 \end{bmatrix} \begin{bmatrix}X_k^T&1\end{bmatrix} + \lambda \begin{bmatrix} \mathcal{I}_d & 0 \\ 0 & 0 \end{bmatrix}}\right)^{-1} \sum_{k \in \bar S_i\cap \bar L} Y_k \begin{bmatrix} X_k \\ 1 \end{bmatrix}. \end{align*} \EndFor \State Compute the EMSE with and without split: \begin{align*} \mbox{RSS}^{c} = \sum_{i = 1}^n \Big(Y_i - \hat Y^c_i \Big)^2 &&\mbox{and}&& \mbox{RSS}^{p} = \sum_{i = 1}^n \Big(Y_i - \hat Y^p_i \Big)^2 \end{align*} \State Compute the total variation: $ \mbox{tV} = \sum_{i = 1}^n \left(Y_i - \bar Y\right)^2 $ \If{$(\mbox{RSS}^c - \mbox{RSS}^p)/\mbox{tV} > m$} \Return TRUE \Else \Return FALSE \EndIf \EndProcedure \end{algorithmic} \caption{Early Stopping: The One Step Look-Ahead Algorithm} \label{algo:EarlyStopping} \algcomment{For a set $S$ we define its compliment as $\bar S := \{i : 1\le i \le n\mbox{ and } i \not \in S \}$.} \end{algorithm} \section{Predictive Performance} \label{section:simulationstudies} It is well known that RF outperforms regression trees, and we have therefore implemented a version of RF that utilizes our new splitting algorithm. We call this Linear Random Forests (\textit{LRF}\xspace) and we demonstrate its predictive performance in the following section. A version of LRF is implemented in our \textbf{\textit{forestry}}\xspace package.\footnote{A version of \textbf{\textit{forestry}}\xspace is available at \url{https://github.com/soerenkuenzel/forestry.}} \subsection{Methods and Tuning} In this section, we compare the predictive power of LRF with five competitors: \begin{itemize} \item The random forest algorithm as implemented in the \textbf{\textit{ranger}}\xspace package \citep{wright2015ranger} and in the \textbf{\textit{forestry}}\xspace package. \item The Bayesian Additive Regression Trees (BART) algorithm as implemented in the \textbf{\textit{BART}}\xspace package\citep{chipman2010bart}. \item Local linear forests \citep{friedberg2018local} as implemented in the \textbf{\textit{grf}}\xspace package \citep{athey2019generalized}. % \item {The Rule and Instance based Regression Model presented in \citep{quinlan1992learning} as implemented in the \textbf{\textit{Cubist}}\xspace package.} \item Generalized Linear Models as implemented in the \textbf{\textit{glmnet}}\xspace package \citep{friedman2010regularization}. \end{itemize} In most real world prediction tasks, appliers carefully tune their methods to get the best possible performance. We believe that this is also important when comparing different methods. That is why we used the \textbf{\textit{caret}}\xspace package \citep{kuhn2008building} to tune the hyperparameters of all of the above methods. Specifically, we used the \textbf{\textit{caret}}\xspace package's adaptive random tuning over 100 hyperparameter settings, using 8 fold CV tuning repeated and averaged over 4 iterations. \subsection{Experiments} LRF is particularly well suited for picking up smooth signals. It can also behave like a linear model or like classical RFs. To demonstrate this adaptivity, we first analyze artificially generated examples. We will see that LRF automatically adapts to the smoothness of the underlying data generating distribution. In the second part of this study, we show the competitive performance of our estimator on real world data. \subsubsection{Adaptivity for the appropriate level of smoothness} We analyze three different setups. In the first setup, we use linear models to generate the data. Here we expect \textbf{\textit{glmnet}}\xspace to perform well and the default versions of RF as implemented in \textbf{\textit{ranger}}\xspace and \textbf{\textit{forestry}}\xspace to not perform well. In the second setup we use step functions. Here we expect RF and other tree-based algorithms to perform well and \textbf{\textit{glmnet}}\xspace to perform relatively worse. In the third setup, there are areas that are highly non-linear and other areas that are very linear. It will thus be difficult for both the default RF algorithm and \textbf{\textit{glmnet}}\xspace to perform well on this data set, but we expect the adaptivity of LRF to excel here. \begin{enumerate} \item \textbf{Linear Response Surface} \\ In \textbf{Experiment 1}, we start with a purely linear response surface. We simulate the features from a normal distribution and we generate $Y$ according to the following linear model: \begin{equation} \begin{aligned} &X \sim N(0,1) \in \mathbb{R}^{10},~\varepsilon \sim N(0,4)\\ &Y = f_L(X) + \varepsilon,\\ &f_L(X) = -0.47 X_2 -0.98 X_3 - 0.87 X_4 + 0.63 X_8 - 0.64 X_{10}. \end{aligned} \end{equation} \item \textbf{Step Functions}\label{sec:simstep}\\ Next, we are interested in the other extreme. In \textbf{Experiment 2}, we simulate the features from a 10-dimensional normal distribution distribution, $X \sim N(0,1) \in \mathbb{R}^{10}$ and we create a regression function from a regression tree with random splits, 50 leaf nodes, and randomly sampled response values between -10 and 10 and we call this function $f_S$. $Y$ is then generated according to the following model: \begin{align} &Y = f_S(X) + \varepsilon\\ &\varepsilon \sim N(0,1) \end{align} A specific description how $f_S$ was generated can be found in detail in Appendix \ref{sec:AppCreatestepResSurf}. \item \textbf{Linear Function with steps}\\ Finally, we look at a data set that exhibits both a linear part and a step-wise constant part. Specifically, we split the space into two parts and we combine the regression functions from \textbf{Experiment 1} and \textbf{Experiment 2} to create a new regression function as follows: \begin{align} &Y = \begin{cases} f_L(X)&\mbox{if } X_1 < .5\\ f_S(X) &\mbox{else} \end{cases} +\varepsilon\\ &\varepsilon \sim N(0,1). \end{align} \end{enumerate} The results of these simulations for a range of sample sizes can be found in Figure \ref{fig:MSE_simulation}. \begin{figure} \begin{center} \begin{subfigure}{.8\textwidth} \centering \includegraphics[width=\linewidth]{"varyn_Experiment_1"} \vspace*{-6mm} \caption{Experiment 1: Linear regression function.} \label{fig:Exp1} \end{subfigure} \begin{subfigure}{.8\textwidth} \centering \includegraphics[width=\linewidth]{"varyn_Experiment_2"} \vspace*{-6mm} \caption{Experiment 2: Step function.} \label{fig:Exp2} \end{subfigure} \begin{subfigure}{.8\textwidth} \centering \includegraphics[width=\linewidth]{"varyn_Experiment_3"} \vspace*{-6mm} \caption{Experiment 3: Partly linear and partly a step function.} \label{fig:sfig2} \end{subfigure} \end{center} \caption{Different levels of smoothness. In Experiment 1, the response surface is a linear function, in Experiment 2, it is a step function, and in Experiment 3, it is partly a step function and partly a linear function.} \label{fig:MSE_simulation} \end{figure} \subsubsection{Real World data sets} \label{sec:realworlddatasets} To analyze the behavior of these estimators on real data, we used a variety of data sets. Table \ref{tbl:dssummary} describes the metrics of the data sets that we have used and Table \ref{fig:realperformance} shows the performance of the different estimators. Of these datasets, Autos describes pricing data and many related features scraped from German Ebay listings, Bike describes Capital Bikeshare user counts and corresponding weather features. These datasets are available on Kaggle \citep{usedcars} and the UCI repository respectively \citep{bike}. The remaining datasets were lifted from Brieman's original regression performance section \citep{breiman2001random}, with the test setups altered only slightly. For the Boston, Ozone, and Servo datasets, we used 5-fold cross validation to estimate the Root Mesan Squared Error (RMSE), for the Abalone dataset, we took a test set of 50\%, and for the three Friedman simulations, we kept Brieman's original scheme using 2000 simulated test points. \subsection{Results} \begin{table}[ht] \begin{flushleft} \begin{tabular}{rrrrr} \hline name & ntrain & ntest & dim & numeric features \\ \hline Abalone & 2089 & 2088 & 11 & 11 \\ Autos & 1206 & 39001 & 12 & 6 \\ Bike & 869 & 16510 & 16 & 16 \\ Boston & 506 & & 9 & 9 \\ Friedman 1 & 1000 & 2000 & 11 & 11 \\ Friedman 2 & 1000 & 2000 & 5 & 5 \\ Friedman 3 & 1000 & 2000 & 5 & 5 \\ Ozone & 330 & & 9 & 9 \\ Servo & 167 & & 13 & 13 \\ \hline \end{tabular} \caption{Summary of real data sets.} \label{tbl:dssummary} \end{flushleft} \end{table} \begin{table}[H] \centering \includegraphics[width =1\textwidth]{performance.png} \caption{\textit{Estimator RMSE compared across real data sets}} \label{fig:realperformance} \end{table} The results shown in Figure \ref{fig:MSE_simulation} show the results for the different estimators on the simulated response surfaces detailed in Section \ref{section:simulationstudies}. As expected, we find that Regularized Linear Models (RLM) as implemented in the \textbf{\textit{glmnet}}\xspace package perform very well on Experiment 1 where the response is linear, while it performs poorly on Experiments 2 and 3. The default random forest estimators implemented for example in \textbf{\textit{ranger}}\xspace performs very well on Experiment 2, but it performs rather poorly on Experiment 1 and 3, as estimators which can exploit the linearity benefit greatly here. The estimators which can pick up linear signals (RLM, LLF, and LRF), perform nearly identically on Experiment 1, showing a tuned LRF can mimic the linear performance of a purely linear model such as RLM. Experiment 2 showcases a pure step function, in which smooth estimators such as RLM and LLF suffer, while RF and boosting algorithms such as BART excel. In this scenario, the performance of LRF now converges to match that of the purely random forest algorithms. Finally, in Experiment 3, the response surface is evenly distributed between smooth response values, and a step function. In this case, there are areas of weakness for both the smooth estimators and the RF estimators, but the adaptivity of LRF allows it to adapt to the differences across the response surface, and fit the appropriately different estimators on each portion. The results shown in Table \ref{fig:realperformance} are mixed, but display the adaptivity of LRF on datasets which are both linear as well as highly nonlinear. The ability to tune the nodesize in LRF allows for fits which mimic linear models in large nodes, and closely mimic CART fits in small node sizes. With fast tuning, this range of variation can be exploited to deliver an estimator which can adapt itself well to a variety of different response surfaces. This adaptivity results in an estimator which can exploit the presence of smooth signals very well and remain competitive over a wide range of response surfaces. \section{Interpretability} \label{section:interpretability} In this section, we want to show how linear aggregation can be used to create more interpretable trees and we demonstrate this with a large data set about voter turnout. We will show the usefulness of linear aggregation to better understand the heterogeneity in the data. We first outline the problem of estimating the Conditional Average Treatment Effect and summarize a few results from the literature before applying LRF to the data set. \subsection{Social Pressure and Voter Turnout Data Set} We use a data set from a large field experiment that has been conducted by \cite{GerberGreenLarimer} to measure the effectiveness of four different mailers on voter turnout. The data set contains 344,084 potential voters in the August 2006 Michigan statewide election with a wide range of offices and proposals on the ballot. The sample was restricted to voters that voted in the 2004 general election, because the turnout in the 2006 election was expected to be extremely low among potential voters who did not vote in the 2004 general election. The specific mailers can be found in \cite{GerberGreenLarimer} and we briefly describe the mailers as follows. Each mailer carries the message "DO YOUR CIVIC DUTY --- VOTE!" and applies a different level of social pressure. We present the mailers ordered by the amount of social pressure they put on the recipients. \begin{itemize} \item Civic Duty (CD): The Civic Duty mailer contains the least amount of social pressure and only reminds the recipient that "the whole point of democracy is that citizens are active participants in government". \item Hawthorne (HT): Households receiving the Hawthorne mailer were told "YOU ARE BEING STUDIED!" and it explains that voter turnout will be studied in the upcoming August primary election, but whether or not an individual votes "will remain confidential and will not be disclosed to anyone else." \item Self (SE): The Self mailer exerts even more pressure. It informs the recipient that "WHO VOTES IS PUBLIC INFORMATION!" and contains a chart containing the information of who voted in the past two elections within the household the letter was addressed to. It also contains a field for the upcoming August 2006 election and it promises that an updated chart will be sent to the households after the election. \item Neighbors (NE): The Neighbors mailer increases the social pressure even more and starts with the rhetorical question: "WHAT IF YOUR NEIGHBORS KNEW WHETHER YOU VOTED?". It lists the voting records not only of the people living in the household, but also of those people living close by and it promises to send an updated chart after the election. This treatment mailer implies that the voting turnout of the recipients are publicised to the people living close by and thereby creates the strongest social pressure. \end{itemize} The randomization was done on a household level. The set of all households was split into four treatment groups and a control group. Each of the four treatment groups contained about 11\% of all voters, while the control group contained about 56\% of all households. The data set also contains seven key individual-level covariates: gender, age, and whether or not the individual voted in the primary elections in 2000, 2002, 2004, or the general election in 2000 and 2002. We also derived three further covariates from the ones above. We believe that there are voters that generally have a high voting propensity, but still did not vote in every election. To enable a tree algorithm to discriminate potential voters with high voting propensity from those with a low one, we added a new feature that we called Cumulative Voting History (CVH). It is the number of times the voter has voted within the last five election before the 2004 general election. Similarly, we define the Cumulative Primary Voting History (CPVH) as the number of primary elections a voter has participated in between 2000 and 2004 and the Cumulative General election Voting History (CGVH) as the number of general elections a voter has participated in between 2000 and 2002. \cite{kunzel2019metalearners} analyze the effect of the Neighbors mailer while paying specific attention to uncovering the heterogeneity in the data. They find strong evidence of heterogeneous effects using the S-, T- and X-learner combined with random forests.\footnote{The S-, T- and X-learner are algorithms that can make use of a base algorithm such as random forests to estimate the CATE. We refer to \citep{kunzel2019metalearners} for a detailed description.} Specifically, they estimate the Conditional Average Treatment Effect (CATE), $$ \tau(x) = \mathbb{E}[Y(1) - Y(0)| X = x]. $$ Here, $Y(1) \in \{0,1\}$ is the outcome when a unit is treated (is assigned to receive the Neighbors mailer), $Y(0)$ is the outcome when the unit is in the control group, and $x$ is the vector of covariates of unit $x$. Estimating the CATE is useful for targeting treatment to individuals with a particularly strong effect. Policy makers could use these estimates to specifically target individuals with a large CATE. However, researchers are often interested in better understanding the underlying effects through plots and interpretable summaries of the estimators. This is, in particular, important for communication with subject experts and policy makers. \cite{kunzel2018causaltoolbox, kunzel2019metalearners}, for example, uncover the heterogeneity by using partial dependence plots and by looking at specific subgroups that have been defined through subject knowledge and exhaustive EDAs. They find that the estimated CATE varies with the CVH and it is suggested that the treatment effect is particularly low for potential voters who did not vote in any other election before the general election in 2004 and units that voted in all past elections. These are interesting insights, but it is unsatisfying that looking into these particular subgroups had to be motivated by subject knowledge or an EDA of an independent data set. Using a linear aggregation function in RF directly enables us to understand the underlying prediction function and we will show this in the following using the S-learner with random forests. We will see that we do not need to specify interesting subgroups and that the algorithm uncovers the heterogeneity automatically. \subsection{Making causal mechanisms more interpretable} \label{sec:SL_interpretability} Recall that in \cite{kunzel2019metalearners}, the S-Learner estimates the outcome by using all of the features and the treatment indicator, without giving the treatment indicator a special role, $$ \hat \mu(x, w) = \hat \mathbb{E}[Y | X = x, W = w]. $$ The predicted CATE for an individual unit is then the difference between the predicted values when the treatment-assignment indicator is changed from control to treatment, with all other features held fixed, \begin{equation} \label{eq:S-Learner_default_first_step} \hat \tau(x) = \hat \mu(x, 1) - \hat \mu(x, 0). \end{equation} We are making four crucial changes to this formulation of S-RF: \begin{enumerate} \item In the original formulation, the treatment is binary. In our data set, there are, however, four different treatments and we generalize the S-learner here to work with multiple treatments at the same time. Specifically, we encode a treatment indicator for each of the four treatments and we estimate the response function using all covariates and the treatment indicators as independent variables, $$ \hat \mu(x, w_{1}, \ldots, w_{4}) = \hat \mathbb{E}[Y | X = x, W_1 = w_1, \ldots, W_4 = w_4]. $$ The CATE for the CD mailer is then defined as $$ \hat \tau(x) = \hat \mu(x, 1, 0, 0 ,0) - \hat \mu(x, 0, 0, 0, 0) $$ and the treatment effects for the other mailers is defined analogue. \item In the usual S-RF algorithm, each tree contains several splits on the treatment indicators and the features. To compute the CATE of the NE mailer at $x$, the average of the leaf in which $(x,0,0,0,0)$ falls is subtracted from the average of the leaf in which $(x,0,0,0,1)$ falls.\footnote{ If $(x,0,0,0,0)$ falls into a leaf $L$ and on the path to the leaf there was no split on $w_4$, then also $(x,0,0,0,1)$ will fall into the same leaf and thus the predicted CATE will be 0 (c.f. \ref{eq:S-Learner_default_first_step}). This often leads to bias, and can be beneficial when the treatment effect is close to 0.} In our new formulation, we choose to linearly adapt in the four treatment indicators and we allow splits on all covariates but not the variables that encode the treatment assignment. In other words, the splits are done in such a way that a ridge regularized linear model that is linear in the four treatment indicators minimizes the overall RSS. Figure \ref{fig:RRFforSLearner} shows the first four trees of an S-RF estimator with linear aggregation in the treatment indicators. Specifically, we chose the overfit penalty, $\lambda$, to be $10^{-8}$ so that the splits are essentially linear and the coefficient of the linear models in each leaf can be interpreted as the average treatment effect in the particular leaf. \item Another important variation is that for each tree, we split the training set into two disjoint sets: A splitting set that is used to create the tree structure and an aggregation set that is used to compute the leaf aggregation. This property has been studied before under different names (\cite{scornet2015consistency, wager2015estimation}) to obtain better confidence intervals or prove mathematical properties about the RF algorithm. Here, we use it to add interpretability and to allow valid inference. Since the tree structure is independent of the aggregation set, the leaf estimates are based on a completely independent data set. Thus for a leaf, $L$, the regression coefficients become estimates for the average treatment effect for that leaf, \begin{equation} (\hat \tau, \hat b) = \argmin_{(\tau, b)} \sum_{i : X_i \in L} \left(Y_i - W_i^T \tau - b\right)^2 +\lambda \|\tau\|_2^2. \end{equation} Here $W_i \in \{0,1\}^4$ is the four dimensional vector containing the indicator for the treatment group of unit $i$ (e.g., $W=(0,0,0,0)$ encodes the control group, $W=(1,0,0,0)$ encodes the CD group and $W=(0,1,0,0)$ encodes the HT group). $X_i$ and $Y_i$ are the features and the observed outcome of unit $i$ and thus $\{i: X_i \in L\}$ is the set of all indices of all units that fall in leaf $L$. $(\hat \tau, \hat b)$ is plotted in the leaves of each node in Figure \ref{fig:RRFforSLearner}. Take, for example, the leaf on the very left in the first tree. It contains units that have never voted in a primary ($\mbox{CPVH} < 0.5$) and who have also not voted in the 2002 general election ($\mbox{g2002} = \mbox{no}$). The structure and thus the splits of this tree is based on a set that is disjoint to the subset of the training set that is used to estimate the coefficients. Thus $\hat b$ (in the plot \lstinline[columns=fixed]{untr BL}) is an estimate for the voting propensity of voters falling into this leaf that were in the control group and the $\hat \tau_3$ (in the plot \lstinline[columns=fixed]{TE(SE)}) is an estimate for the treatment effect of the Self mailer. \item If we trained the trees in the random forests algorithm without any stopping criteria other than a minimal node size, we would still get very deep trees and they might even perform very well in the standard random forest aggregation. We noticed, however, that for a single tree predictor, training until purity leads to overfitting and makes it very hard to learn a lot about the underlying causal effects, since one cannot really understand trees with several hundred or even thousands of nodes. We then use the one step look-ahead stopping criteria introduced in Section \ref{sec:earlystopping}. \end{enumerate} \subsection{Software Solutions} Regression trees with linear aggregation can be much shallower and therefore more interpretable without sacrificing predictive performance. However, we warn to not blindly use only one tree and instead to use several. In the example below, we created several trees. For each tree, we randomly split the training data into two parts: the splitting and the averaging set. Since this partitioning is different for each tree, we find that there is some variation in the trees and practitioners should consider multiple trees to draw rubust conclusions. To aid researchers in analyzing regression trees, we implemented a plotting function in the \textbf{\textit{forestry}}\xspace package that is fast, easy to use, and flexible. It enables researchers to quickly look at many trees in a RF algorithm. Figure \ref{fig:RRFforSLearner} is created using this package by varying the \lstinline[columns=fixed]{tree.id} parameter to look at different trees. We recommend using a smaller \lstinline[columns=fixed]{minSplitGain} to draw even more personalized conclusions. \begin{lstlisting} rft <- forestry(x = x, y = y, minSplitGain = .005, linear = TRUE, overfitPenalty = 1e-8, linFeats = 1:4, splitratio = .5) plot(forest, tree.id = 1) \end{lstlisting} \subsection{Interpretation of the results} Let us take a look at the four trees in Figure \ref{fig:RRFforSLearner}. These trees are not exactly the same, however, they still describe a very similar and therefore consistent behavior. First of all, we notice that the primary voting history (CPVH) appears to be the most important variable. However, age, the 2002 general election turnout, and the overall voting history (CVH) appear to be useful features carrying a lot of information about the voting propensity of the voters and the magnitude of the turnout. In each tree, there is a leaf node of potential voters who never or very rarely voted in the five elections before the 2004 general election. Unsurprisingly, all of these units have a very low base line estimate for voting in the 2004 primary election (the outcome of interest) when they are not treated. A bit more surprising, however, is that the treatment effects of the four mailers appear to be rather small for these units. This contradicts our intuition that for a group of potential voters with a low baseline, there is a lot of space for improvement and one might expect large treatment effects. We also find that in each of the trees there is a subgroup of units that have voted in at least two out of the three recorded primary elections. As expected, for these units, the voting propensity is very high even if they do not receive any of the mailers. The treatment effects are very large as well, which is again a bit surprising. After all, for a potential voter $i$ who would vote if they did not receive any of the mailers ($Y(0) = 1$), the individual treatment effect, $D_i = Y_i(1) - Y_i(0)$, can only be $0$ or $-1$. It is also interesting to see that there are a lot of splits on age at around 53 years. Older voters tend to have a much higher baseline turnout of approximately $10\%$. The treatment effects here are very heterogeneous: All trees suggest that among voters who voted in at least one primary ($\mbox{CPVH} > .5$ or $\mbox{CVH} > 2.5$),\footnote{Since there have been only two general elections reported, a potential voter with $\mbox{CVH} > 2.5$ implies that they must have voted in at least one primary.} the treatment effects of the different mailers appear to be pretty similar for the two age groups. On the contrary, for potential voters who voted in one general election, but never in a primary, the trees suggest that the treatment effect of the SE and NE mailers is larger for younger voters. \begin{figure} \begin{center} \begin{subfigure}[b]{.495\textwidth} \centering \includegraphics[height=\linewidth]{"ridge_tree_1"} % % % \end{subfigure} \begin{subfigure}[b]{.495\textwidth} \centering \includegraphics[height=.78\linewidth]{"ridge_tree_2"} % % % \end{subfigure} \vspace*{6mm} \begin{subfigure}[t]{.495\textwidth} \centering \includegraphics[height=\linewidth]{"ridge_tree_4"} % % % \end{subfigure} \begin{subfigure}[t]{.495\textwidth} \centering \includegraphics[height=.78\linewidth]{"ridge_tree_3"} % % % \end{subfigure} \end{center} \caption{The first four trees of the S-Learner as described in Section \ref{sec:SL_interpretability}. The first row in each leaf contains the number of observations in the aggregation set that fall into the leaf. The second part of each leaf displays the regression coefficients. \lstinline[columns=fixed]{untr BL} stands for untreated Base Line and it can be interpreted as the proportion of units that fall into that leaf who voted in the 2004 primary election. \lstinline[columns=fixed]{TE(CD)} can be interpreted as an estimate for the ATE of the CD mailer within the leaf. The color are chosen to represent the size of the treatment effect for the neighbors treatment. Eg., red represents leaves with a low treatment effect for the Neighbors mailer, TE(NE). } \label{fig:RRFforSLearner} \end{figure} \begin{comment} {\color{blue} \subsection{Making X-RF interpretable} * only optimized for predicting the voter turnout, but not the CATE that's why we see splits that don't really lead to different CATE estimates, but very different voting propensities in the baseline (e.g., see two groups furthes to the right). * Estimating the CATE it is not always interesting to just have a low EMSE, but also a an interpetable result * Two ways of making it more interpretable: 1.) W as a feature as in the S-Learner and then the coefficient of the W matters 2.) using a single tree in the second level of the X-Learner } \end{comment} \section{Conclusion} \label{section:conclusion} In this paper, we have proposed three main changes to the core CART algorithm and explored their consequences in several examples. Specifically, our changes were focused on three main additions: introducing linear aggregation functions for prediction in the leaf nodes of the estimator, modifying the CART splitting algorithm to optimize the linear aggregation functions on each node resulting from the split, and adding a stopping criteria which limits further node creation when splitting would not increase the $R^2$ by a predetermined percentage. In order to explore these contributions, we analyzed the increase in predictive power over a range of data sets in Section \ref{section:simulationstudies}. Here we also highlighted the adaptivity of LRF as an estimator by using a wide range of node sizes and regularization parameters. We then noted how the linear aggregation leads to estimators that are much simpler to understand in Section \ref{section:interpretability}. We utilized the stopping criteria to build trees that have high performance as well as offer inference through both the selected splits and resulting regression coefficients. We have already implemented a version of gradient boosting in the \textbf{\textit{forestry}}\xspace package, and we are very interested in evaluating the effect of linear aggregation on gradient boosting. We also believe that LRF can be less biased than the usual versions of RF, and we wonder whether it would improve nonparametric confidence interval estimation. Finally, we believe that the regression coefficients could be very informative and we would like to study statistical tests that can be used to determine whether the estimated coefficients for the leaves are statistically provably different. \section*{Acknowledgment} We thank the Office of Naval Research (ONR) Grant N00014-17-1-2176 and the Berkeley Institute for Data Science. \bibliographystyle{apalike} \input{linearAggr.bbl} \newpage
{'timestamp': '2019-06-20T02:02:31', 'yymm': '1906', 'arxiv_id': '1906.06463', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06463'}
arxiv
\section{Introduction} Clustering of large scale data is an active area of research in deep learning and big-data domain. It has gained significant attention as labeling data is costly and anomalous in real-world data. For example, getting ground truths for satellite imagery is difficult. A few disaster management applications suffer from that. Nevertheless, clustering algorithms have been studied widely. But, its performance drops drastically when it encounters high dimensional data. Also, their time-complexity increases dramatically. To handle curse of dimensionality, original data space is projected into low dimensional manifold and clustering is applied using them with standard algorithms on that new manifold. However, this approach fails when number of samples reaches to millions or billions. To cope up with the situation, several deep architecture based clustering approaches have been proposed in recent years. Most of them are \emph{CNN} or \emph{feed-forward} based auto encoder architecture~\cite{DEC2015,DEPICT,JULE2016,DCAE_clustering}, embedded with simple, \emph{k-means} like, clustering algorithm. These models have the tendency of learning features of the dataset and their corresponding cluster labels jointly. They employ a heuristic for clustering and use it along with the reconstruction loss function for training the model. Therefore, the bottleneck is to get initial clusters to accommodate clustering objective function in the loss function. The intuitive choice for the above problem is to train well-known auto-encoder model with reconstruction loss to generate new embedding subspace. Then, best known clustering algorithm is employed on that subspace to generate clusters~\cite{DEPICT}. Thereafter, new model is ready to train using two components of the loss function. However, another choice is to employ \emph{k-means} like algorithm to get initial cluster labels. Other than auto-encoders, there are stacked convolutional layer based deep architecture exist~\cite{CCNN2018}. However, they pre-trained their model with large-scale \emph{ImageNet} dataset in order to use clustering objective function. It is to be noted that if the model architecture is similar to well-known classifiers architecture like \emph{AlexNet}~\cite{Alexnet}, \emph{VGG}~\cite{VGGnet}, \emph{ResNet}~\cite{resnet}, \emph{DenseNet}~\cite{denseNet} then learned parameters on those layers are eventually transferred. However, pre-training is only an approach of initializing the model parameters as this can not fit the data distribution of the dataset under consideration. Also, it is speeding up the convergence of iterations for real time training. To put it in a nutshell, the existing unsupervised deep approaches have following pitfalls: 1) training the network from scratch, and 2) obtaining initial cluster labels. To address the above mentioned pitfalls, we propose a deep clustering algorithm which does not require any initial cluster labels. In this paper, we consider the following two issues: \begin{enumerate} \item Can we utilize features generated from well-known pre-trained deep networks to develop clustering algorithm such that computational cost and memory requirement be reduced? \item Can we perform clustering of these feature vectors under the same deep learning framework in absence of any information on labeling of these data? \end{enumerate} In recent years, \emph{AlexNet}~\cite{Alexnet}, \emph{VGG}~\cite{VGGnet}, \emph{ResNet}~\cite{resnet}, \emph{DenseNet}~\cite{denseNet} receive high popularity in \emph{ImageNet} challenge. Thus, it motivates us to choose one of the networks which have the capability of extracting good feature representatives. However, these networks are supervised. Hence, they can not be used in the scenario where no label is present. In this paper, we propose a loss function which enable the unsupervised labeling of data using these networks. For the purpose of illustration, we have chosen typically \emph{VGG-16} with batch normalization in our experiments. Also, we replace all fully connected and following layers by a single fully connected layer followed by batch normalization and \emph{ReLU} layers. Our loss function is formulated using following entropy based clustering heuristics: \begin{enumerate} \item For a true partitioning, low entropy is desirable. This demands highly skewed probability distribution for a sample to be assigned to a cluster. \item Any random partitioning than the actual one should lead to higher entropy, given the class distribution is not heavily skewed. For example, when all the feature vectors form trivially a single cluster, the distribution becomes highly skewed. In this case, though the entropy is zero, it does not reflect any meaningful information regarding partitioning. \end{enumerate} There is a trade-off between these two factors. We propose a loss function for the network which takes into account these two factors for a given number of clusters. To summarize, the major contributions of our work are: \begin{enumerate} \item We propose a simple but effective approach to reuse well-known supervised deep architectures in an unsupervised learning paradigm. \item We formulate an entropy based loss function to guide clustering and deep representation learning in a single framework that can be transferred to other tasks and datasets. \item Our experimental results show that the proposed framework is consistent and competitive irrespective of different datasets. \item Finally, we use this network in remote sensing domain to provide segmentation for multi-spectral images. \end{enumerate} \section{Approach} \subsection{Notation} We represent an image set with $n$ images by $X=\{x_{1}, \cdots, x_{n}\}$ where each sample $x_{i}$ represents an image of resolution $n_{1} \times n_{2}$. The clustering task is to group image set $X$ into $K$ clusters $Y=\{y_{1}, \cdots y_{K}\}$. Using embedding function $f_{\theta}:X \rightarrow Z$, we transform raw image samples $X$ into its embedding subspace $Z=\{z_{1}, \cdots, z_{n}\}$ where $z_{i}\in \mathbb{R}^{d}$. We estimate posterior probability $\mathbb{P}(Y|Z)$ and use Eq.~\ref{eq:label} to assign each of the samples to one of $K$ cluster labels. \begin{equation} \label{eq:label} \hat{k}_{x_{i}}=\underset{k}{\argmax}~\mathbb{P}(y_{k}|z) \end{equation} However, we reuse well-known \emph{CNN} network architecture to transform raw images into its embedded subspace. It is well-known that transfer learning expedites the process of learning new distribution. Hence, we may transfer learned weights of those networks in the beginning. Additionally, \emph{softmax} function is used to learn $\mathbb{P}(Y|Z)$. Section~\ref{architecture} describes detailed architecture of our model. \subsection{Unsupervised Training Criterion} {\bf Motivation}: Designing a loss function for unsupervised classification is highly influenced by the concept of ``structuredness" and ``diversity" of the dataset. Data can be well predicted if it belongs to a uniform distribution. In information theory, this ``structuredness" is quantified by low entropy. On the other hand, multi class environment is characterized by ``diversity" in data, which increases entropy of the dataset. A clustering algorithm becomes vulnerable when it produces highly skewed partition. Thereby, it witnesses low entropy. Therefore, it is desirable that an algorithm should report low entropy for a partition only when it is non-skewed.\\ {\bf Deep Network Scenario}: We discuss this issue in the context of deep architecture. In general, deep networks are trained by the dataset which is divided into mini-batches. They accumulate losses incurred by each mini-batch and update the parameters of the network by incorporating the gradient of the loss function. We consider that a data is well classified by the network when the probability that it corresponds to a particular class out of $K$ classes, is near about 1. Therefore, it estimates low entropy. To accomplish it, classification entropy ($H_{\Phi}$) is designed. However, skewed partitioning is reduced by enforcing ``diversity" in the mini-batch. The underlying intuition is that more the number of distinct representatives the architecture experiences in a mini-batch, better it learns the grouping. To accomplish it, class entropy ($H_{\Psi}$) is designed. Therefore, the aim is to maximize the class entropy while minimizing classification entropy.\\ {\bf Mathematical Formulation}: In our model, we have feature extraction layers and classification layers. Feature extraction layers provide the mapping from input image space to feature embedded space $f_{\theta_{1}}:X \rightarrow Z$. However Classification layers provide the mapping of feature embedded space to cluster labels space, i.e.$f_{\theta_{2}}:Z \rightarrow R$. We are interested in knowing the probability that the $m^{th}$ sample belongs to $l^{th}$ class, which is denoted as $p_{ml}$. i.e. \begin{equation} p_{ml}=P(y_{m}=l|R)=\frac{exp({r_{ml}})}{\sum_{j=1}^{K}exp({r_{mj}})} \end{equation} We design our loss function ($L$) for unsupervised classification with aforesaid motivation as follows : \begin{equation} \label{eq:loss} \begin{array}{lll} L&=&\lambda H_{\Phi}-H_{\Psi}\\ \\ H_{\Phi}&=&-\frac{1}{M}\sum_{m=1}^{M}\sum_{l=1}^{K}p_{ml}\log_{}(p_{ml})\\ \\ H_{\Psi}&=&-\sum_{l=1}^{K}p_{l}\log_{}(p_{l})\\ \\ p_{l}&=&\frac{\sum_{m=1}^{M}(p_{ml})}{\sum_{l=1}^{K}\sum_{m=1}^{M}(p_{ml})}\\ \\ \end{array} \end{equation} where $\lambda$ weighs loss function $L$. \subsection{Implementation Bottleneck} In our work, mini-batch size is a prime factor for successful implementation of our proposition. It is important that network should see all possible cluster representatives in one go. To maintain this criterion, mini batch size should be sufficiently large. However, with the constrained size of {\emph GPU}, it could be hard to train network with a large batch-size. Therefore, Algorithm~\ref{algo-1} may not be reliable for assigning efficient cluster labels to the input samples. To deal with such bottleneck, we employ a strategy to increase the mini-batch size. We can store losses, incurred by $t-1$ mini-batches using only $K+1$ variable. Therefore, $t^{th}$ mini-batch will accumulate previous semi processed losses and generate loss for all the samples that network visits till now. Then, it back propagates the accumulated loss in the network. With this strategy, it is possible to execute our algorithm even in the \emph{GPU} with constrained memory. Algorithm~\ref{algo-2} depicts the strategy. \begin{algorithm} \SetKwInOut{Input}{Input} \SetKwInOut{Output}{Output} \Input{\\X=Collection of Image Data\\ K=Target number of cluster\\ B= Batch Size} \Output{\\$Y^{*}$ : image labels \\ $\theta^{*}$ : CNN parameters} Initialize $\theta$, optimizer=(\emph{SGD}, lr=0.0001)\\ \Repeat{converged} { \ForEach{minibatch} { Compute $\mathbb{P}(Y|Z)$ by forward propagation using $\theta$.\\ compute {\em Loss= $\lambda H_{\Phi}-H_{\Psi}$} using Eq.\ref{eq:loss}.\\ Update $\theta$ by back propagation. } } \caption{Joint optimization on $y$ and $\theta$} \label{algo-1} \end{algorithm} \begin{algorithm} \SetKwInOut{Input}{Input} \SetKwInOut{Output}{Output} \Input{\\X=Collection of Image Data\\ K=target number of cluster\\ M= Number of samples in each mini-batch \\ t=number of mini-batches in one pass} \Output{\\$Y^{*}$ : image labels \\ $\theta^{*}$ : CNN parameters} Initialize $\theta$, \emph{SGD}=(lr,momentum),mini-batch-size=0\\ \Repeat{converged} { \ForEach{minibatch ($B$)} { mini-batch-size+=size of $B$.\\ Compute $\mathbb{P}(Y|Z)$ by forward propagation using $\theta$.\\ \eIf{t mini-batches visited} { $h_{\phi}=h_{\phi}+\sum_{m=1}^{M}\sum_{l=1}^{K}p_{ml}\log_{}(p_{ml})$\\ $H_{\Phi}=h_{\phi}/$mini-batch-size\\ $h_{\psi}=h_{\psi}+\sum_{m=1}^{M}(p_{ml})$\\ $p_{l}=\frac{(h_{\psi}))}{\sum_{k=1}^{K}(h_{\psi})}$\\ $H_{\Psi}=-\sum_{l=1}^{K}p_{l}\log_{}(p_{l})$\\ {\em Loss= $\lambda H_{\Phi}-H_{\Psi}$}\\ Update $\theta$ by back propagation.\\ mini-batch-size=0 } { $h_{\phi}=h_{\phi}+\sum_{m=1}^{M}\sum_{l=1}^{K}p_{ml}\log_{}(p_{ml})$ \\ $h_{\psi}=h_{\psi}+\sum_{m=1}^{M}(p_{ml})$\\ store $h_{\phi}$, $h_{\psi}.$ } } } \caption{Joint optimization on $y$ and $\theta$ for large size of minibatch beyond the available \emph{GPU} capacity } \label{algo-2} \end{algorithm} \section{Experiments} In this section, we first compare \emph{RECAL} with state-of-the-art clustering methods on several bench-mark image datasets. Then, we run \emph{k-means} clustering algorithm on our learned deep representations. Finally, we analyze the performance of \emph{RECAL} model on unsupervised segmentation task on multi-spectral \emph{LISS-IV} images. \subsection{Alternative Clustering Models} We compare our model with several baseline and deep models, including k-means, normalized cuts (NCuts)~\cite{N-Cut_2000}, self-tuning spectral clustering (SC-ST)~\cite{SC-ST_NIPS04}, large-scale spectral clustering (SC-LS)~\cite{SC-LS15},~ graph degree linkage-based agglomerative clustering (AC-GDL)~\cite{AC-GDL12}, agglomerative clustering via path integral (AC-PIC)~\cite{AC-PIC_13}, local discriminant models and global integration (LDMGI)~\cite{Local-Discriminant-Models_Global-Integration_10}, NMF with deep model (NMF-D) \cite{Deep-semi-NMF14}, task-specific clustering with deep model (TSC-D) \cite{TSC-D15}, deep embedded clustering (DEC)\cite{DEC2015}, joint unsupervised learning (JULE)~\cite{JULE2016} and deep embedded regularized clustering (DEPICT)~\cite{DEPICT} for unsupervised clustering. \begin{table*}[!htb] \center \caption{Description of Datasets} \begin{tabular}{lccccccc} \hline Dataset & MNIST-full & USPS & COIL-20 & COIL-100 & U-Mist & CMU-PIE & YTF \\ \hline \#Samples & 70000 & 9298 & 1440 & 7200 & 575 & 2856 & 10000 \\ \#Categories & 10 & 10 & 20 & 100 & 20 & 68 & 41 \\ Image Size & 28$\times$ 28 & 16 $\times$ 16 & 128 $\times$ 128 & 128 $\times$ 128 & 112 $\times$ 92 & 32 $\times$ 32 & 55 $\times$ 55 \\ \hline \end{tabular} \label{tab:datasets} \end{table*} \subsection{Dataset} We have chosen different types of datasets to show consistent behavior of our model towards accomplishing clustering. As, we are examining unsupervised models, we concatenate training and test datasets whenever applicable. \emph{MNIST-full}~\cite{MNIST}: It contains monochrome images of handwritten digits. \emph{USPS}\footnote{\url{https://www.cs.nyu.edu/~roweis/data.html}}:~It is a handwritten digits dataset from the \emph{US} postal services ~\emph{COIL-20} and \emph{COIL-100}~\cite{COIL}: They are databases of multi-view objects. \emph{UMist}~\cite{UMist}: It includes face images of 20 people.~\emph{CMU-PIE}~\cite{cmu-pie}: It includes face images of 4 different facial expressions.~\emph{Youtube-Face (YTF)~\cite{YTF}}: We follow an experimental set up for this dataset as in ~\cite{JULE2016,DEPICT}. We select the first 41 subjects of \emph{YTF} dataset. Faces inside images are first cropped and then resized to 55 by 55 sizes. A brief description of these datasets is provided in Table~\ref{tab:datasets}. \subsection{Evaluation Metric} We follow current literature which uses normalized mutual information (NMI)~\cite{NMI} as evaluation criteria for clustering algorithms. \emph{NMI} evaluates the similarity between two labels of same dataset in normalized form (0,1). However, $0$ implies no correlation and 1 shows perfect correlation between two labels. We use predicted labels (by the model) and the ground truth labels to estimate \emph{NMI}. \subsection{Implementation Details} \label{architecture} We adopt feature extraction layers of \emph{VGG16}~\cite{VGGnet} with batch normalization and use the weights of the original network trained with \emph{ImageNet} as a starting point. However, we consider a fully connected layer followed by a batch normalization and a \emph{ReLU} layer for unsupervised labeling (equivalent classification layers). We stacked classification layers on top of feature extraction layers of \emph{VGG16}. For \emph{USPS} dataset, we decapitate feature layers of \emph{VGG16} to get an output of size $1 \times 1$, otherwise, we use all feature layers of \emph{VGG16}. Consequently, we normalize the image intensities using Eq.~\ref{eq:normalize} where ($\mu$) and ($\sigma$) are mean and standard deviation of the given dataset, respectively. Moreover, we use stochastic gradient discent (SGD) as our optimization method with the learning rate=0.0001 and momentum=0.9. The weights of fully connected layer is initialized by \emph{Xavier} approach~\cite{xavier}. Pre-trained models may not generate useful features to obtain a good clustering for the target dataset. Hence, fine-tuning is required. Pre-trained models not only expedite the process of convergence in fine-tuning but, it helps to provide a global solution instead of a local one. \begin{equation} \label{eq:normalize} \hat{x}=\frac{x-\mu}{\sigma} \end{equation} \subsection{Quantitative Comparison We show \emph{NMI} for every method on various datasets. Experimental results are averaged over 3 runs. We borrowed best results from either original paper or \cite{JULE2016} if reported on a given dataset. Otherwise, we put dash marks (-) without reporting any result. We report our results in two parts: 1) the clustering labels predicted by our network after training it for several epochs; 2) the clustering results obtained by running \emph{k-means} clustering algorithm on learned representation by our network. Table~\ref{tab:NMI} reports the clustering metric, normalized mutual information \emph{(NMI)}, of the comparative algorithms along with \emph{RECAL} on the aforementioned datasets. We have transferred weights of feature layers of \emph{VGG-16} (trained with \emph{ImageNet}) to the feature layers of \emph{RECAL} and classification layers are initialized with \emph{Xavier}'s approach. As shown, \emph{RECAL} perform competitively and consistently. It should be noted that hyper parameter tuning using labeled samples is not feasible always in real world clustering task. \emph{DEPICT} has already shown an approach of not using supervised signals. However, their approach is dependent on other clustering algorithm. Hence, our algorithm is an independent and significantly better clustering approach for handling real world large scale dataset. Interestingly, clustering results on learned representatives produce better outcome as shown in Table~\ref{tab:clusteringNMI}. It indicates that our method can learn more discriminative feature representatives compared to image intensity. Notably, our learned representation is much better than \emph{JULE}~\cite{JULE2016} for multi-viewed objects and digit dataset where their clustering result by their model, produce perfect \emph{NMI} on \emph{COIL-20}. However, our method performs poorly on face datasets. Also, Table~\ref{tab:NMI} suggests that learned features are much distinctive compared to the features obtained by {\emph VGG-16} model trained with {\emph ImageNet} We have executed our code on a machine with \emph{GeForce GTX 1080 Ti} GPU. \section{Multi-spectral image segmentation} For illustrating usefulness of this approach, we consider application of this method for unsupervised labeling of pixels in an image. We experiment with satellite multi-spectral images. We have observed that very tiny patches may be a representative of a pure class. With this assumption, we split the pre-processed satellite image into small patches (e.g, $32 \times 32$ or $16 \times 16$ or $8 \times 8$) with strides of $k$ (e.g, $16$ or $8$) pixels. However, we decapitate the feature layers of \emph{VGG-16} from its tail such that size of the feature (not output of whole model) for an input patch of $8 \times 8$ is $1 \times 1$. Otherwise, there is no change in the network architecture. We do our experiments with other large size patches on this decapitated version of the network. \subsection{Description of Dataset} For our experiments, we have used images captured by Linear Imaging Self Scanner \emph{LISS-IV} sensor of \emph{RESOURCESAT-2}. Table~\ref{tab:liss4} illustrates the specifications of \emph{LISS-IV} sensor and scene details. It includes sensors, acquisition dates and other specification of the Indian Remote Sensing Resourcesat-2 mission. We have taken two scenes for our experiment. Scene information is shown in Table~\ref{tab:scene_info}. Both scenes are captured by the same \emph{LISS-IV} sensor on different dates. As field investigation is a crucial task and requires expertise, we have used Microsoft\textregistered~BingTM maps for validation of our experiment. \begin{table}[htb!] \caption{Specification of \emph{LISS-IV} sensor and scene information} \begin{tabular}{ll} \hline \textbf{Description of Parameter} & \textbf{Details} \\ \hline Agency & NRSC \\ Satellite & Resourcesat 2 \\ Sensor & LISS-IV \\ Swath (km) & 70 \\ Resolution (m) & 5.8 \\ Repetivity (days) & 5 \\ Qunatisation & 10-bit \\ No of Bands & 3 \\ Spectral Bands ($\mu$) & \begin{tabular}[c]{@{}l@{}}Band 2 (0.52 - 0.59 )\\ Band 3 (0.62 - 0.68 )\\ Band 4 (0.77 - 0.86 ) \end{tabular}\\\hline \end{tabular} \label{tab:liss4} \end{table} \begin{table}[htb!] \center \caption{Description of the study area} \begin{tabular}{lll} \hline \textbf{Scene} & \textbf{Parameters} & \textbf{Details}\\\hline \multirow{3}{*}{Scene-1} & Acquisition Date & 25-NOV-2011 \\ & Scene Center Lattitude & 22.426371 N \\ & Scene Center Longitude & 88.169285 E \\ \hline \multirow{3}{*}{Scene-2} & Acquisition Date & 10-APR-2017 \\ &Scene Center Lattitude & 23.615814 N \\ & Scene Center Longitude & 87.400460 E \\ \hline \end{tabular} \label{tab:scene_info} \end{table} \subsection{Description of Scene} Scene-1 covers an approximately 21 km $\times$ 23 km rectangle region located surrounding the city of Kolkata in West Bengal, India. This region mainly contains built-up areas, bare lands, vegetation (man made gardens, play grounds, small agricultural land etc), and water body. We have cropped small regions from the original data. On the other hand, Scene-2 is the whole dataset. It covers nearly 71 km $\times$ 86 km rectangle region located surrounding the place of Ranugunj, Durgapur, Panagarh, Dubrajpur etc. in West Bengal, India. However, this scene contains large hierarchy of classes. It contains built-up area, bare lands, vegetation (forest area, agricultural land, man made gardens etc.), water-body, coal mining area, etc. Moreover, built-up area covers a large area in Scene-1, whereas vegetation region predominates in Scene-2. \subsection{Pre-processing of dataset} In general, a sensor captures Earth's surface radiance and this response is quantized into $n$-bit values. It is commonly called Digital Number (\emph{DN}). However, to convert calibrated (\emph{DN}s) to at-sensor radiance, two meta-parameters are used: known dynamic-range limits of the instrument and their corresponding pre-defined spectral radiance values. Meta files are provided by the satellite data provider. This radiance is then converted to top-of-atmosphere (\emph{ToA}) reflectance by normalizing for solar elevation and solar spectral irradiance. \subsection{Results} In this experiment, we separately trained the model with the patches from Scene-1 and Scene-2 for $K=10$. Lets call it model-1 and model-2 respectively. We observe each segmented output from model-1 and model-2 separately. However, we check cross-dataset segmentation output which measures the robustness of the network. i.e, We use model-1 to generate the segmentation for scene-2 and vice versa. Notably, number of patches from Scene-1 and Scene-2 are approx. 0.2 million and 2.2 million respectively. Models took nearly 1-1.5 days for training. For Scene-1, our model has detected built-up area, vegetation and water-body distinctively among 10 classes. However, model-2 identifies vegetation, water body and wetland area. This is to be noted that model-2 predicts vegetation into three distinct classes. This result might be indicator of three types of vegetation in that location. We have shown models' predictions and Microsoft\textregistered~BingTM maps of the scenes in Fig~\ref{fig:scene_prediction_with_ccudata},~\ref{fig:scene_prediction_with_ranigunjdata} and Fig~\ref{fig:bings1},~\ref{fig:bings2}, respectively. Notably, Fig~\ref{fig:waterbody_s1} and Fig~\ref{fig:crosswetland_s2} show different types of region for a particular class in two scenes: built-up area in Scene-1 and wetland in Scene-2. Many of previous researches~\cite{built-up1,built-up2,built-up3} have reported similar characteristics of built-up area with wetland, farmland, etc. Similar false alarms persist in our experiment too. We use same color symbol for showing same cluster number in both scene-1 and scene-2 for the same model in Fig~\ref{fig:scene_prediction_with_ccudata}, \ref{fig:scene_prediction_with_ranigunjdata}. \subsubsection{Analysis} Experimental results reflect the generalization of model-1 and model-2 in various classes in Fig~\ref{fig:scene_prediction_with_ccudata}, \ref{fig:scene_prediction_with_ranigunjdata}. For example, Fig \ref{fig:waterbody_s1}, \ref{fig:water-body} provide visually similar structure for water-body. We prepare a validation set using Microsoft\textregistered~BingTM maps of that region. It shows 97\% accuracy in identifying water-body in validation set. Taking visual consensus of two models, we are able to identify a few such structures for vegetation and wet land. For Scene-2 following pair of figures describe visually similar structure: (Fig~\ref{fig:crossveg1_s2}, Fig~\ref{fig:vegetation1_s2}), (Fig~\ref{fig:crossveg2_s2}, Fig~\ref{fig:vegetation2_s2}) and (Fig~\ref{fig:crosswetland_s2}, Fig~\ref{fig:wetland_s2}). Similarly, (Fig~\ref{fig:veg2_s1}, Fig~\ref{fig:forest1}) and (Fig~\ref{fig:veg3_s1}, Fig~\ref{fig:forest2}) reveal similar visual structure in Scene-1. We measure consensus of two models using {\em Jaccard similarity} score as shown in Eq~\ref{eq:consensus}. \begin{equation} \label{eq:consensus} \text{\emph{ Jaccard similarity}}=\frac{\abs{M1 \cap M2}}{\abs{M1 \cup M2}} \end{equation} where $M1$ and $M2$ represent pixels predicted by model-1 and model-2, respectively. Table-\ref{tab:confusion_matrix_s1} and Table-\ref{tab:confusion_matrix_s2} show the \emph{Jaccard similarity} score for various identified classes in scene-1 and scene-2, respectively. We have shown upper triangular matrix in Table~\ref{tab:confusion_matrix_s1},~\ref{tab:confusion_matrix_s2} due to the symmetric nature of this score. We follow similar naming convention for denoting a particular class for a specific scene as shown in Fig~\ref{fig:scene_prediction_with_ccudata}, \ref{fig:scene_prediction_with_ranigunjdata}. However, further study is required for validating different classes with ground truth data, such as vegetation, wet land, built up areas, etc. \begin{table}[htb!] \centering \caption{{\em Jaccard similarity} score for different classes (as shown in Fig~\ref{fig:scene_prediction_with_ccudata}, \ref{fig:scene_prediction_with_ranigunjdata}) for scene-1} \begin{tabular}{ll|lllll|} \cline{3-7} & & \multicolumn{5}{c|}{Model-2} \\ \cline{3-7} & & cV1S1 & cV2S1 &cB2S1 &cB1S1 & cWBS1\\ \hline \multicolumn{1}{|c|}{\multirow{5}{*}{\begin{sideways}Model-1\end{sideways}}} & V1S1 & \textbf{0.545} & 0.004 & 0.004& 0.002 &0.004\\ \multicolumn{1}{|l|}{} & V2S1 & &\textbf{0.299} & 0.015& 0.014&0.001 \\ \multicolumn{1}{|l|}{} & B1S1 & & &\textbf{0.243} & 0.105&0.007\\ \multicolumn{1}{|l|}{} & B2S1 & & & & \textbf{0.211} & 0.004\\ \multicolumn{1}{|l|}{} & WBS1 & & & & & \textbf{0.721} \\ \hline \end{tabular} \label{tab:confusion_matrix_s1} \end{table} \begin{table}[htb!] \centering \caption{{\em Jaccard similarity} score for different classes (as shown in Fig~\ref{fig:scene_prediction_with_ccudata}, \ref{fig:scene_prediction_with_ranigunjdata}) for scene-2} \begin{tabular}{ll|lllll|} \cline{3-7} & & \multicolumn{5}{c|}{Model-1} \\ \cline{3-7} & & cV2S2 & cV1S2 &cV3S2 &cWBS2 & cWLS2 \\ \hline \multicolumn{1}{|c|}{\multirow{5}{*}{\begin{sideways}Model-2\end{sideways}}} & V1S2 & \textbf{0.624} & 0.004&0.000 & 0.008 &0.000\\ \multicolumn{1}{|l|}{} & V2S2 & & \textbf{0.186}&0.001 &0.059 & 0.000\\ \multicolumn{1}{|l|}{} & V3S2 & & & \textbf{0.315}&0.002&0.031\\ \multicolumn{1}{|l|}{} & WBS2 & & & & \textbf{0.556} & 0.011\\ \multicolumn{1}{|l|}{} & WLS2 & & & & & \textbf{0.570}\\ \hline \end{tabular} \label{tab:confusion_matrix_s2} \end{table} \begin{table*}[!htb] \centering \caption{Clustering performance of different algorithms on image datasets based on normalized mutual information (NMI).} \begin{tabular}{lccccccc} \hline Dataset & MNIST-full & USPS & COIL-20 & COIL-100 & U-Mist & CMU-PIE & YTF \\ \hline k-means & 0.500 & 0.447 & 0.775 & 0.822 & 0.609 & 0.549 & 0.761 \\ N-cuts & 0.411 & 0.675 & 0.884 & 0.861 & 0.782 & 0.411 & 0.742 \\ SC-ST & 0.416 & 0.726 & 0.895 &0.858 & 0.611 & 0.581 & 0.620 \\ SC\_LS & 0.706 & 0.681 & 0.877 & 0.833 & 0.810 & 0.788 & 0.759 \\ AC-GDL & 0.844 & 0.824 & 0.937 & 0.933 & 0.755 & 0.934 & 0.622 \\ AC-PIC & 0.940 & 0.825 & 0.950 & 0.964 & 0.750 & 0.902 & 0.697 \\ LDMGI &0.802 &0.563 & - & - & -& -& -\\ \hline\hline NMF-D & 0.152 & 0.287 & 0.648 & 0.748 & 0.467 & 0.920 & 0.562 \\ TSC-D & 0.651 & - & - & - & - & - & - \\ DEC & 0.816 & 0.586 & - & - & - & 0.924 & 0.446 \\ JULE-SF & 0.906 & 0.858 & 1.000 & 0.978 & 0.880 & 0.984 & 0.848 \\ JULE-RC & 0.913 & 0.913 & 1.000 & 0.985 & 0.877 & 1.000 & 0.848 \\ DEPICT & 0.917 & 0.927 & - & - & - & 0.974 & 0.802 \\\hline \hline RECAL & 0.852 & 0.913 & 0.880 & 0.831 & 0.694 & 0.627 & 0.779 \\\hline \end{tabular} \label{tab:NMI} \end{table*} \begin{table*}[!htb] \centering \caption{Clustering performance (\emph{NMI}) for \emph{k-means} algorithms using learned representations by different models as inputs} \begin{tabular}{llccccccc} \hline \multicolumn{1}{l}{Method} & Model & MNIST-full & USPS & COIL-20 & COIL-100 & UMist & CMU\_PIE & YTF \\\hline \multirow{3}{*}{k-means} & \emph{RECAL} & 0.885 & \textbf{0.913} & \textbf{0.948} & \textbf{0.919} &0.675 & 0.715 & 0.809 \\ & \emph{JULE} & \textbf{0.927} & 0.758 & 0.926 & \textbf{0.919} & \textbf{0.871} & \textbf{0.956} & \textbf{0.835}\\ & \emph{VGG-16} & 0.182 &0.014 & 0.769 &0.792 &0.576 &0.302 &0.167 \\\hline \end{tabular} \label{tab:clusteringNMI} \end{table*} \begin{figure} \centering \includegraphics[width=0.4\textwidth, height=0.3\textheight]{images/ccu_resize.jpg} \caption{Scene-1, Bing Hybrid Map} \label{fig:bings1} \end{figure} \begin{figure} \centering \includegraphics[width=0.4\textwidth, height=0.3\textheight]{images/ranigunj_bing_map.jpg} \caption{Scene-2, Bing Hybrid Map} \label{fig:bings2} \end{figure} \begin{figure*} \centering \begin{tabular}[l]{lllll} \centering \begin{subfigure}[b]{0.18\textwidth} \includegraphics[width=\textwidth]{images/ccu_class_1.png} \caption{water body, Scene-1 \centering(WBS1)} \label{fig:waterbody_s1} \end{subfigure}& \begin{subfigure}[b]{0.18\textwidth} \includegraphics[width=\textwidth]{images/ccu_class_2.png} \caption{built-up1, Scene-1 \centering(B1S1)} \label{fig:built-up_s1} \end{subfigure}& \begin{subfigure}[b]{0.18\textwidth} \includegraphics[width=\textwidth]{images/ccu_class_4.png} \caption{built-up2, Scene-1 \centering(B2S1)} \label{fig:veg1_s1} \end{subfigure} & \begin{subfigure}[b]{0.18\textwidth} \includegraphics[width=\textwidth]{images/ccu_class_7_1.png} \caption{vegetation, Scene-1 \centering(V1S1)} \label{fig:veg2_s1} \end{subfigure}& \begin{subfigure}[b]{0.18\textwidth} \includegraphics[width=\textwidth]{images/ccu_class_9_1.png} \caption{vegetation, Scene-1 \centering(V2S1)} \label{fig:veg3_s1} \end{subfigure} \\ \begin{subfigure}[b]{0.18\textwidth} \includegraphics[width=\textwidth]{images/ccu_cross_ranigunj_class_1.png} \caption{waterbody, Scene-2 \centering(cWBS2)} \label{fig:crosswaterbody_s2} \end{subfigure}& \begin{subfigure}[b]{0.18\textwidth} \includegraphics[width=\textwidth]{images/ccu_cross_ranigunj_class_2.png} \caption{wet-land, Scene-2 \centering(cWLS2)} \label{fig:crosswetland_s2} \end{subfigure}& \begin{subfigure}[b]{0.18\textwidth} \includegraphics[width=\textwidth]{images/ccu_cross_ranigunj_class_4.png} \caption{vegetation, Scene-2 \centering(cV1S2)} \label{fig:crossveg1_s2} \end{subfigure}& \begin{subfigure}[b]{0.18\textwidth} \includegraphics[width=\textwidth]{images/ccu_cross_ranigunj_class_7_1.png} \caption{vegetation, Scene-2 \centering(cV2S2)} \label{fig:crossveg2_s2} \end{subfigure}& \begin{subfigure}[b]{0.18\textwidth} \includegraphics[width=\textwidth]{images/ccu_cross_ranigunj_class_9_1.png} \caption{vegetation, Scene-2 \centering(cV3S2)} \label{fig:crossveg3_s2} \end{subfigure} \end{tabular} \caption{First and second rows show segmentation results of scene-1 and scene-2 respectively. The result set is generated using model-1. }\label{fig:scene_prediction_with_ccudata} \end{figure*} \begin{figure*} \centering \begin{tabular}[l]{lllll} \centering \begin{subfigure}[b]{0.18\textwidth} \includegraphics[width=\textwidth]{images/model2_ranigunj_class_7.png} \caption{water body, Scene-2 \centering(WBS2)} \label{fig:waterbody_s2} \end{subfigure}& \begin{subfigure}[b]{0.18\textwidth} \includegraphics[width=\textwidth]{images/model2_ranigunj_class_3.png} \caption{vegetation, Scene-2 \centering(V1S2)} \label{fig:vegetation2_s2} \end{subfigure}& \begin{subfigure}[b]{0.18\textwidth} \includegraphics[width=\textwidth]{images/model2_ranigunj_class_10.png} \caption{Vegetation, Scene-2 \centering(V2S2)} \label{fig:vegetation1_s2} \end{subfigure}& \begin{subfigure}[b]{0.18\textwidth} \includegraphics[width=\textwidth]{images/model2_ranigunj_class_6_.png} \caption{Vegetation, Scene-2 \centering(V3S2)} \label{fig:vegetation3_s2} \end{subfigure}& \begin{subfigure}[b]{0.18\textwidth} \includegraphics[width=\textwidth]{images/model2_ranigunj_class_9.png} \caption{Wetland, Scene-2 \centering(WLS2)} \label{fig:wetland_s2} \end{subfigure}\\ \begin{subfigure}[b]{0.18\textwidth} \includegraphics[width=\textwidth]{images/model2_cross_class_7.png} \caption{water-body, Scene-1 \centering(cWBS1)} \label{fig:water-body} \end{subfigure}& \begin{subfigure}[b]{0.18\textwidth} \includegraphics[width=\textwidth]{images/model2_cross_class_3.png} \caption{Vegetation, Scene-1 \centering(cV1S1)} \label{fig:forest1} \end{subfigure}& \begin{subfigure}[b]{0.18\textwidth} \includegraphics[width=\textwidth]{images/model2_cross_class_10.png} \caption{vegetation, Scene-1 \centering(cV2S1)} \label{fig:forest2} \end{subfigure}& \begin{subfigure}[b]{0.18\textwidth} \includegraphics[width=\textwidth]{images/model2_cross_class_6.png} \caption{built-up, Scene-1 \centering(cB1S1)} \label{fig:builtup3} \end{subfigure}& \begin{subfigure}[b]{0.18\textwidth} \includegraphics[width=\textwidth]{images/model2_cross_class_9.png} \caption{built-up, Scene-1 \centering(cB2S1)} \label{fig:wetland} \end{subfigure} \end{tabular} \caption{First and second rows show segmentation results of scene-2 and scene-1 respectively. The result set is generated using model-2.} \label{fig:scene_prediction_with_ranigunjdata} \end{figure*} \section{Conclusion} In this paper, we have proposed an approach to transform supervised \emph{CNN} classifier architecture into an unsupervised clustering model. We address ``structuredness" and ``diversity" of the dataset to migrate from supervised to unsupervised paradigm. Our model jointly learns discriminative embedding subspace and cluster labels. The major strength of this approach is : scalability and re-usability. Experimental results show that \emph{RECAL} performs competitively for real-world clustering task. However, it learns representation better compared to the existing approaches for non-face image datasets. We have shown segmentation as one of the application by our proposed method in remote sensing domain. To achieve this, we split the original image into small patches and get label for each of them. Then, they are combined to get the segmentation of the whole image. We qualitatively observe that this model is able to detect vegetation, water-body, wet-land, built-up area separately. We also provide the power of transferring learned representation across separate scenes in this work. However, built-up area has confusion with wetland and vegetation in cross-dataset segmentation task. It is probably due to the similar characteristics among these classes which is an innate problem in the underlying dataset. We also observe that training of the proposed network is fast. It took about roughly 30 hours to process more than 2 million patches in our experiments in \emph{GeForce GTX 1080 Ti GPU}. This strongly indicates the property of scalability for our model. {\small \bibliographystyle{ieee}
{'timestamp': '2019-06-18T02:05:23', 'yymm': '1906', 'arxiv_id': '1906.06480', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06480'}
arxiv
\section*{Introduction} Recent work [1] suggests that recurrent ``neural network" models of several types perform better than sequential models in acquiring and processing hierarchical structure. Indeed, recurrent networks have achieved state-of-the-art results in a number of natural language processing tasks, including named-entity recognition [2], language modeling [3], sentiment analysis [4], natural language generation [5], and beyond. \bigskip \noindent The hierarchical structure associated with natural languages is often modeled as some variant of context-free languages, whose languages may be defined over an alphabet $\Sigma$. These context-free languages are exactly those that can be recognized by pushdown automata (PDAs). Thus it is natural to ask whether these modern natural language processing tools, including simple recurrent neural networks (RNNs) and other, more advanced recurrent architectures, can learn to recognize these languages. \bigskip \noindent The computational power of RNNs has been studied extensively using empirical testing. Much of this research [8], [9] focused on the ability of RNNs to recognize simple context-free languages such as $a^nb^n$ and $a^nb^mB^mA^n$, or context-sensitive languages such as $a^nb^nc^n$. Related works [10], [11], [12] focus instead on Dyck languages of balanced parenthesis, which motivates some of our methods. Gated architectures such as the Gated Recurrent Unit (GRU) and Long Short-Term Memory (LSTM) obtain high accuracies on each of these tasks. While simpler RNNs have also been tested, one difficulty is that the standard hyperbolic tangent activation function makes counting difficult. On the other hand, RNNs with ReLU activations were found to perform better, but suffer from what is known as the ``exploding gradient problem" and thus are more difficult to train [8]. \bigskip \noindent Instead of focusing on a single task, many researchers have studied the broader {\it{theoretical}} computational power of recurrent models, where weights are not trained but rather initialized to recognize a desired language. A celebrated result [6] shows that a simple recurrent architecture with 1058 hidden nodes and a saturated-linear activation $\sigma$ is a universal Turing Machine, with: $$ \sigma(x) = \begin{cases}0, & x < 0\\x, & 0 \le x \le 1\\1, & x > 1\end{cases} $$ However, their architecture encodes the whole input in its internal state and the relevant computation is only performed after reading a terminal token. This differs from more common RNN variants that consume tokenized inputs at each time step. Furthermore, the authors admit that were the saturated-linear activation to be replaced with the similar and more common sigmoid or hyperbolic tangent activation functions, their methodology would fail. \bigskip \noindent More recent work [7] suggests that single-layer RNNs with rectified linear unit (ReLU) activations and softmax outputs can also be simulated as universal Turing Machines, but this approach again suffers from the assumption that the entire input is read before computation occurs. \bigskip \noindent Motivated by these earlier theoretical results, in this report we seek to show results about the computational power of recurrent architectures actually used in practice - namely, those that read tokens one at a time and that use standard rather than specially chosen activation functions. In particular we will prove that, allowing infinite precision, RNNs with just one hidden layer and ReLU activation are at least as powerful as PDAs, and that GRUs are at least as powerful as deterministic finite automata (DFAs). Furthermore, we show that using infinite edge weights and a non-standard output function, GRUs are also at least as powerful as PDAs. \section{Simple RNNs} Let a {\it{simple RNN}} be an RNN with the following architecture: \begin{align*} h_t &= f(W_xx_t + W_hh_{t - 1} + b_h)\\ o_t &= W_oh_t + b_o \end{align*} where $o_i \in \mathbb{R}$ for all $i$, for some chosen activation function $f$, usually the ReLU or the hyperbolic tangent functions. We assume that the inputs are {\it{one-hots}} of a given set of symbols $\Sigma$, vectors of length $|\Sigma|$ where each element but one is $0$ and the remaining element is $1$. \bigskip \noindent Say that an RNN {\it{accepts}} an input $w$ of length $n$ if after passing $w$ through the RNN, its final output $o_n$ belongs to a predetermined set $S \subseteq \mathbb{R}$, for which membership can be tested in $O(1)$ time. Let the $S$-{\it{language}} of an RNN consist exactly of all inputs that it accepts given set $S$. \bigskip \noindent In practice, the inputs and hidden nodes of an RNN are stored as numbers with finite precision. Including this restriction, we show the following result: \bigskip \noindent {\bf{Theorem 1.1}}. For every language $L \subseteq \Sigma^*$, $L$ is regular if and only if $L$ is the $S$-language of some finite precision simple RNN. \bigskip \noindent {\it{Proof.}} We begin with the ``if" direction. Suppose we are given some simple RNN and set $S \subseteq \mathbb{R}$. It suffices to show that there exists a DFA that accepts the $S$-language of this RNN. Assume that the RNN has $m$ hidden nodes, and that these hidden nodes are precise up to $k$ bits. Then there are exactly $2^{mk}$ possible hidden states for the RNN. Construct the following DFA with: \begin{itemize} \item set of $2^{mk}$ states $Q = \{q_h:h\ \text{is a possible hidden state of the RNN}\}$ \item alphabet $\Sigma$ \item transition function $\delta$ where $\delta(q_h, x) = q_{f(W_xx + W_hh + b_h)}$ \item initial state $q_{h_0}$ \item set of accepting states $F = \{q_h|W_hh + b_o \in S\}$ \end{itemize} It's clear that after reading the first $n$ inputs of a word $w$, the current state of this DFA is $q_{h_n}$, which immediately completes the proof of this direction. \bigskip \noindent For the ``only if" direction, suppose we have a DFA $D = (Q, \Sigma, \delta, q_0, F)$ with corresponding language $L$. We will construct a simple RNN whose inputs are one-hotted symbols from $\Sigma$, with ReLU activation function $f(x) = \text{max}(0, x)$, and with $|Q||\Sigma|$ hidden nodes whose $\{0\}$-language is $L$. \bigskip \noindent The RNN has three layers: the first layer (input layer) has $|\Sigma| + |Q||\Sigma|$ nodes; the second layer (hidden layer) has $|Q||\Sigma|$ nodes; and the third layer (output layer) has one node. For the $|\Sigma|$ nodes in the input layer associated with the one-hot of the current symbol, label each node with its corresponding symbol from $\Sigma$. Label the $|Q||\Sigma|$ hidden nodes (in both the first and second layers) with all $|Q||\Sigma|$ symbol-state combinations $(x, q)$ for $x \in \Sigma$ and $q \in Q$. \bigskip \noindent For every $x \in \Sigma$, connect the node in the input layer with label $x$ to all nodes in the hidden layer with labels $(x, q)$ for any $q \in Q$ with edges with weight $1$. For all $(x, q) \in \Sigma \times Q$, connect the node in the input layer with label $(x, q)$ to all nodes in the hidden layer with labels $(x', q')$ where $\delta(q, x') = q'$ with edges also of weight $1$. Finally, for all $(x, q) \in \Sigma \times Q/F$, connect the node in the hidden layer with label $(x, q)$ to the single node in the output layer with an edge of weight $1$. \bigskip \noindent Each of the hidden nodes are initialized to $0$ except a single hidden node with label $(x, q_0)$ for a randomly chosen $x \in \Sigma$, which is initialized to $1$. To complete the description of the RNN, we set $b_h = -1$ and $b_o = 0$. We claim that the following invariant is maintained: after reading some word, suppose the current state of $D$ is $q$. Then after reading the same word, the hidden nodes of the RNN would all be equal to $0$ except for one node with label $(x, q)$ for some $x \in \Sigma$, which would equal $1$. \bigskip \noindent We prove the claim by induction on the length of the inputted word $n$. The base case of $n = 0$ is trivial. Now assume that after reading a word of length $n$ the current state of $D$ is $q$, and after reading that same word all hidden nodes of the RNN are equal to $0$ except one node with label $(x, q)$ for some $x \in \Sigma$, which is equal to $1$. If the next symbol is $x'$, then the current state of $D$ would be $q'$ where $\delta(q, x') = q'$. For the RNN, the input layer will have exactly two $1$s, namely the node with label $x'$ and the node with label $(x, q)$. Since all edges have weight $1$, that means that before adding $b_h$ or applying $f$ the maximum value a node in the hidden layer can take on is $2$. For this to occur it must be connected to both the nodes in the input layer with value $1$, and thus by definition its label must be $(x', \delta(q, x')) = (x', q')$. By integrality every other node in the hidden layer will take on a value of at most $1$, so after adding $b_h = -1$ and applying $f$ we easily see that the invariant is maintained. \bigskip \noindent Utilizing this invariant it is clear that upon reading a word $w \in L$ the RNN will output $0$, and upon reading a word $w \not\in L$ it will output $1$. Thus $L$ is precisely the $\{0\}$-language of the RNN and the theorem is proven.\qed \bigskip \noindent {\bf{Discussion 1.2}}. This result shows that simple RNNs with finite precision are exactly as computationally powerful as DFAs. In terms of reducing the size of the hidden layer constructed in the proof of the ``only if" direction, it seems likely that $|Q||\Sigma|$ is optimal since $\delta$ is defined on $|Q||\Sigma|$ inputs and needs to be captured fully by the RNN. \bigskip \noindent Removing the finite precision stipulation unsurprisingly increases the capabilities of RNNs. It is natural to now ask whether these simple RNNs can recognize more complicated $S$-languages, and indeed the answer is affirmative. Thus we shift our focus to context-free languages. We begin with some preliminaries: \bigskip \noindent The {\it{Dyck language}} $D_n$ consists of all words over the size $2n$ alphabet $\Sigma = \bigcup\limits_{i = 1}^{n}\{(_i, )_i\}$ that correspond to a balanced string of $n$ types of parentheses. We also define the set of proper prefixes $$ P_n = \{w|w \not\in D_n, \exists v \in \Sigma^*\ \text{such that}\ wv \in D_n\} $$ so that any word in $P_n$ is the prefix of a word in $D_n$ but is itself unbalanced. We proceed with a motivating theorem: \bigskip \noindent {\bf{Theorem 1.3}} (Chomsky-Sch$\ddot{\text{u}}$tzenberger Theorem). Any context-free language $L$ can be written as $L = D_n \cap R$ for some $n \in \mathbb{Z}^{+}$ and regular language $R$ after a suitable relabeling. \bigskip \noindent {\it{Proof.}} The interested reader may find a proof in [13]. \qed \bigskip \noindent Thus it makes sense to focus on constructing sets $S$ and simple RNNs whose $S$-language is $D_n$. Indeed, since $D_n = g^{-1}(D_2)$ for some homomorphism $g$, we start by focusing on $D_2$, in some sense the ``hardest" context-free language. \bigskip \noindent The critical idea is to ``memorize" an input in the binary representation of some rational number, simulating a stack. Indeed, consider associating with any word $w = w_1w_2\dots w_m \in D_2$ a state $s \in \mathbb{Q}$, defined as follows: \begin{align*} s_0 &= 0\\ s_t &= \begin{cases}s_{t - 1}/2, & w_t = (_1\\s_{t - 1}/2 + 1/2, & w_t = (_2\\2s_{t - 1}, & w_t =\ )_1\\2s_{t - 1} - 1, & w_t =\ )_2\end{cases} \end{align*} Consider the word $(_2(_1)_1(_2(_1)_1)_2)_2$. The evolution of the state as the word is read symbol by symbol is given by $$ 0, 0.1, 0.01, 0.1, 0.11, 0.011, 0.11, 0.1, 0 $$ This example makes it clear that this notion of state accurately captures all the relevant information about words in $P_2 \cup D_2$. \bigskip \noindent The difficulty in capturing this notion of state in a RNN is that the constant to multiply $s_{t - 1}$ by changes depending on the input (it can be either $2$ or $1/2$ in our example above). Thus storing $s_t$ in a single hidden node is impossible. Instead, we use two hidden nodes. Below, we generalize from $D_2$ to $D_n$. \bigskip \noindent Ignoring the output layer for now, consider the simple RNN defined by \begin{align*} h_0 &= [0\ \ 0]^T\\ h_t &= \text{ReLU}(W_xx_t + W_hh_{t - 1}) \end{align*} where the inputs $x$ are $2n \times 1$ one-hots of the symbols in $\Sigma$ (the alphabet of $D_n$) in the order $(_1, (_2, \dots, (_n, )_1, )_2, \dots, )_n$ and the hidden states have dimension $2 \times 1$ where \begin{align*} W_{x} &= \begin{bmatrix}2(2n + 1)^{-1} & 4(2n + 1)^{-1} & \dots & 2n(2n + 1)^{-1} & -2n - 1 & -2n - 1 & \dots & -2n - 1\\-2n - 1 & -2n - 1 & \dots & -2n - 1 & -2 & -4 & \dots & -2n\end{bmatrix}\\ \\ W_{h} &= \begin{bmatrix}(2n + 1)^{-1} & (2n + 1)^{-1}\\2n + 1 & 2n + 1\end{bmatrix} \end{align*} As before, associate with each word $w = w_1w_2\dots w_m \in D_n$ a state $s \in \mathbb{Q}$ now satisfying \begin{align*} s_0 &= 0\\ s_t &= \begin{cases}(2n + 1)^{-1}s_{t - 1} + 2i(2n + 1)^{-1}, & w_t =(_i \\(2n + 1)s_{t - 1} - 2i, & w_t =\ )_i\end{cases} \end{align*} for all $i \in \{1, 2, \dots, n\}$. \bigskip \noindent This is similar to the state we defined before, though now generalized to $D_n$ and also with intentionally present blank space inserted between the digits in base $2n + 1$. We will show the following invariant: \bigskip \noindent {\bf{Lemma 1.4}}. Given an input word $w \in P_n \cup D_n$, we have $h_t = [s_t\ \ 0]^T$ or $h_t = [0\ \ s_t]^T$ for all $t$. \bigskip \noindent {\it{Proof}}. We proceed by induction on $t$. The base case of $t = 0$ is trivial. Now, suppose $w_{t + 1} = (_i$ for some $i \in \{1, 2, \dots, n\}$ and assume without loss of generality that $h_t = [s_t\ \ 0]^T$. Then $$ h_{t + 1} = \text{ReLU}(W_xx_{t + 1} + W_hh_t) = \text{ReLU}\left([2i(2n + 1)^{-1}\ \ -2n - 1]^T + [(2n + 1)^{-1}s_t\ \ (2n + 1)s_t]^T\right) $$ Now, since $w \in P_n \cup D_n$ we have that $s_t \in [0, 1)$ for any $t$, which follows immediately from the stack interpretation of the base $2n + 1$ representation of $s_t$. Thus $\text{ReLU}(-2n - 1 + (2n + 1)s_t) = 0$ and so $$ h_{t + 1} = [(2n + 1)^{-1}s_t + 2i(2n + 1)^{-1}\ \ 0]^T = [s_{t + 1}\ \ 0]^T $$ as desired. Alternatively, suppose $w_{t + 1} = )_i$ for some $i \in \{1, 2, \dots, n\}$. Again, assume without loss of generality that $h_t = [s_t\ \ 0]^T$. Then $$ h_{t + 1} = \text{ReLU}(W_xx_{t + 1} + W_hh_t) = \text{ReLU}\left([-2n - 1\ \ -2i]^T + [(2n + 1)^{-1}s_t\ \ (2n + 1)s_t]^T\right) $$ The fact that $w \in P_n \cup D_n$ clearly implies that $(2n + 1)s_t - 2i \ge 0$ and so we have that $$ h_{t + 1} = [0\ \ (2n + 1)s_t - 2i]^T = [0\ \ s_{t + 1}]^T $$ which completes the induction.\qed \bigskip \noindent A pictorial example of this RNN is depicted below for $n = 2$: \begin{center} \tikzstyle{vertex}=[circle, draw] \begin{tikzpicture}[transform shape] \node[vertex](r1) at (-2, 2) {\ $ h_{1, t}\ \ $}; \node[vertex](r2) at (2, 2) {$ \ h_{2, t}\ \ $}; \node[vertex](q1) at (-7,-2) {$\ x_{1, t}\ \ $}; \node[vertex](q2) at (-5,-2) {$\ x_{2, t}\ \ $}; \node[vertex](q3) at (-3,-2) {$\ x_{3, t}\ \ $}; \node[vertex](q4) at (-1,-2) {$\ x_{4, t}\ \ $}; \node[vertex](h1) at (3,-2) {$ h_{1, t - 1} $}; \node[vertex](h2) at (7,-2) {$ h_{2, t - 1} $}; \begin{scope}[every path/.style={-}, every node/.style={inner sep=1pt}] \draw (r1) -- node [pos=0.5, anchor=south east] {$0.4$} (q1); \draw (r1) -- node [pos=0.5, anchor=south east] {$0.8$} (q2); \draw (r1) -- node [pos=0.7, anchor=north west] {$-5$} (q3); \draw (r1) -- node [pos=0.5, anchor=north east] {$-5$} (q4); \draw (r1) -- node [pos=0.75, anchor=south west] {$0.2$} (h1); \draw (r1) -- node [pos=0.65, anchor=south west] {$0.2$} (h2); \draw (r2) -- node [anchor=south east, pos=0.8] {$-5$} (q1); \draw (r2) -- node [anchor=south east, pos=0.8] {$-5$} (q2); \draw (r2) -- node [pos=0.5, anchor=south east] {$-2$} (q3); \draw (r2) -- node [pos=0.75, anchor=north west] {$-4$} (q4); \draw (r2) -- node [pos=0.25, anchor=south west] {$5$} (h1); \draw (r2) -- node [pos=0.5, anchor=south west] {$5$} (h2); \end{scope} \end{tikzpicture} \end{center} \bigskip \noindent Thus we have found an efficient way to store $s_t$. Now it's clear that for any $w = w_1w_2\dots w_m \in P_n$ we have $s_m > 0$ and for any $w = w_1w_2\dots w_m \in D_n$ we have $s_m = 0$, so it is tempting to try and add a simple output layer to this RNN and claim that its $\{0\}$-language is $D_n$. However, this is most likely impossible to accomplish. \bigskip \noindent Indeed, consider the word $w = )_1(_1$. We have that $s_2 = 0$ for this word, but $w \not\in D_n$. Furthermore, consider the word $w = (_2)_1(_1)_2$. We have that $s_t \ge 0$ for all $t$ and $s_4 = 0$ for this word, yet $w \not\in D_n$. Hence we must be able to flag when an inappropriate closing parenthesis appears in an input and retain that information while reading the rest of the input. To that end, consider the following simple RNN, an example of which can be found in Appendix A.1: \begin{align*} h_0 &= [0\ \ 0\ \ 0\ \ 0\ \ 0\ \ 0]^T\\ h_t &= \text{ReLU}(W_xx_t + W_hh_{t - 1})\\ o_t &= W_oh_t \end{align*} where again the inputs $x$ are $2n \times 1$ one-hots of the symbols in $\Sigma$ (the alphabet of $D_n$) in the order $(_1, (_2, \dots, (_n, )_1, )_2, \dots, )_n$ and the hidden states have dimension $6 \times 1$ where \begin{align*} W_{x} &= \begin{bmatrix}2(2n + 1)^{-1} & 4(2n + 1)^{-1} & \dots & 2n(2n + 1)^{-1} & -2n - 1 & -2n - 1 & \dots & -2n - 1\\-2n - 1 & -2n - 1 & \dots & -2n - 1 & -2 & -4 & \dots & -2n\\0 & 0 & \dots & 0 & 2 & 4 & \dots & 2n\\0 & 0 & \dots & \dots & \dots & \dots & \dots & 0\\-2n - 1 & -2n - 1 & \dots & -2n - 1 & -3 & -5 & \dots & -2n - 1\\0 & 0 & \dots & \dots & \dots & \dots & \dots & 0\end{bmatrix}\\ \\ W_{h} &= \begin{bmatrix}(2n + 1)^{-1} & (2n + 1)^{-1} & 0 & 0 & 0 & 0\\2n + 1 & 2n + 1 & 0 & 0 & 0 & 0\\-2n - 1 & -2n - 1 & 0 & 0 & 0 & 0\\0 & 0 & 1 & 1 & 0 & 0\\2n + 1 & 2n + 1 & 0 & 0 & 0 & 0\\0 & 0 & 0 & 0 & 1 & 1\end{bmatrix}\\ \\ W_o &= [1\ \ 1\ \ 1\ \ 1\ \ 1\ \ 1]^T \end{align*} Because the last four elements of the first two rows of $W_h$ are all equal to $0$ and otherwise the first two rows of $W_x$ and $W_h$ are the same as before, it is clear that Lemma 1.4 still applies in some form for the new simple RNN. Indeed, denoting $$ h_t = [h_{1, t}\ \ h_{2, t}\ \ h_{3, t}\ \ h_{4, t}\ \ h_{5, t}\ \ h_{6, t}]^T $$ we have \bigskip \noindent {\bf{Corollary 1.5}}. With respect to a word $w \in P_n \cup D_n$, we have $[h_{1, t}\ \ h_{2, t}] = [s_t\ \ 0]$ or $[h_{1, t}\ \ h_{2, t}] = [0\ \ s_t]$ for all $t$. \bigskip \noindent We proceed with an important lemma: \bigskip \noindent {\bf{Lemma 1.6}}. For any word $w \in P_n$, there is a unique $x \in \{)_1, )_2, \dots, )_n\}$ such that $wx \in P_n \cup D_n$. \bigskip \noindent {\it{Proof}}. This immediately follows from the definition of a balanced string. Indeed, if $s$ is the state associated with $w$ then this unique $x$ is given by $$ x = )_i \Longleftrightarrow \frac{2i}{2n + 1} \le s < \frac{2i + 1}{2n + 1} $$\qed \bigskip \noindent We are now ready to show the following: \bigskip \noindent {\bf{Lemma 1.7}}. Given an input word $w = w_1w_2\dots w_m \in P_n \cup D_n$, we have that $h_{3, m} = h_{5, m} = 0$. \bigskip \noindent {\it{Proof}}. We first restrict our attention to $h_{3, m}$. Note that $$ h_{3, m} = \begin{cases}\text{ReLU}\left(-(2n + 1)h_{1, m-1} - (2n + 1)h_{2, m-1}\right), & w_m = (_i\\\text{ReLU}\left(2i - (2n + 1)h_{1, m-1} - (2n + 1)h_{2, m-1}\right), & w_m =\ )_i\end{cases} $$ for any $i$, which follows from the definition of $W_h$ and $W_x$. Then using Corollary 1.5 we find $$ h_{3, m} = \begin{cases}\text{ReLU}\left(-(2n + 1)s_{m - 1}\right), & w_m = (_i\\\text{ReLU}\left(2i - (2n + 1)s_{m-1}\right), & w_m =\ )_i\end{cases} $$ Now using the inequality in the proof of Lemma 1.6 we immediately obtain $h_{3, m} =0$ as desired. \bigskip \noindent Considering now $h_{5, m}$ we notice $$ h_{5, m} = \begin{cases}\text{ReLU}\left(-2n - 1 + (2n + 1)h_{1, m-1} + (2n + 1)h_{2, m-1}\right), & w_m = (_i\\\text{ReLU}\left(-2i - 1 + (2n + 1)h_{1, m-1} + (2n + 1)h_{2, m-1}\right), & w_m =\ )_i\end{cases} $$ and doing an analysis similar to that for $h_{3, m}$, we obtain $h_{5, m} = 0$ as desired.\qed \bigskip \noindent Applying Lemma 1.6 allows us to make the following statement: \bigskip \noindent {\bf{Lemma 1.8}}. Given a word $w = w_1w_2\dots w_m \in P_n$, consider the unique $j \in \{1, 2, \dots, n\}$ such that $w)_j \in P_n \cap D_n$. Then with respect to a word $w)_i$ with $i > j$, we have $h_{3, m + 1} > 0$. Similarly, with respect to a word $w)_i$ with $i < j$, we have $h_{5, m + 1} > 0$. \bigskip \noindent {\it{Proof}}. First suppose $i > j$. As in the proof of Lemma 1.7, we use $$ h_{3, m + 1} = \text{ReLU}\left(2i - (2n + 1)h_{1, m} - (2n + 1)h_{2, m} + h_{3, m}\right) = \text{ReLU}\left(2i - (2n + 1)s_m\right) $$ where we again use Corollary 1.5 and the fact that $h_{3, m} = 0$ from Lemma 1.7. But from the proof of Lemma 1.6, since $w)_j \in P_n \cup D_n$ we know that $$ \frac{2j}{2n + 1} \le s_m < \frac{2j + 1}{2n + 1} $$ and since $i > j$ we have that $2i > 2j + 1$ since $i$ and $j$ are integral. Thus $h_{3, m + 1} > 0$ as desired. \bigskip \noindent Now assume $i < j$. As in the previous case we obtain $$ h_{5, m + 1} = \text{ReLU}\left(-2i -1 + (2n + 1)h_{1, m} + (2n + 1)h_{2, m} + h_{5, m}\right) = \text{ReLU}\left(-2i - 1 + (2n + 1)s_m\right) $$ again using Corollary 1.5 and Lemma 1.7. And again using the inequality from the proof of Lemma 1.6 and the fact that $i < j$ we obtain $h_{5, m + 1} > 0$, completing the proof.\qed \bigskip \noindent Thus we have constructed the desired ``flags." Indeed, hidden nodes $h_3$ and $h_5$ remain equal to $0$ while the currently read input lies in $P_n \cup D_n$, but one of these nodes becomes positive the moment the currently read input does not lie in this set. \bigskip \noindent However, there are still difficulties. It is possible for $h_3$ or $h_5$ to become positive and later return to $0$. Indeed, running the simple RNN on the word $w = (_2)_1(_1)_2(_2)_2$, we compute $h_{1, 6} = h_{2, 6} = h_{3, 6} = h_{5,6} = 0$. However, clearly $w \not\in P_n \cup D_n$. Therefore we need to add architecture that retains the information as to whether the hidden nodes $h_3$ or $h_5$ ever become positive, and below we show that hidden nodes $h_4$ and $h_6$ respectively are sufficient. \bigskip \noindent {\bf{Lemma 1.9}}. For any input $w \in \Sigma^*$ we have $$ h_{4, t} = \sum_{i = 0}^{t - 1}h_{3, i} $$ $$ h_{6, t} = \sum_{i = 0}^{t - 1}h_{5, i} $$ \bigskip \noindent {\it{Proof}}. From the definition of $W_x$ and $W_h$ we have $$ h_{4, t} = \text{ReLU}(h_{3, t - 1} + h_{4, t - 1}) $$ $$ h_{6, t} = \text{ReLU}(h_{5, t - 1} + h_{6, t - 1}) $$ and since $h_{3, t}, h_{5, t} \ge 0$ for all $t$ (because of the ReLU) we immediately have the result by induction or direct expansion.\qed \bigskip \noindent We are now ready to combine these lemmas and accomplish our original goal: \bigskip \noindent {\bf{Theorem 1.10}}. The $\{0\}$-language of the simple RNN described earlier in the section is $D_n$. \bigskip \noindent {\it{Proof.}} Consider any input $w = w_1w_2\dots w_m \in \Sigma^*$ into the RNN. For the remainder of the proof, remember that $h_{i, t} \ge 0$ for all $i, t$ because of the ReLU activation. We consider three cases: \begin{itemize} \item Case 1: $w \in P_n \cup D_n$. \end{itemize} In this case by Corollary 1.5 we have $h_{1, m} + h_{2, m} = s_m$. Furthermore, by Lemma 1.7 we have $h_{3, m} = h_{5, m} = 0$. By combining Lemmas 1.7 and 1.9, we have $h_{4, m} = h_{6, m} = 0$. Thus $o_m = s_m$ which, given that $w \in P_n \cup D_n$, equals $0$ precisely when $w \in D_n$, by the inequality from the proof of Lemma 1.6. \begin{itemize} \item Case 2: $w \not\in P_n \cup D_n$ and $w_1w_2\dots w_{m - 1} \in P_n \cup D_n$. \end{itemize} In this case we clearly must have $w_m = )_i$ for some $i \in \{1, 2, \dots, n\}$ and thus by Lemma 1.8 we have that either $h_{3, m} > 0$ or $h_{5, m} > 0$, so $o_m > 0$. \begin{itemize} \item Case 3: $w_1w_2\dots w_k \not\in P_n \cup D_n$ for some $k \in \{1, 2, \dots, m - 1\}$. \end{itemize} Suppose $j$ is the minimal index such that $w_1w_2\dots w_j \not\in P_n \cup D_n$. Then by minimality $w_1w_2\dots w_{j - 1} \in P_n \cup D_n$ so again by Lemma 1.8 we have that either $h_{3, j} > 0$ or $h_{5, j} > 0$. But since $j \le k \le m - 1$ by Lemma 1.9 this means that either $h_{4, m} > 0$ or $h_{6, m} > 0$, so $o_m > 0$. \bigskip \noindent Thus $o_m = 0$ if and only if $w \in D_n$, completing the proof of the theorem.\qed \bigskip \noindent Now recall in the proof of Theorem 1.1 we showed that any regular language $R$ was the $\{0\}$-language of some simple RNN, and moreover that for any input not in $R$ the output of that RNN is positive. This allows us to provide a simple proof of the main theorem of this section: \bigskip \noindent {\bf{Theorem 1.11}}. For any context-free language $L$, suppose we relabel and write $L = D_n \cap R$ for some regular language $R$, whose corresponding minimum-size DFA has $r$ states. Then there exists a simple RNN with a hidden layer of size $6 + 2nr$ whose $\{0\}$-language is $L$. \bigskip \noindent {\it{Proof}}. Consider the simple RNN with $R$ as its $\{0\}$-language described in the proof of Theorem 1.1 and the simple RNN with $D_n$ as its $\{0\}$-language constructed to prove Theorem 1.10. Merge the $|\Sigma| = 2n$ nodes in the input layer corresponding to the input and merge the single output nodes of both RNNs. Stack the two hidden layers, and add no new edges. There were $|\Sigma|r = 2nr$ hidden nodes in the first RNN and $6$ in the second, so altogether the new RNN has $6 + 2nr$ hidden nodes. \bigskip \noindent The output of the new RNN is equal to the summed output of the two original RNNs, and from the proofs of Theorems 1.1 and 1.10 these outputs are always nonnegative. Thus the output of the new RNN is $0$ if and only if the outputs of both old RNNs were $0$, immediately proving the theorem.\qed \bigskip \noindent {\bf{Discussion 1.12}}. This result shows that simple RNNs with arbitrary precision are at least as computationally powerful as PDAs. \section{Gated RNNs} In practice, architectures more complicated than the simple RNNs studied above - notably gated RNNs, including the Gated Recurrent Unit (GRU) and Long Short-Term Memory (LSTM) - perform better on many natural language tasks. Thus we are motivated to explore their computational capabilities. Here we focus on the GRU, described by the equations below: \begin{align*} z_t &= \sigma(W_zx_t + U_zh_{t - 1} + b_z)\\ r_t &= \sigma(W_rx_t + U_rh_{t - 1} + b_r)\\ h_t &= z_t \circ h_{t - 1} + (1 - z_t) \circ \text{tanh}(W_hx_t + U_h(r_t \circ h_{t - 1}) + b_h)\\ o_t &= f(h_t) \end{align*} for some $f: \mathbb{R}^{m \times 1} \rightarrow \mathbb{R}$ where $h$ has dimension $m \times 1$ and $\sigma(x) = (1 + e^{-x})^{-1}$ is the {\it{sigmoid}} function and $\text{tanh}(x) = (e^{2x} - 1)(e^{2x} + 1)^{-1}$ is the {\it{hyperbolic tangent}} function, and the $\circ$ symbol represents element-wise multiplication. Usually the hidden state $h_0$ is initialized to be $0$, but we will ignore that restriction. Some literature switches the placements of the $z_t$ and $1 - z_t$, but since $\sigma(-x) = 1 - \sigma(x)$ this is immaterial. \bigskip \noindent We begin this section by again limiting our architecture to use finite precision, and also assume $f(h) = W_oh$ for some $W_o \in \mathbb{R}^{1 \times m}$. We can prove an analogue of Theorem 1.1: \bigskip \noindent {\bf{Theorem 2.1}}. For every language $L \subseteq \Sigma^*$, $L$ is regular if and only if $L$ is the $S$-language of some finite precision GRU. \bigskip \noindent {\it{Proof}}. The ``if" direction can be shown in the same manner as in Theorem 1.1. So, here we focus on the ``only if" direction. Suppose we have a DFA $D = (Q, \Sigma, \delta, q_0, F)$ with corresponding language $L$. We will construct a GRU whose inputs are one-hotted symbols from $\Sigma$ with $|Q||\Sigma|$ hidden nodes whose $\{0\}$-language is $L$. \bigskip \noindent For convenience, for all $x \in \Sigma$ let $e_x$ denote the corresponding one-hot vector for $x$. Furthermore, let $N = |\Sigma||Q|$. \bigskip \noindent First set $W_z = W_h = 0$ and $U_z = U_r = 0$ and $b_z = b_r = b_h = 0$, so the simplified GRU is given by: \begin{align*} r_t &= \sigma(W_rx_t)\\ \text{tanh}^{-1}(2h_t - h_{t - 1}) &= U_h(r_t \circ h_{t - 1})\\ o_t &= W_oh_t \end{align*} Now, define an arbitrary bijective map $g: \{1, 2, \dots, |Q|\} \rightarrow Q$. Then construct $|Q|$ vectors $$ s_i = [s_{i,1}\ \ s_{i,2}\ \ \dots\ \ s_{i,N}]^T $$ where for all $i \in \{1, 2, \dots, |Q|\}$ and $k \in \{1, 2, \dots, N\}$ we set $$ s_{i, k} = \begin{cases}0.25, & 0 \le i|\Sigma| - k < |\Sigma|\\0, & \text{otherwise}\end{cases} $$ Our goal will be to find $W_r$ and $U_h$ such that if $h_{t - 1} = s_i$ for some $i$, and $x_t$ is the one-hot encoding of some $x \in \Sigma$, then $h_t = s_j$ where if $g(i) = q$ for some $q \in Q$ then $g(j) = \delta(q, x)$. If this is possible, then we could set $h_0 = s_{g^{-1}(q_0)}$ and be able to track the current state of the DFA effectively. \bigskip \noindent The strategy for accomplishing this is essentially to pick a simple $W_r$, and then solve a system of equations to produce the desired $U_h$. \bigskip \noindent For convenience, define the natural map $h: \{1, 2, \dots, |\Sigma|\} \rightarrow \Sigma$ where $h(i) = x$ if and only if the $i$th element of $e_x$ is equal to $1$. \bigskip \noindent Let $$ W_r = \begin{bmatrix}\sigma^{-1}(r_{1,1}) & \sigma^{-1}(r_{1,2}) & \dots & \sigma^{-1}(r_{1,|\Sigma|})\\\sigma^{-1}(r_{2,1}) & \sigma^{-1}(r_{2,2}) & \dots & \sigma^{-1}(r_{2,|\Sigma|})\\\vdots & \vdots & \ddots & \vdots\\\sigma^{-1}(r_{N,1}) & \sigma^{-1}(r_{N,2}) & \dots & \sigma^{-1}(r_{N,|\Sigma|})\end{bmatrix} $$ \\ where $$ r_{k, j} = \begin{cases}0.4, & k \not\equiv j \pmod{|\Sigma|}\\0.8, & k \equiv j \pmod{|\Sigma|}\end{cases} $$ for all $k \in \{1, 2, \dots, N\}$ and $j \in \{1, 2, \dots, |\Sigma|\}$. Now consider the $N$ equations $$ \text{tanh}^{-1}(2s_j - s_i) = U_h(\sigma(W_re_x) \circ s_i) $$ where $g(j) = \delta(g(i), x)$, for every $i \in \{1, 2, \dots, |Q|\}$ and $x \in \Sigma$. Let \begin{align*} b_{k, (i -1)|\Sigma| + j} &= \text{tanh}^{-1}(2s_{g^{-1}(\delta(g(i), h(j))), k} - s_{i, k})\\ c_{k, (i - 1)|\Sigma| + j} &= r_{k, j}s_{i, k} \end{align*} for all $i \in \{1, 2, \dots, |Q|\}$ and $j \in \{1, 2, \dots, |\Sigma|\}$ and $k \in \{1, 2, \dots, N\}$. Letting \\ \begin{align*} B = \begin{bmatrix}b_{1,1} & b_{1,2} & \dots & b_{1,N}\\b_{2,1} & b_{2,2} & \dots & b_{2,N}\\\vdots & \vdots & \ddots & \vdots\\b_{N,1} & b_{N,2} & \dots & b_{N,N}\end{bmatrix}\ \ \ \ \ \ \ \ \ C = \begin{bmatrix}c_{1,1} & c_{1,2} & \dots & c_{1,N}\\c_{2,1} & c_{2,2} & \dots & c_{2,N}\\\vdots & \vdots & \ddots & \vdots\\c_{N,1} & c_{N,2} & \dots & c_{N,N}\end{bmatrix} \end{align*} \\ The $N$ earlier equations can now be combined as a single matrix equation given by $$ U_hC = B \Longrightarrow U_h = BC^{-1} $$ \bigskip \noindent Now it is easy to see that $$ C = \begin{bmatrix}C_1 & 0 & \dots & 0\\0 & C_2 & \dots & 0\\\vdots & \vdots & \ddots & \vdots\\0 & 0 & \dots & C_{|Q|}\end{bmatrix} $$ where $C_j$ is a $|\Sigma| \times |\Sigma|$ matrix for each $j \in \{1, 2, \dots, |\Sigma|\}$. In particular, we have that $$ C_j = \begin{bmatrix}0.2 & 0.1 & \dots & 0.1\\0.1 & 0.2 & \dots & 0.1\\\vdots & \vdots & \ddots & \vdots\\0.1 & 0.1 & \dots & 0.2\end{bmatrix} $$ for each $j$. \bigskip \noindent Using basic row operations it is easy to see that $\text{det}(C_j) = 0.1^{|\Sigma|}(|\Sigma| + 1)$ for all $j$, so $$ \text{det}(C) = \prod_{j= 1}^{|Q|}\text{det}(C_j) = 0.1^N(|\Sigma| + 1)^{|Q|} \ne 0 $$ and thus $C^{-1}$ is well-defined. Furthermore, since $s_{i, k} \in \{0, 0.25\}$ for each $i, k$, the inputs into all inverse hyperbolic tangents in $B$ lie in $(-1, 1)$ and so $B$ is well-defined as well. Thus our expression for $U_h$ is well-defined. \bigskip \noindent Now, given our choices for the $s_i, W_r$, and $U_h$, after reading any input $w = w_1w_2\dots w_m$, if $q$ is the current state of the DFA associated with $L$, then $h_m = s_{g^{-1}(q)}$. Now because the $s_i$ are clearly linearly independent, we can find a $W_o$ such that $$ W_os_i = \begin{cases}0, & g(i) \in F\\1, & g(i) \not\in F\end{cases} $$ for all $i \in \{1, 2, \dots, Q\}$ and it's clear that the $\{0\}$-language of the resulting GRU will be $L$, as desired.\qed \bigskip \noindent {\bf{Discussion 2.2}}. In the above proof, we are implicitly assuming that the activation functions of the GRU are not actually the sigmoid and hyperbolic tangent functions but rather finite precision analogues for which the equations we solved are all consistent. However, for the remainder of this section we can drop this assumption. \bigskip \noindent If we remove the finite precision restriction, we again wish to prove that Gated RNNs are as powerful as PDAs. To do so, we emulate the approach from Section 1. Immediately we encounter difficulties - in particular, our previous approach relied on maintaining the digits of a state $s$ in base $2n + 1$ very carefully. With outputs now run through sigmoid and hyperbolic tangent functions, this becomes very hard. Furthermore, updating the state $s$ occasionally requires multiplication by $2n + 1$ (when we read a closing parenthesis). But because $\sigma(x) \in (0, 1)$ and $\text{tanh}(x) \in (-1, 1)$ for all $x \in \mathbb{R}$, this is impossible to do with the GRU architecture. \bigskip \noindent To account for both of these issues, instead of keeping track of the state $s_t$ as we read a word, we will instead keep track of the state $s'_t$ of a word $w = w_1w_2\dots w_m \in \Sigma^*$ defined by \begin{align*} s'_0 &= 0\\ s'_t &= \begin{cases}(2n + 1)^{-1 - k}s'_{t - 1} + 2i(2n + 1)^{-1 - kt}, & w_t =(_i \\(2n + 1)^{1 - k}s'_{t - 1} - 2i(2n + 1)^{-kt}, & w_t =\ )_i\end{cases} \end{align*} for all $i \in \{1, 2, \dots, n\}$, for some predetermined sufficiently large $k$. We have the following relationship between $s'_t$ and $s_t$: \bigskip \noindent {\bf{Lemma 2.3}}. For any word $w = w_1w_2\dots w_m \in \Sigma^*$ we have $s_t = (2n + 1)^{kt}s'_t$ for all $t \in \{1, 2, \dots, m\}$. \bigskip \noindent {\it{Proof}}. Multiplying the recurrence relationship for $s'_t$ by $(2n + 1)^{kt}$ we recover the recurrence relationship for $s_t$ in Section 1, implying the desired result.\qed \bigskip \noindent Thus the state $s'$ allows us to keep track of the old state $s$ without having to multiply by any constant greater than $1$. Furthermore, for large $k$, $s'$ will be extremely small, allowing us to abuse the fact that $\text{tanh}(x) \sim x$ for small values of $x$. In terms of the stack of digits interpretation of $s$, $s'$ is the same except between every pop or push we add $k$ zeros to the top of the stack. \bigskip \noindent Again we wish to construct a GRU from whose hidden state we can recover $s'_t$. Ignoring the output layer for now, consider the GRU defined by \begin{align*} h_0 &= [h_{1, 0}\ \ 1\ \ 1]^T\\ z_t &= \sigma(W_zx_t)\\ r_t &= \sigma(W_rx_t)\\ h_t &= z_t \circ h_{t - 1} + (1 - z_t) \circ \text{tanh}(U_h(r_t \circ h_{t - 1})) \end{align*} where $h_{1, 0} \ge 0$ will be determined later, the inputs $x$ are again $2n \times 1$ one-hots of the symbols in $\Sigma$ in the order $(_1, (_2, \dots, (_n, )_1, )_2, \dots, )_n$ and the hidden states have dimension $3 \times 1$ where \begin{align*} W_z &= \begin{bmatrix}\sigma^{-1}((2n + 1)^{-1 - k}) & \dots & \sigma^{-1}((2n + 1)^{-1 - k}) & \sigma^{-1}((2n + 1)^{1 - k}) & \dots & \sigma^{-1}((2n + 1)^{1 - k})\\\sigma^{-1}((2n + 1)^{-k}) & \dots & \dots & \dots & \dots & \sigma^{-1}((2n + 1)^{-k})\\\sigma^{-1}((2n + 1)^{-k}) & \dots & \dots & \dots & \dots & \sigma^{-1}((2n + 1)^{-k})\end{bmatrix}\\ \\ W_r &= \begin{bmatrix}0 & 0 & \sigma^{-1}(0.5 - 2((2n + 1)^{k + 1} - 1)^{-1})\\0 & 0 & \sigma^{-1}(0.5 - 4((2n + 1)^{k + 1} - 1)^{-1})\\\vdots & \vdots & \vdots\\0 & 0 & \sigma^{-1}(0.5 - 2n((2n + 1)^{k + 1} - 1)^{-1})\\0 & 0 & \sigma^{-1}(0.5 + 2((2n + 1)^{k} - 2n - 1)^{-1})\\0 & 0 & \sigma^{-1}(0.5 + 4((2n + 1)^{k} - 2n - 1)^{-1})\\\vdots & \vdots & \vdots\\0 & 0 & \sigma^{-1}(0.5 + 2n((2n + 1)^{k} - 2n - 1)^{-1})\end{bmatrix}^T\\ \\ U_h &= \begin{bmatrix}0 & 1 & -1\\0 & 0 & 0\\0 & 0 & 0\end{bmatrix}\\ \end{align*} where $\sigma^{-1}(x) = -\ln(x^{-1} - 1)$ is the inverse of the sigmoid function. For sufficiently large $k$, clearly our use of $\sigma^{-1}$ is well-defined. We will show the following invariant: \bigskip \noindent {\bf{Lemma 2.4}}. Given an input word $w \in P_n \cup D_n$, if $h_{1, 0} = 0$ then we have $h_t \approx [s'_t\ \ (2n + 1)^{-kt}\ \ (2n + 1)^{-kt}]^T$ for all $t$. \bigskip \noindent {\it{Proof}}. As in Section 1, let $z_t = [z_{1, t}\ \ z_{2, t}\ \ z_{3, t}]^T$ and $r_t = [r_{1, t}\ \ r_{2, t}\ \ r_{3, t}]^T$ and $h_t = [h_{1, t}\ \ h_{2, t}\ \ h_{3, t}]^T$. First, we will show $h_{2, t} = (2n + 1)^{-kt}$ for all $t \in \{1, 2, \dots, m\}$ by induction on $t$. The base case is trivial, so note \begin{align*} z_{2, t + 1} &= \sigma(\sigma^{-1}((2n + 1)^{-k})) = (2n + 1)^{-k}\\ r_{2, t + 1} &= \sigma(0) = 0.5\\ h_{2, t + 1} &= z_{2, t + 1}h_{2, t} + (1 - z_{2, t + 1})\text{tanh}(0) = (2n + 1)^{-k}h_{2, t} \end{align*} so by induction $h_{2, t + 1} = (2n + 1)^{-k(t + 1)}$ as desired. Similarly, we obtain $h_{3, t} = (2n + 1)^{-kt}$ for all $t$. \bigskip \noindent Now we restrict our attention to $h_{1, t}$. Note that \begin{align*} z_{1, t} &= \begin{cases}\sigma(\sigma^{-1}((2n + 1)^{-1 - k})) = (2n + 1)^{-1 - k}, & w_t = (_i\\\sigma(\sigma^{-1}((2n + 1)^{1 - k})) = (2n + 1)^{1 - k}, & w_t =\ )_i\end{cases}\\ r_{2, t} &= \sigma(0) = 0.5\\ r_{3, t} &= \begin{cases}0.5 - 2i((2n + 1)^{k + 1} - 1)^{-1}, & w_t = (_i\\0.5 + 2i((2n + 1)^{k} - 2n - 1)^{-1}, & w_t =\ )_i\end{cases}\\ \end{align*} and so using the definition of $U_h$ we obtain \begin{align*} h_{1, t} &= z_{1, t}h_{1, t - 1} + (1 - z_{1, t})\text{tanh}(2^{-k(t - 1)}r_{2, t} - 2^{-k(t - 1)}r_{3, t})\\ &= \begin{cases}(2n + 1)^{-1 - k}h_{1, t - 1} + (1 - (2n + 1)^{-1 - k})\text{tanh}(2i(2n + 1)^{-k(t - 1)}((2n + 1)^{k + 1} - 1)^{-1}), & w_t = (_i\\(2n + 1)^{1 - k}h_{1, t - 1} - (1 - (2n + 1)^{1 - k})\text{tanh}(2i(2n + 1)^{-k(t - 1)}((2n + 1)^{k} - 2n - 1)^{-1}), & w_t =\ )_i\end{cases} \end{align*} If we removed the $\text{tanh}$ from the above expression, it would simplify to $$ h_{1, t} = \begin{cases}(2n + 1)^{-1 - k}h_{1, t - 1} + 2i(2n + 1)^{-1 -kt}, & w_t = (_i\\(2n + 1)^{1 - k}h_{1, t - 1} - 2i(2n + 1)^{-kt}, & w_t =\ )_i\end{cases} $$ which is exactly the recurrence relation satisfied by $s'_t$. Since the expressions inside the hyperbolic tangents are extremely small (on the order of $2^{-kt}$), this implies that $h_{1, t}$ is a good approximation for $s'_t$ as desired. This will be formalized in the next lemma.\qed \bigskip \noindent {\bf{Lemma 2.5}}. For any input word $w \in P_n \cup D_n$, if $h_{1, 0} = 0$ then we have $|(2n + 1)^{kt}h_{1, t} - s_t| < 2(2n + 1)^{-2k + 7}$ for all $t$. \bigskip \noindent {\it{Proof}}. Let $\epsilon_t = (2n + 1)^{kt}h_{1, t} - s_t$ for all $t$. Then we easily find that $$ \epsilon_t = \begin{cases}(2n + 1)^{-1}\epsilon_{t - 1} + (2n + 1)^{kt}(1 - (2n + 1)^{-1-k})\text{tanh}\left(\frac{2i(2n + 1)^{-k(t - 1)}}{(2n + 1)^{k + 1} - 1}\right) - \frac{2i}{2n + 1}, & w_t = (_i\\(2n + 1)\epsilon_{t - 1} - (2n + 1)^{kt}(1 - (2n + 1)^{1-k})\text{tanh}\left(\frac{2i(2n + 1)^{-k(t - 1)}}{(2n + 1)^{k} - 2n - 1}\right) + 2i, & w_t = \ )_i\end{cases} $$ Now define $\epsilon'_t$ by the recurrence $$ \epsilon'_t = \begin{cases}(2n + 1)^{-1}\epsilon'_{t - 1} - (2n + 1)^{kt}(1 - (2n + 1)^{-1-k})\text{tanh}\left(\frac{2i(2n + 1)^{-k(t - 1)}}{(2n + 1)^{k + 1} - 1}\right) + \frac{2i}{2n + 1}, & w_t = (_i\\(2n + 1)\epsilon'_{t - 1} - (2n + 1)^{kt}(1 - (2n + 1)^{1-k})\text{tanh}\left(\frac{2i(2n + 1)^{-k(t - 1)}}{(2n + 1)^{k} - 2n - 1}\right) + 2i, & w_t = \ )_i\end{cases} $$ with $\epsilon'_0 = \epsilon_0 = 0$. Because $\text{tanh}(x) < x$ for all $x > 0$ it is easy to see that $\epsilon'_t \ge |\epsilon_t|$ for all $t$. \bigskip \noindent Now by a Taylor expansion, $\text{tanh}(x) = x - \frac{x^3}{3} + \frac{2x^5}{15} + O(x^7)$, so we have that $$ 0 \le x - \text{tanh}(x) \le \frac{x^3}{3} < x^3 $$ for $x > 0$. Thus we obtain the bound $$ \frac{2i}{2n + 1} - (2n + 1)^{kt}(1 - (2n + 1)^{-1-k})\text{tanh}\left(\frac{2i(2n + 1)^{-k(t - 1)}}{(2n + 1)^{k + 1} - 1}\right) < \frac{8i^3(2n + 1)^{-2kt + 2k - 1}}{((2n + 1)^{k + 1} - 1)^2} $$ Since $2i < 2n + 1$ and $(2n + 1)^{k + 1} - 1 \ge (2n + 1)^k$ we also have $$ \frac{8i^3(2n + 1)^{-2kt + 2k - 1}}{((2n + 1)^{k + 1} - 1)^2} < \frac{(2n + 1)^3(2n + 1)^{-2kt + 2k - 1}}{(2n + 1)^{2k}} = (2n + 1)^{-2kt + 2} < (2n + 1)^{-2kt + 5} $$ Similarly we obtain the bound $$ 2i - (2n + 1)^{kt}(1 - (2n + 1)^{1-k})\text{tanh}\left(\frac{2i(2n + 1)^{-k(t - 1)}}{(2n + 1)^{k} - 2n - 1}\right) < \frac{8i^3(2n + 1)^{-2kt + 2k - 2}}{((2n + 1)^{k - 1} - 1)^2} $$ Since again $2i < 2n + 1$ and $(2n + 1)^{k - 1} - 1 \ge (2n + 1)^{k - 2}$ we also have $$ \frac{8i^3(2n + 1)^{-2kt + 2k - 2}}{((2n + 1)^{k - 1} - 1)^2} < \frac{(2n + 1)^3(2n + 1)^{-2kt + 2k - 2}}{(2n + 1)^{2k - 4}} = (2n + 1)^{-2kt + 5} $$ Thus if we define $a_t$ by the recurrence $$ a_t = \begin{cases}(2n + 1)^{-1}a_{t - 1} + (2n + 1)^{-2kt + 5}, & w_t = (_i\\(2n + 1)a_{t - 1} + (2n + 1)^{-2kt + 5}, & w_t = \ )_i\end{cases} $$ with $a_0 = \epsilon'_0 = 0$, then $a_t \ge \epsilon'_t$ for all $t$. \bigskip \noindent Now we wish to upper bound $a_t$. Since $i$ is not present in the recurrence for $a_t$, assume without loss of generality that all parenthesis in an input word $w = w_1w_2\dots w_m \in P_n \cup D_n$ lie in $\{(_1, )_1\}$. Suppose that $)_1(_1$ was a substring of $w$, so that $w = x)_1(_1y$. Then we would have \begin{align*} a_{|x| + 2} &= (2n + 1)^{-1}\left((2n + 1)a_{|x|} + (2n + 1)^{-2k(|x| + 1) + 5}\right) + (2n + 1)^{-2k(|x| + 2) + 5}\\ &= a_{|x|} + (2n + 1)^{-2k(|x| + 1) + 4} + (2n + 1)^{-2k(|x| + 2) + 5} \end{align*} However, for the word $w' = x(_1)_1y$ (which would clearly still lie in $P_n \cup D_n$) we would have \begin{align*} a_{|x| + 2} &= (2n + 1)\left((2n + 1)^{-1}a_{|x|} + (2n + 1)^{-2k(|x| + 1) + 5}\right) + (2n + 1)^{-2k(|x| + 2) + 5}\\ &= a_{|x|} + (2n + 1)^{-2k(|x| + 1) + 6} + (2n + 1)^{-2k(|x| + 2) + 5} \end{align*} which is larger. Thus to upper bound $a_t$ it suffices to consider only words that do not contain the substring $)_1(_1$, which are words in the form $$ w = (_1(_1\dots(_1)_1)_1\dots)_1 $$ with $r$ open parentheses followed by $s \le r$ closing parentheses. Furthermore, adding extra closing parenthesis where suitable clearly increases the final $a_t$ so we can assume $s = r$. We can then exactly calculate $a_{2r}$ as $$ \sum_{i = 1}^{r}(2n + 1)^{-2ki + 5 + i} + \sum_{i = 1}^{r}(2n + 1)^{-2k(r + i) + 5 + r - i} $$ Considering each sum separately we have for sufficiently large $k$ that \begin{align*} \sum_{i = 1}^{r}(2n + 1)^{-2ki + 5 + i} &< \lim_{q \rightarrow \infty}(2n + 1)^5\sum_{i = 1}^{q}(2n + 1)^{(-2k + 1)i}\\ &= \frac{(2n + 1)^{-2k + 6}}{1 - (2n + 1)^{-2k + 1}}\\ &< (2n + 1)^{-2k + 7} \end{align*} and \begin{align*} \sum_{i = 1}^{r}(2n + 1)^{-2k(r + i) + 5 + r - i} &= (2n + 1)^{5 + (1 - 2k)r}\sum_{i = 1}^{r}(2n + 1)^{(-2k - 1)i}\\ &< \frac{(2n + 1)^{5 + (1 - 2k)r}}{1 - (2n + 1)^{-2k - 1}}\\ &< (2n + 1)^{-2k + 7} \end{align*} And therefore $2(2n + 1)^{-2k + 7}$ is an upper bound on $a_t$. Thus $$ |\epsilon_t| \le \epsilon'_t \le a_t < 2(2n + 1)^{-2k + 7} $$ for all $t$ as desired.\qed \bigskip \noindent {\bf{Corollary 2.6}}. For any input word $w = w_1w_2\dots w_m \in P_n \cup D_n$, if $w_1w_2\dots w_t$ contains $a_t$ open parentheses and $b_t \le a_t$ closing parentheses then $$ (2n + 1)^{kt}h_{1, t} = h_{1, 0}(2n + 1)^{b_t - a_t} + s_t + \epsilon $$ with $|\epsilon| < 2(2n + 1)^{-2k + 7}$ for all $t$. \bigskip \noindent {\it{Proof}}. This follows directly from the computations in the proof of Lemma 2.5 and the recurrence for $h_{1, t}$.\qed \bigskip \noindent Now, set $h_{1, 0} = 3(2n + 1)^{-2k + 7}$. We then have the following useful analogues of Lemmas 1.7 and 1.8: \bigskip \noindent {\bf{Corollary 2.7}}. For any input word $w = w_1w_2\dots w_m \in P_n \cup D_n$ we have $h_{1, m} > 0$. \bigskip \noindent {\it{Proof}}. This follows immediately from Corollary 2.6 and the fact that $h_{1, 0} > 2(2n + 1)^{-2k + 7}$. \qed \bigskip \noindent {\bf{Lemma 2.8}}. Given a word $w_1w_2\dots w_m \in P_n$, consider the unique $j \in \{1, 2, \dots, n\}$ such that $w)_j \in P_n \cup D_n$. Then for an input word $w)_i$ with $i > j$, we have $h_{1, m + 1} < 0$. \bigskip \noindent Note that $$ h_{1, m + 1} = (2n + 1)^{1 - k}h_{1, m} - (1 - (2n + 1)^{1 - k})\text{tanh}(2i(2n + 1)^{-km}((2n + 1)^{k} - 2n - 1)^{-1}) $$ so multiplying both sides by $(2n + 1)^{k(m + 1)}$ and using the inequality from the proof of Lemma 2.5 we have $$ (2n + 1)^{k(m + 1)}h_{1, m + 1} < (2n + 1)^{km + 1}h_{1, m} - 2i + (2n + 1)^{-2k(m + 1) + 5} $$ Now by Corollary 2.6 we have that $$ (2n + 1)^{km}h_{1, m} < s_m + 5(2n + 1)^{-2k + 7} < \frac{2j + 1}{2n + 1} + 5(2n + 1)^{-2k + 7} $$ where we used the inequality from the proof of Lemma 1.6 and the fact that $h_{1, 0} = 3(2n + 1)^{-2k + 7}$. Therefore $$ (2n + 1)^{k(m + 1)}h_{1, m + 1} < 2j + 1 - 2i + 5(2n + 1)^{-2k + 8} + (2n + 1)^{-2k(m + 1) + 5} $$ Since $i > j$ we have that $2j + 1 - 2i \le -1$ and so for sufficiently large $k$ we then have $$ h_{1, m + 1} < 0 $$ as desired. \qed \bigskip \noindent With these results in hand, consider the larger GRU, an example of which can be found in Appendix A.2, defined by \begin{align*} h_0 &= [3(2n + 1)^{-2k + 7}\ \ 1\ \ 1\ \ 1\ \ 3(2n + 1)^{-2k + 7}\ \ 1\ \ 1\ \ 1]^T\\ z_t &= \sigma(W_zx_t + U_zh_{t - 1})\\ r_t &= \sigma(W_rx_t)\\ h_t &= z_t \circ h_{t - 1} + (1 - z_t) \circ \text{tanh}(U_h(r_t \circ h_{t - 1}))\\ o_t &= \frac{|h_{1, t}|}{h_{2, t}} - h_{4, t} - h_{8, t} + 2 \end{align*} where the inputs $x$ are again $2n \times 1$ one-hots of the symbols in $\Sigma$ in the order $(_1, (_2, \dots, (_n, )_1, )_2, \dots, )_n$ and the hidden states have dimension $8 \times 1$ where \begin{align*} W_z &= \begin{bmatrix}\sigma^{-1}((2n + 1)^{-1 - k}) & \dots & \sigma^{-1}((2n + 1)^{-1 - k}) & \sigma^{-1}((2n + 1)^{1 - k}) & \dots & \sigma^{-1}((2n + 1)^{1 - k})\\\sigma^{-1}((2n + 1)^{-k}) & \dots & \dots & \dots & \dots & \sigma^{-1}((2n + 1)^{-k})\\\sigma^{-1}((2n + 1)^{-k}) & \dots & \dots & \dots & \dots & \sigma^{-1}((2n + 1)^{-k})\\0 & \dots & \dots & \dots & \dots & 0\\\sigma^{-1}((2n + 1)^{-1 - k}) & \dots & \sigma^{-1}((2n + 1)^{-1 - k}) & \sigma^{-1}((2n + 1)^{1 - k}) & \dots & \sigma^{-1}((2n + 1)^{1 - k})\\\sigma^{-1}((2n + 1)^{-k}) & \dots & \dots & \dots & \dots & \sigma^{-1}((2n + 1)^{-k})\\\sigma^{-1}((2n + 1)^{-k}) & \dots & \dots & \dots & \dots & \sigma^{-1}((2n + 1)^{-k})\\0 & \dots & \dots & \dots & \dots & 0\end{bmatrix}\\ \\ U_z &= \begin{bmatrix}0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\\infty & 0 & 0 & 0 & 0 & 0 & 0 & 0\\0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\0 & 0 & 0 & 0 & \infty & 0 & 0 & 0\end{bmatrix}\\ \\ W_r &= \begin{bmatrix}0 & 0 & \sigma^{-1}(0.5 - 2((2n + 1)^{k + 1} - 1)^{-1}) & 0 & 0 & 0 & \sigma^{-1}(0.5 - 2n((2n + 1)^{k + 1} - 1)^{-1}) & 0\\0 & 0 & \sigma^{-1}(0.5 - 4((2n + 1)^{k + 1} - 1)^{-1}) & 0 & 0 & 0 & \sigma^{-1}(0.5 - (2n - 2)((2n + 1)^{k + 1} - 1)^{-1}) & 0\\\vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots\\0 & 0 & \sigma^{-1}(0.5 - 2n((2n + 1)^{k + 1} - 1)^{-1}) & 0 & 0 & 0 & \sigma^{-1}(0.5 - 2((2n + 1)^{k + 1} - 1)^{-1}) & 0\\0 & 0 & \sigma^{-1}(0.5 + 2((2n + 1)^{k} - 2n - 1)^{-1}) & 0 & 0 & 0 & \sigma^{-1}(0.5 + 2n((2n + 1)^{k} - 2n - 1)^{-1}) & 0\\0 & 0 & \sigma^{-1}(0.5 + 4((2n + 1)^{k} - 2n - 1)^{-1}) & 0 & 0 & 0 & \sigma^{-1}(0.5 + (2n - 2)((2n + 1)^{k} - 2n - 1)^{-1}) & 0\\\vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots\\0 & 0 & \sigma^{-1}(0.5 + 2n((2n + 1)^{k} - 2n - 1)^{-1}) & 0 & 0 & 0 & \sigma^{-1}(0.5 + 2((2n + 1)^{k} - 2n - 1)^{-1}) & 0\end{bmatrix}^T\\ \\ U_h &= \begin{bmatrix}0 & 1 & -1 & 0 & 0 & 0 & 0 & 0\\0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\0 & 0 & 0 & 0 & 0 & 1 & -1 & 0\\0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\end{bmatrix}\\ \end{align*} As before, with respect to a word $w \in \Sigma^*$ define $s_t$ by \begin{align*} s_0 &= 0\\ s_t &= \begin{cases}(2n + 1)^{-1}s_{t - 1} + 2i(2n + 1)^{-1}, & w_t =(_i \\(2n + 1)s_{t - 1} - 2i, & w_t =\ )_i\end{cases} \end{align*} for all $i \in \{1, 2, \dots, n\}$ and all $t$. Similarly define $\overline{s}_t$ by \begin{align*} \overline{s}_0 &= 0\\ \overline{s}_t &= \begin{cases}(2n + 1)^{-1}\overline{s}_{t - 1} + 2i(2n + 1)^{-1}, & w_t =(_{n - i} \\(2n + 1)\overline{s}_{t - 1} - 2i, & w_t =\ )_{n - i}\end{cases} \end{align*} For our new GRU, let $h_t = [h_{1, t}\ \ h_{2, t}\ \ h_{3, t}\ \ h_{4, t}\ \ h_{5, t}\ \ h_{6, t}\ \ h_{7, t}\ \ h_{8, t}]^T$. We then have the following results: \bigskip \noindent {\bf{Lemma 2.9}}. For any input word $w \in \Sigma^*$ we have $h_{2, t} = h_{3, t} = h_{6, t} = h_{7, t} = (2n + 1)^{-kt}$. \bigskip \noindent {\it{Proof}}. This follows immediately from the proof of Lemma 2.4.\qed \bigskip \noindent {\bf{Lemma 2.10}}. For any input word $w = w_1w_2\dots w_m \in P_n \cup D_n$, if $w_1w_2\dots w_t$ contains $a_t$ open parentheses and $b_t \le a_t$ closing parenthesis then $$ (2n + 1)^{kt}h_{1, t} = h_{1, 0}(2n + 1)^{b_t - a_t} + s_t + \epsilon_1 $$ $$ (2n + 1)^{kt}h_{5, t} = h_{5, 0}(2n + 1)^{b_t - a_t} + \overline{s}_t + \epsilon_2 $$ with $|\epsilon_1|, |\epsilon_2| < 2(2n + 1)^{-2k + 7}$ for all $t$. \bigskip \noindent {\it{Proof}}. This follows immediately from the proof of Corollary 2.6 and the new $W_r$, since $h_{5, t}$ behaves exactly like $h_{1, t}$ if each input $(_i$ or $)_i$ were $(_{n - i}$ or $)_{n - i}$ respectively, instead. \qed \bigskip \noindent {\bf{Lemma 2.11}}. For any input word $w = w_1w_2\dots w_m \in \Sigma^*$ we have $h_{4, m}, h_{8, m} \in \{0, 1\}$ and $h_{4, m} = h_{8, m} = 1 $ if and only if $w_1w_2\dots w_{m - 1} \in P_n \cup D_n$. \bigskip \noindent {\it{Proof}}. From our chosen $U_z$ we see that $$ z_{4, t} = \begin{cases}\sigma(\infty) = 1, & h_{1, t-1} > 0\\\sigma(-\infty) = 0, & h_{1, t - 1} < 0\end{cases} $$ $$ z_{8, t} = \begin{cases}\sigma(\infty) = 1, & h_{5, t-1} > 0\\\sigma(-\infty) = 0, & h_{5, t - 1} < 0\end{cases} $$ Since $h_{4, 0} = h_{8, 0} = 1$ and since the fourth and eighth rows of $U_h$ are identically $0$, the equation $$ h_t = z_t \circ h_{t - 1} + (1 - z_t) \circ \text{tanh}(U_h(r_t \circ h_{t - 1})) $$ implies that $$ h_{4, m} = \prod_{i = 1}^{m}z_{4, i} $$ $$ h_{8, m} = \prod_{i = 1}^{m}z_{8, i} $$ which immediately implies that $h_{4, m}, h_{8, m} \in \{0, 1\}$. Now, suppose $w_1w_2\dots w_{m - 1} \in P_n \cup D_n$. Then from Corollary 2.7 and its analogue for $h_{5, t}$ we see that $z_{4, t} = z_{8, t} = 1$ for all $t \in \{1, 2, \dots, m\}$, so $h_{4, m} = h_{8, m} = 1$ as desired. \bigskip \noindent Otherwise, there exists some minimal $k \in \{0, 1, \dots, m - 2\}$ such that $w_1w_2\dots w_{k + 1} \not\in P_n \cup D_n$. Then $w_{k + 1} = )_i$ for some $i \in \{1, 2, \dots, n\}$. Consider the unique $j \ne i$ such that $w_1w_2\dots w_k)_j \in P_n \cup D_n$. If $i > j$ then from the proof of Lemma 2.8 we have that $h_{1, k + 1} < 0$ and so $z_{4, k + 2} = 0$. Since $k + 2 \le m$ this means that $h_{4, m} = 0$. If $i < j$ then from the analogue of the proof of Lemma 2.8 for $h_{5, t}$, we obtain $h_{8, m} = 0$. This completes the proof. \qed \bigskip \noindent We are now ready to combine these lemmas to prove an important result, the analogue of Theorem 1.10 for GRUs: \bigskip \noindent {\bf{Theorem 2.12}}. The $(0, (2n + 1)^{-1})$-language of the GRU described earlier in the section is $D_n$. \bigskip \noindent {\it{Proof}}. Consider any input word $w = w_1w_2\dots w_m \in \Sigma^*$ into the GRU. We consider four cases: \begin{itemize} \item Case 1: $w \in D_n$. \end{itemize} In this case, we clearly have $s_m = 0$ and $h_{1, m} > 0$ from the proof of Corollary 2.7, so by Lemmas 2.9 and 2.10 we have that $$ \frac{|h_{1, m}|}{h_{2, m}} = (2n + 1)^{km}h_{1, m} = h_{1, 0} + \epsilon $$ with $|\epsilon| < 2(2n + 1)^{-2k + 7}$. Furthermore from Lemma 2.11 we have that $h_{4, m} = h_{8, m} = 1$ so since $h_{1, 0} = 3(2n + 1)^{-2k + 7}$ we must have $$ o_m \in ((2n + 1)^{-2k + 7}, 5(2n + 1)^{-2k + 7}) \subset (0, (2n + 1)^{-1}) $$ for sufficiently large $k$, as desired. \begin{itemize} \item Case 2: $w \in P_n$. \end{itemize} As in Case 1 we have that $h_{1, m} > 0$ and so by Lemmas 2.9 and 2.10 we have that $$ \frac{|h_{1, m}|}{h_{2, m}} = (2n + 1)^{km}h_{1, m} \ge s_m + \epsilon $$ with $|\epsilon| < 2(2n + 1)^{-2k + 7}$. Furthermore from Lemma 2.11 we have that $h_{4, m} = h_{8, m} = 1$ so here $$ o_m \ge s_m - 2(2n + 1)^{-2k + 7} \ge 2(2n + 1)^{-1} - 2(2n + 1)^{-2k + 7} > (2n + 1)^{-1} $$ for sufficiently large $k$, since the minimum value of $s_m$ is clearly $2(2n + 1)^{-1}$. \begin{itemize} \item Case 3: $w \not\in P_n \cup D_n$ and $w_1w_2\dots w_{m - 1} \in P_n \cup D_n$. \end{itemize} Suppose $w_1w_2\dots w_{m - 1})_j \in P_n \cup D_n$ for some unique $j \in \{1, 2, \dots, n\}$. If $w_m = )_i$ for some $i > j$ then from Lemmas 2.9 and 2.10 and the proof of Lemma 2.8 we obtain $$ \frac{h_{1, m}}{h_{2, m}} = (2n + 1)^{km}h_{1, m} < -1 + 5(2n + 1)^{-2k + 8} + (2n + 1)^{-2km + 5} < -(2n + 1)^{-1} $$ for sufficiently large $k$. If instead $i < j$ then the same technique with the inequality $\text{tanh}(x) < x$ can be used to show $$ \frac{h_{1, m}}{h_{2, m}} > (2n + 1)s_m - 2(2n + 1)^{-2k + 8} - 2i > 2 - 2(2n + 1)^{-2k + 8} > (2n + 1)^{-1} $$ if $k$ is sufficiently large. As before using Lemma 2.11 we have that $h_{4, m} = h_{8, m} = 1$ and combining these bounds we find that $$ o_m > (2n + 1)^{-1} $$ \begin{itemize} \item Case 4: $w_1w_2\dots w_k \not\in P_n \cup D_n$ for some $k \in \{1, 2, \dots, m - 1\}$ \end{itemize} In this case we know that $h_{2, m} \ge 0$ by Lemma 2.9, so we have $$ \frac{|h_{1, m}|}{h_{2, m}} \ge 0 $$ and by Lemma 2.11 we know that $0 \le h_{4, m} + h_{8, m} \le 1$ so $$ o_m \ge 0 + 2 - h_{4, m} - h_{8, m} \ge 1 > (2n + 1)^{-1} $$ \bigskip \noindent Thus $o_m \in (0, (2n + 1)^{-1})$ if $w \in D_n$ and $o_m > (2n + 1)^{-1}$ otherwise, as desired.\qed \bigskip \noindent We may now proceed to show the main theorem of this section, an analogue of Theorem 1.11 for GRUs: \bigskip \noindent {\bf{Theorem 2.13}}. For any context-free language $L$ suppose we relabel and write $L = D_n \cap R$ for some regular language $R$, whose corresponding minimum DFA has $r$ states. Then there exists a GRU with a hidden layer of size $8 + 2nr$ whose $(0, (2n + 1)^{-1})$-language is $L$. \bigskip \noindent {\it{Proof}}. This follows by combining the GRUs from the proofs of Theorems 2.1 and 2.12, as we did for simple RNNs in the proof of Theorem 1.11.\qed \bigskip \noindent {\bf{Discussion 2.14}}. A critical idea in this section was to use the fact that $\text{tanh}(x) = x + O(x^2)$ near $x = 0$, and in fact this idea can be used for any activation function with a well-behaved Taylor series expansion around $x = 0$. \bigskip \noindent {\bf{Discussion 2.15}}. We ``cheated" a little bit by allowing $\infty$ edge weights and by having $o_t = f(h_t)$ where $f$ wasn't quite linear. However, $\infty$ edge weights make sense in the context of allowing infinite precision, and simple nonlinear functions over the hidden nodes are often used in practice, like the common softmax activation function. \section{Suggestions for Further Research} We recognize two main avenues for further research. The first is to remove the necessity for infinite edge weights in the proof of Theorem 2.13, and the second is to extend the results of Theorems 1.11 and 2.13 to Turing recognizable languages. \bigskip \noindent In the proof of Lemma 2.11, edge weights of $\infty$ are necessary for determining whether a hidden node ever becomes negative. Merely using large but finite weights does not suffice, because the values in the hidden state that they will be multiplied with are rapidly decreasing. Their product will vanish, and thus we would not be able to utilize the squashing properties of common activation functions as we did in the proof of Lemma 2.11. Currently we believe that it is possible to prove that GRUs are as computationally powerful as PDAs without using infinite edge weights, but are unaware of a method to do so. \bigskip \noindent Because to the our knowledge there is no analogue of the Chomsky-Sch$\ddot{\text{u}}$tzenberger Theorem for Turing recognizable languages, it seems difficult to directly extend our methods to prove that recurrent architectures are as computationally powerful as Turing machines. However, just as PDAs can lazily be described as a DFA with an associated stack, it is well-known that Turing machines are equally as powerful as DFAs with associated queues, which can be simulated with two stacks. Such an approach using two counters was used in proofs in [6], [8] to establish that RNNs with arbitrary precision can emulate Turing machines. We believe that an approach related to this fact could ultimately prove successful, but it would be more useful if set up as in the proofs above in a way that is faithful to the architecture of the neural networks. Counter automata of this sort are also quite unlike the usual implementations found for context-free languages or their extensions for natural languages. Work described in [10] demonstrates that in practice, LSTMs cannot really generalize to recognize the Dyck language $D_2$. It remains to investigate whether any recent neural network variation does in fact readily generalize outside its training set to “out of sample” examples. This would be an additional topic for future research. \newpage \section*{A.1. Simple RNN $D_2$ Examples} Consider the RNN described in the proof of Theorem 1.10 for $n = 2$. We will show the evolution of its hidden state as it reads various inputs: \begin{itemize} \item Input: $w = (_2(_1)_1(_1(_2)_2)_1)_2$ \end{itemize} For this example we obtain \begin{align*} h_0 &= [0\ \ 0\ \ 0\ \ 0\ \ 0\ \ 0]^T\\ h_1 &= [0.8\ \ 0\ \ 0\ \ 0\ \ 0\ \ 0]^T\\ h_2 &= [0.56\ \ 0\ \ 0\ \ 0\ \ 0\ \ 0]^T\\ h_3 &= [0\ \ 0.8\ \ 0\ \ 0\ \ 0\ \ 0]^T\\ h_4 &= [0.56\ \ 0\ \ 0\ \ 0\ \ 0\ \ 0]^T\\ h_5 &= [0.912\ \ 0\ \ 0\ \ 0\ \ 0\ \ 0]^T\\ h_6 &= [0\ \ 0.56\ \ 0\ \ 0\ \ 0\ \ 0]^T\\ h_7 &= [0\ \ 0.8\ \ 0\ \ 0\ \ 0\ \ 0]^T\\ h_8 &= [0\ \ 0\ \ 0\ \ 0\ \ 0\ \ 0]^T\\ o_8 &= 0 \end{align*} \begin{itemize} \item Input: $w = (_1)_1(_2(_1)_1$ \end{itemize} For this example we obtain \begin{align*} h_0 &= [0\ \ 0\ \ 0\ \ 0\ \ 0\ \ 0]^T\\ h_1 &= [0.4\ \ 0\ \ 0\ \ 0\ \ 0\ \ 0]^T\\ h_2 &= [0\ \ 0\ \ 0\ \ 0\ \ 0\ \ 0]^T\\ h_3 &= [0.8\ \ 0\ \ 0\ \ 0\ \ 0\ \ 0]^T\\ h_4 &= [0.56\ \ 0\ \ 0\ \ 0\ \ 0\ \ 0]^T\\ h_5 &= [0\ \ 0.8\ \ 0\ \ 0\ \ 0\ \ 0]^T\\ o_5 &= 0.8 \end{align*} \begin{itemize} \item Input: $w = (_2)_1(_1)_2)_2$ \end{itemize} For this example we obtain \begin{align*} h_0 &= [0\ \ 0\ \ 0\ \ 0\ \ 0\ \ 0]^T\\ h_1 &= [0.8\ \ 0\ \ 0\ \ 0\ \ 0\ \ 0]^T\\ h_2 &= [0\ \ 2\ \ 0\ \ 0\ \ 1\ \ 0]^T\\ h_3 &= [0.8\ \ 5\ \ 0\ \ 0\ \ 5\ \ 1]^T\\ h_4 &= [0\ \ 25\ \ 0\ \ 0\ \ 24\ \ 6]^T\\ h_5 &= [0\ \ 121\ \ 0\ \ 0\ \ 120\ \ 30]^T\\ o_5 &= 271 \end{align*} \newpage \section*{A.2. GRU $D_2$ Examples} Consider the GRU described in the proof of Theorem 2.12 for $n = 2$ and $k = 5$. We will show the evolution of its hidden state as it reads various inputs: \begin{itemize} \item Input: $w = (_2(_1)_1(_1(_2)_2)_1)_2$ \end{itemize} For this example we obtain \begin{align*} h_0 &= [2.4\text{e-}02\ \ 1.0\ \ 1.0\ \ 1.0\ \ 2.4\text{e-}02\ \ 1.0\ \ 1.0\ \ 1.0]^T\\ h_1 &= [2.58\text{e-}04\ \ 3.20\text{e-}04\ \ 3.20\text{e-}04\ \ 1.0\ \ 1.3\text{e-}04\ \ 3.20\text{e-}04\ \ 3.20\text{e-}04\ \ 1.0]^T\\ h_2 &= [5.74\text{e-}08\ \ 1.02\text{e-}07\ \ 1.02\text{e-}07\ \ 1.0\ \ 9.02\text{e-}08\ \ 1.02\text{e-}07\ \ 1.02\text{e-}07\ \ 1.0]^T\\ h_3 &= [2.64\text{e-}11\ \ 3.28\text{e-}11\ \ 3.28\text{e-}11\ \ 1.0\ \ 1.33\text{e-}11\ \ 3.28\text{e-}11\ \ 3.28\text{e-}11\ \ 1.0]^T\\ h_4 &= [5.88\text{e-}15\ \ 1.05\text{e-}14\ \ 1.05\text{e-}14\ \ 1.0\ \ 9.24\text{e-}15\ \ 1.05\text{e-}14\ \ 1.05\text{e-}14\ \ 1.0]^T\\ h_5 &= [3.06\text{e-}18\ \ 3.36\text{e-}18\ \ 3.36\text{e-}18\ \ 1.0\ \ 1.93\text{e-}18\ \ 3.36\text{e-}18\ \ 3.36\text{e-}18\ \ 1.0]^T\\ h_6 &= [6.02\text{e-}22\ \ 1.07\text{e-}21\ \ 1.07\text{e-}21\ \ 1.0\ \ 9.50\text{e-}21\ \ 1.07\text{e-}21\ \ 1.07\text{e-}21\ \ 1.0]^T\\ h_7 &= [2.77\text{e-}25\ \ 3.44\text{e-}25\ \ 3.44\text{e-}25\ \ 1.0\ \ 1.39\text{e-}25\ \ 3.44\text{e-}25\ \ 3.44\text{e-}25\ \ 1.0]^T\\ h_8 &= [2.64\text{e-}30\ \ 1.1\text{e-}28\ \ 1.1\text{e-}28\ \ 1.0\ \ 2.64\text{e-}30\ \ 1.1\text{e-}28\ \ 1.1\text{e-}28\ \ 1.0]^T\\ o_8 &= 0.024 \end{align*} \begin{itemize} \item Input: $w = (_1)_1(_2(_1)_1$ \end{itemize} For this example we obtain \begin{align*} h_0 &= [2.4\text{e-}02\ \ 1.0\ \ 1.0\ \ 1.0\ \ 2.4\text{e-}02\ \ 1.0\ \ 1.0\ \ 1.0]^T\\ h_1 &= [1.30\text{e-}04\ \ 3.20\text{e-}04\ \ 3.2\text{e-}04\ \ 1.0\ \ 2.58\text{e-}04\ \ 3.20\text{e-}04\ \ 3.20\text{e-}04\ \ 1.0]^T\\ h_2 &= [2.46\text{e-}09\ \ 1.02\text{e-}07\ \ 1.02\text{e-}07\ \ 1.0\ \ 2.48\text{e-}09\ \ 1.02\text{e-}07\ \ 1.02\text{e-}07\ \ 1.0]^T\\ h_3 &= [2.64\text{e-}11\ \ 3.28\text{e-}11\ \ 3.28\text{e-}11\ \ 1.0\ \ 1.33\text{e-}11\ \ 3.28\text{e-}11\ \ 3.28\text{e-}11\ \ 1.0]^T\\ h_4 &= [5.88\text{e-}15\ \ 1.05\text{e-}14\ \ 1.05\text{e-}14\ \ 1.0\ \ 9.24\text{e-}15\ \ 1.05\text{e-}14\ \ 1.05\text{e-}14\ \ 1.0]^T\\ h_5 &= [2.70\text{e-}18\ \ 3.36\text{e-}18\ \ 3.36\text{e-}18\ \ 1.0\ \ 1.36\text{e-}18\ \ 3.36\text{e-}18\ \ 3.36\text{e-}18\ \ 1.0]^T\\ o_5 &= 0.805 \end{align*} \begin{itemize} \item Input: $w = (_2)_1(_1)_2)_2$ \end{itemize} For this example we obtain \begin{align*} h_0 &= [2.4\text{e-}02\ \ 1.0\ \ 1.0\ \ 1.0\ \ 2.4\text{e-}02\ \ 1.0\ \ 1.0\ \ 1.0]^T\\ h_1 &= [2.58\text{e-}04\ \ 3.20\text{e-}04\ \ 3.20\text{e-}04\ \ 1.0\ \ 1.30\text{e-}04\ \ 3.20\text{e-}04\ \ 3.20\text{e-}04\ \ 1.0]^T\\ h_2 &= [2.07\text{e-}07\ \ 1.02\text{e-}07\ \ 1.02\text{e-}07\ \ 1.0\ \ -2.02\text{e-}07\ \ 1.02\text{e-}07\ \ 1.02\text{e-}07\ \ 1.0]^T\\ h_3 &= [2.64\text{e-}11\ \ 3.28\text{e-}11\ \ 3.28\text{e-}11\ \ 1.0\ \ 1.33\text{e-}11\ \ 3.28\text{e-}11\ \ 3.28\text{e-}11\ \ 0.0]^T\\ h_4 &= [2.52\text{e-}16\ \ 1.05\text{e-}14\ \ 1.05\text{e-}14\ \ 1.0\ \ 2.52\text{e-}16\ \ 1.05\text{e-}14\ \ 1.05\text{e-}14\ \ 0.0]^T\\ h_5 &= [-1.30\text{e-}17\ \ 3.36\text{e-}18\ \ 3.36\text{e-}18\ \ 1.0\ \ -6.31\text{e-}18\ \ 3.36\text{e-}18\ \ 3.36\text{e-}18\ \ 0.0]^T\\ o_5 &= 4.88 \end{align*} \newpage
{'timestamp': '2019-06-20T02:06:03', 'yymm': '1906', 'arxiv_id': '1906.06349', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06349'}
arxiv
\section{Background} In this section, we recall the standard EFG model and the more recent notions of augmented information sets, public states, and subgames. \subsection{Extensive-form games} We focus on two-player zero-sum extensive-form games with imperfect information. Based on~\cite{osborne1994course}, game $G$ can be described by \begin{itemize} \item $\mathcal{H}$ -- the set of \defword{histories}, representing sequences of actions. \item $\mathcal{Z}$ -- the set of terminal histories (those $z\in \mathcal H$ which are not a prefix of any other history). We use $g \sqsubset h$ to denote the fact that $g$ is equal to or a prefix of $h$, and extend this notation to subsets of $\mathcal H$ as $A \sqsubset B \iff (\exists g \in A) (\exists h \in B) : g \sqsubset h$. \item For a \defword{non-terminal history} $h\in \mathcal H\setminus \mathcal Z$, $\mathcal A(h) := \{ a \, | \ ha \in \mathcal H \}$ is the set of actions available at a . \item $\mathcal N = \{1, \dots, N\}$ is the \defword{player set}, where $c$ is a special player, called ``chance'' or ``nature''. \item $\mathcal P : \mathcal H \setminus \mathcal Z \rightarrow \mathcal N \cup \{ c \}$ is the \defword{player function} partitioning non-terminal histories into $\mathcal H_p$, $p=1,\dots,N,c$ depending on which player acts at $h$. \item \defword{The strategy of chance} is a fixed probability distribution $\sigma_c$ over actions in $\mathcal H_c$. \item The \defword{utility function} $u=(u_p)_{p\in \mathcal N}$ assigns to each terminal history $z$ a reward $u_p(z)\in \mathbb{R}$ received by each player upon reaching $z$. \item The \defword{information-partition} $\mathcal I = (\mathcal I_p)_{p\in \mathcal N}$ captures the imperfect information of $G$. For each player, $\mathcal I_p$ is a partition of $\mathcal H_p$. If $g,h\in \mathcal H_i$ belong to the same $I\in \mathcal I_p$ then $p$ cannot distinguish between them. For each $I \in \mathcal I_p$, the available actions $\mathcal A(h)$ are the same for each $h \in I$, and we overload $\mathcal A(\cdot)$ as $\mathcal A(I) := \mathcal A(h)$. We only consider games with \defword{perfect recall}, where the players remember their past actions and the information sets visited so far. \end{itemize} We focus on two-player \defword{zero-sum games}, where $\mathcal N = \{1, 2\}$ and $u_2 = - u_1$. However, this assumption is only truly necessary for results related to optimal game values (Section~\ref{sec:theory}). A \defword{behavioral strategy} $\sigma_p \in \Sigma_p$ of player $p$ assigns to each $I\in \mathcal I_p$ a probability distribution $\sigma_p(I)$ over available actions $a\in \mathcal A(I)$. A tuple $\sigma = (\sigma_p)_{p\in \mathcal N}$ is called a \defword{strategy profile}. The~\defword{expected utility} for player $i$ of a strategy profile $\sigma$ is $u_p(\sigma) := \mathbb E_{z\sim\sigma} \, u_p(z)$. The~profile $\sigma$ is an \defword{$\epsilon$-Nash equilibrium} if the benefit of switching to some alternative $\sigma'_p$ is limited by $\epsilon$, i.e., $\forall i \in N : \max_{\sigma'_p \in \Sigma_p} u_p(\sigma_p', \sigma_{-p}) - u_p(\sigma) \le \epsilon$. When $\epsilon = 0$, the profile is called a Nash equilibrium. It is a standard result that in two-player zero-sum games, all $\sigma^*\in \textrm{NE}$ have the same $u_p(\sigma^*)$. The \defword{exploitability} $\textnormal{expl}(\sigma)$ of $\sigma \in \Sigma$ is the average of exploitabilities $\textnormal{expl}_i(\sigma_p)$, $p=1,2$, where \begin{equation*} \textnormal{expl}_p(\sigma_p) := u_p(\sigma^*) - \min_{\sigma_{-p} \in \Sigma_{-p}} u_p(\sigma_p,\sigma_{-p}). \end{equation*} \subsection{Augmented information sets and subgames} To speak about the information available to player $i$ in histories where he doesn't act, we will use the augmented sets ${\mathcal I}^\textnormal{aug}_p$ introduced in \cite{CFR-D}.\footnote{However, our results would still hold if we replaced ${\mathcal I}^\textnormal{aug}_p$ by a different ``augmented information partition'', i.e. a partition $\mathcal J_p$ of $\mathcal H$ which coincides with $\mathcal I_p$ on $\mathcal H_p$ and for which $(\mathcal J_p, \sqsubset )$ forms a (topological) tree w.r.t. the partial order $I \sqsubset J \iff \exists g\in I, h\in J : g \sqsubset h$.} For $p \in \mathcal N$ and $h\in \mathcal H\setminus \mathcal Z$, we define the $p$'s observation-action history $\vec O_p(h)$ in $h$ as the sequence $(I_1,a_1,I_2,a_2,\dots)$ of the information sets visited and actions taken by $p$ on the path to $h$ (incl. $I\ni h$ if $h\in \mathcal H_p$). Two histories $g,h\in \mathcal H\setminus \mathcal Z$ belong to the same \defword{augmented information set} $I\in \mathcal I_p^{\textnormal{aug}}$ if $\vec O_p(g) = \vec O_p(h)$. Clearly $\mathcal I_p^{\textnormal{aug}}$ coincides with $\mathcal I_p$ on $\mathcal H_p$. We assume all information gets revealed at the end of the game, and thus ${\mathcal I}^\textnormal{aug}_p \ni \{z\}$ for each $z\in \mathcal Z$. For $I,J \in \mathcal I_p^\textnormal{aug}$, we define $I \sqsubset J \iff \exists g\in I, h\in J : g \sqsubset h$. \begin{remark}[Thick information sets] \cite{MCCR} note that in general EFGs, augmented information sets can be ``thick'' -- i.e. they can contain both some $h\in \mathcal H$ and it's parent $g\neq h$. Since it is straightforward to circumvent this issue by only considering the \defword{upper frontier} (\cite{halpern2016upperFrontier,halpern1997upperFrontier}) of each $I$, we ignore the issue by assuming none of the discussed domains contains thick augmented information sets. \end{remark} Public states are super-sets of elements of ${\mathcal I}^\textnormal{aug}_p$ that capture the information that everybody knows: \begin{definition}\label{def:publ_state} Let $g\sim h \overset{\textrm{def.}}\iff \vec O_1(g)=\vec O_1(h) \lor \dots \lor \vec O_N(g)=\vec O_N(h)$. A \defword{public tree} is any partition $\mathcal S$ of $\mathcal H$ that forms a tree and is closed under $\sim$. Its elements are called \defword{public states}. \end{definition} Using the concept of public states, \cite{MCCR} define a subgame in EFGs as follows. \begin{definition}\label{def:subgame} A \defword{subgame} $G(S)$ rooted at a~public state $S\in \mathcal S$ is the set $\{ h\in \mathcal H | \ \exists g \in S: g\sqsubset h \}$. \end{definition} \section{Conclusion} We reviewed the properties of reach probabilities and gave a definition of the notion of range that can be applied not just in poker, but in any extensive-form game. We showed that our definition of range is equivalent to several other range-like variables and argued against defining range intuitively as ``the probability of the real situation being $X$ conditional on the player seeing $Y$''. We also listed several equivalent descriptions of a value of a strategy, and contrasted this with a more complicated notion of optimal value. We gave examples illustrating that any definition of optimal value has to take range into account, and that even with a fixed range, optimal values don't have to be unique. However, any vector of optimal values can serve as a heuristic for depth-limited search in imperfect information EFGs. \section*{Acknowledgments} This work was supported by Czech science foundation grant no. 18-27483Y and RCI CZ.02.1.01/0.0/0.0/16 019/0000765. \section{Motivation: depth-limited solving in imperfect information games}\label{sec:cfr} We now describe the CFR algorithm, recall two depth-limited solving algorithms that build on top of it, and discuss their connection to the present paper. For a strategy $\sigma\in \Sigma$, $I\in \mathcal I_i$ and $a\in \mathcal A(I)$, we define the counterfactual regret for not playing $a$ in $I$ under $\sigma$ as \begin{equation} r_p^\sigma(I,a) := Q_{i,c}^{\sigma} (I,a) - V_{i,c}^\sigma (I) \end{equation} and define the corresponding (cumulative) \defword{immediate counterfactual regret} as \[ \bar R^T_{i,\textnormal{imm}} (I) := \! \max_{a\in \mathcal A(I)} \bar R^T_{i,\textnormal{imm}} (I,a) := \! \max_{a\in \mathcal A(I)} \frac{1}{T} \sum_{t=1}^T r_p^{\sigma^t}(I,a) .\] The \defword{Counterfactual Regret minimization} (CFR) algorithm \cite{CFR} works by independently minimizing $\bar R^T_{i,\textnormal{imm}} (I)$ at each $I \in \mathcal I$. Its average strategy $\bar{\sigma}^T$ provably converges to a NE \cite[Theorem 1]{MCCFR}. CFR usually traverses the whole game tree in depth-first search in each iteration. On the way from the root to leafs, it computes the reach probabilities of individual players and on the way back, it computes the expected utilities and updates the regrets. \defword{CFR-D} \cite{CFR-D} is a ``decomposition'' variant of CFR that computes the NE strategy for only a limited number of first moves in the game, called \defword{trunk}. In each iteration, it (I) computes the reach probabilities at the end of the trunk, (II) computes the Nash equilibrium in each subgame rooted at the bottom of the trunk given the fixed reach probabilities, (III) computes counterfactual best response values in the root of the subgame (w.r.t the trunk strategy extended by the subgame NE), and (IV) uses the values from (III) to update the regrets and strategy in the trunk via CFR. Suppose that $\mu$ is a strategy defined in a trunk $T\subset \mathcal H$. The standard variant of CFR-D solves each subgame $G(S,\textnormal{rng}^\mu(S))$ at the bottom of $T$ using CFR, this subgame-solving part of the algorithm (\texttt{SubgameValues} method, \cite[Section 5.3.1]{Neil_thesis}) can be instantiated by any mapping $\nu_p : \mathcal I_p(S) \to \mathbb{R}$ for which \begin{equation}\label{eq:CFR-D_assumptions} \left( \exists \sigma \in \Sigma, \ \textnormal{rng}^\sigma(S) = r \right) : \sigma|_{G(S)} \textnormal{ is a NE in } G(S,r) \ \& \ \nu_p(I) = \max_{\sigma'_p} V_{p,c}^{\sigma'_p, \sigma_{-p}}(I) . \end{equation} Eventually, one might wish to use a depth-limited solver that is more scaleable than CFR-D: \defword{Continual resolving} \citep{DeepStack,MCCR} utilizes the same decomposition principle as CFR-D, but it adds the option to start the search not just from the root, but rather from any public state. DeepStack \cite{DeepStack} is a poker-specific instance of CR. To solve subgames, it uses a neural network trained on a large number of sample subgame solutions. \section{Introduction} Depth-limited look-ahead game solving with heuristic evaluation function recently lead to beating human professionals in go~\cite{alphaZero} and poker~\cite{DeepStack}. While for perfect infomation games, it was a well established methodology since the very beginning \cite{shannon1950pcp}, creating a theoretically sound depth-limited solving in imperfect-information games is substantially more difficult. One key complication is that, in imperfect-information games, it is not possible to define a value of a single state of a game in isolation. Instead, the value depends on the other states that the players consider likely in a particular situation, on the states that they think their opponent considers likely, and so on. Existing applications of theoretically sound depth-limited look-ahead game solving are limited to the game of poker. Depth-limited continual resolving in DeepStack \cite{DeepStack} enabled human-speed expert-level game play with computing resources commonly available in a commodity laptop. \citet{brown2018depth} used depth-limited solving to create a poker bot, which outperforms the strongest submissions from Annual Computer Poker Competition and can be build form scratch on a common desktop. Alternative approaches for creating top-performing poker bots usually require a supercomputer \cite{bowling2015heads,brown2017superhuman}. This success of depth-limited game solving in an imperfect-information game has never been replicated beyond the Texas hold'em poker domain. Texas hold'em has a very particular structure of the available information. After the initial cards are dealt, all the following actions of the players, as well as chance, are pefectly observable. As a result, the amount of hidden information is constant throughout the game. Furthermore, since the players' moves alternate, it is always clear how many actions has each player performed. However, the standard extensive-form game (EFG) framework describes many games which do not enjoy these properties. For example, in blind chess \cite{Ciancarini2010}, we may learn we lost a piece, but not necessarily which opponent's piece took it. In visibility-based pursuit-evasion \cite{raboin2010strategy}, we know the opponent stayed hidden, but not in which direction they moved. In phantom games \cite{teytaud2011lemmas}, we may learn it is our turn to play, but not how many illegal moves has the opponent attempted. Heuristic evaluation function used in DeepStack has been defined in poker terms. The input is the probability of each player holding distinct pairs of cards in their hand in the evaluated situation; the output is the expected number of chips a player can win with their cards if the player played to reach the evaluated situation. It is not clear how to generalize this definition to other games, or even whether the value function they approximate is well-defined. In this paper, we define value functions analogous the DeepStack's heuristic evaluation for arbitrary extensive form game. We formally prove that the minimal set of game states necessary to define the value corresponds to the common knowledge of the players. Furthermore, we prove several properties of the value functions, which are useful for their approximation using machine learning models. We show that the inputs and outputs of the value functions may be represented in several ways with different structure. None of the input-output mappings is unique, hence, the value functions are, strictly speaking, not always functions. However, this is not a fundamental problem, because the possible outputs form a convex set where any element is a suitable output for depth-limited solving. \section{Appendix} \input{proofs} \end{document} \subsection{Conditional reach probabilities for unreachable \texorpdfstring{$I$}{I}}\label{sec:app:reach_probs} We now aim to define the conditional reach probability for $I\sqsubset J$, $I,J\in {\mathcal I}^\textnormal{aug}_p$. To avoid undefined behavior in cases when $\eta^\sigma(I)=0$, we define the ``noisy version'' of $\sigma$ as $\sigma^n(I,a) := (1-\frac{1}{n}) \sigma(I,a) + \frac{1}{n}\frac{1}{|\mathcal A(I)|}$ and set, for $h\in I \in {\mathcal I}^\textnormal{aug}_p$, \begin{align} \eta^\sigma(h|I) := & \lim_{n\to\infty} {\mathbf{P}}_{\sigma^n} \left[ h \textnormal{ reached} \mid I \textnormal{ reached} \right] \\ = & \lim_{n\to\infty} \frac{\eta^{\sigma^n}(h)}{\eta^{\sigma^n}(I)} = \lim_{n\to\infty} \frac{ \eta^{\sigma^n}_{-p}(h) }{ \eta^{\sigma^n}_{-p}(I) } . \end{align} \noindent Note that ``$\eta^\sigma_{-p}(h|I)$'' would coincide with $\eta^\sigma(h|I)$, and $\eta^\sigma_p(h|I)$ wouldn't make any sense. Equipped by this tool, we define the reach probability of $J$ conditional on being in $I$ as \begin{equation*} \eta^\sigma(I,J) := \sum_{g\in I} \eta^\sigma(g|I) \sum_{g \sqsubset h \in J} \eta^\sigma(g,h) . \end{equation*} The analogous definition works for $\eta^\sigma_{-p}(I,J)$ and, denoting $\eta^\sigma_p(I,J) := \eta^\sigma_p(g_p,h_J)$ for arbitrary choice of $I \ni g_p \sqsubset h_J \in J$, leads to $\eta^\sigma(I,J) = \eta^\sigma_p (I,J) \eta^\sigma_{-p}(I,J)$. When $\eta^\sigma(I)>0$, these definitions coincide with the intuitive definition $\eta^\sigma_{(\cdot)}(I,J) = \eta^\sigma_{(\cdot)}(J) / \eta^\sigma_{(\cdot)}(I)$. \begin{remark}[Properties of $\eta^\sigma(\cdot|I)$]\label{rem:cond_r_probs} While the conditional reach probability is defined as a limit, it is straightforward to check that it can always be rewritten as one of the following cases: \begin{itemize} \item When $\eta^\sigma(I)>0$, $\eta^\sigma(h|I)$ is actually equal to the probability of being in $h$ conditional of being in $I$. \item When we at least have $\eta^\sigma_{-p}(I)>0$, $\eta^\sigma(h|I) = \eta^\sigma_{-p}(h) / \eta^\sigma_{-p}(I)$ is the same conditional probability under the assumption that $p$ played to reach $I$. \item Finally, when even $\eta^\sigma_{-p}(I)$ is zero, $\eta^\sigma(h|I) = \eta^{\textnormal{rnd}}(h) / \eta^{\textnormal{rnd}}(I)$ is equal to the same conditional probability, but under the assumption that both players act (uniformly) randomly. \end{itemize} \end{remark} \subsection{Properties of non-optimal value functions} The following two theorems summarize the properties of $V_{p}^\sigma$ and $V_{p,c}^\sigma$. By a \emph{slice} of ${\mathcal I}^\textnormal{aug}_p$ below (not necessarily directly below) $I$ we mean any collection $SL\subset {\mathcal I}^\textnormal{aug}_p$ s.t. (i) $(\forall J \in SL) : J \sqsupset I$ (ii) $J\sqsubset J'$ for no distinct $J,J'\in {\mathcal I}^\textnormal{aug}_p$ (iii) $SL$ is a maximal set with this property. By $\textnormal{ims}(I)$, we denote the set of \emph{immediate successors} of $I$ in ${\mathcal I}^\textnormal{aug}_p$. \newcounter{resumeCounter} \begin{restatable}[Properties of $V_p^\sigma$]{theorem}{propOfV} \label{thm:eq_descr_V} For $\sigma\in \Sigma$, $p$, and $V : {\mathcal I}^\textnormal{aug}_p \to \mathbb{R}$, the following are equivalent: \begin{enumerate}[(1)] \item $(\forall I \in {\mathcal I}^\textnormal{aug}_p) : V(I) = \sum_{h\in I} \eta^\sigma (h|I) v_p^\sigma(h)$ \hfill (and this is equal to $\sum_{h\in I} \eta_{-p}^\sigma (h|I) v_p^\sigma(h)$ ), \label{case:v_formula} \item $(\forall z \in \mathcal Z ) : V(z) = u_p(z)$ and $(\forall I \in {\mathcal I}^\textnormal{aug}_p \textnormal{ non-terminal}) : V(I) = \sum_{ J \in \textnormal{ims}(I) } \eta^\sigma(I,J) V(J)$, \label{case:v_ims} \item $V=V_p^\sigma$ is the counterfactual utility from \cite{CFR}.\label{case:v_zink} \setcounter{resumeCounter}{\value{enumi}} \end{enumerate} Moreover, if $V$ satisfies (1)-(3), then $V(\textnormal{root}) = u_p(\sigma)$, $V : {\mathcal I}^\textnormal{aug}_p \to [\min_{\mathcal Z} u_p (z), \max_{\mathcal Z} u_p (z)]$, and \begin{enumerate}[(1)] \setcounter{enumi}{\value{resumeCounter}} \item $(\forall I \in {\mathcal I}^\textnormal{aug}_p) (\forall SL \textnormal{ slice below }I) : V(I) = \sum_{J \in SL} \eta^\sigma(I,J) V(J)$. \label{case:v_slice} \end{enumerate} \end{restatable} \begin{proof} We prove the theorem for fully mixed $\sigma$. The general case follows by transition to the limit. The ``and this is equal to...'' case in \ref{case:v_formula} follows from Remark~\ref{rem:cond_r_probs}. \eqref{case:v_formula} $\iff$ \eqref{case:v_zink}: Using the formula $v_p^\sigma(h) = \sum_{h \sqsubset z \in \mathcal Z} \eta^\sigma(h,z) u_p(z)$, we get that $V(I)$ from \eqref{case:v_formula} is equal to $\sum_{h\in I} \frac{\eta^\sigma_{-p}(h)}{\eta^\sigma_{-p}(I)} \sum_{h \sqsubset z \in \mathcal Z} \eta^\sigma(h,z) u_p(z)$, which is the definition used in \cite{CFR}. \eqref{case:v_formula} $\implies$ \eqref{case:v_ims}: Suppose that $V$ satisfies \ref{case:v_formula}. For terminal $z$, $V(z)=u_p(z)$ is a special case of $V(I) = \sum_{h\in I} \eta^\sigma (h|I) v_p^\sigma(h)$. We have \begin{align*} V(I) & = \sum_{h\in I} \eta^\sigma (h|I) v_p^\sigma(h) = \sum_{h\in I} \frac{\eta^\sigma (h)}{\eta^\sigma (I)} \sum_{ J \in \textnormal{ims}(I) } \sum_{h\sqsubset g \in J} \eta^\sigma(h,g) v_p^\sigma(g) \\ & = \sum_{h\in I} \sum_{ J \in \textnormal{ims}(I) } \sum_{h\sqsubset g \in J} \frac{\eta^\sigma (J)}{\eta^\sigma (I)} \frac{\eta^\sigma (g)}{\eta^\sigma (J)} v_p^\sigma(g) = \sum_{ J \in \textnormal{ims}(I) } \eta^\sigma (I,J) \sum_{g \in J} \eta^\sigma (g|J) v_p^\sigma(g) \\ & = \sum_{ J \in \textnormal{ims}(I) } \eta^\sigma (I,J) V(J) . \end{align*} \eqref{case:v_ims} $\implies$ \eqref{case:v_formula}: The converse implication can be shown similarly using backward induction. The ``moreover'' part: $V(\textnormal{root}) = u_p(\sigma)$ follows from \eqref{case:v_formula} because $\eta^\sigma(\textnormal{root})=1$. $V : {\mathcal I}^\textnormal{aug}_p \to [\min_{\mathcal Z} u_p (z), \max_{\mathcal Z} u_p (z)]$ follows from \eqref{case:v_ims} by backward induction. \eqref{case:v_slice} can be derived from \eqref{case:v_formula} in the same way as \eqref{case:v_ims}. \end{proof} \noindent The main advantage of $V_p^\sigma$ over $V_{p,c}^\sigma$ is their easy calculation in leaves \eqref{case:v_ims} and intuitive back-propagation \eqref{case:v_slice}, and hence their more intuitive interpretation as ``utilities expected at $I$''. On the other hand, the non-normalized counterfactual values are harder to compute in leaves -- cf. \eqref{case:v_ims} and (\ref{case:vc_ims}') -- but easier to back-propagate (by (\ref{case:vc_slice}'), their back-propagation only requires $p$'s reach probability). Moreover, the corresponding formula (\ref{case:vc_formula}') doesn't suffer from division by 0 when $I$ is unreachable: \begin{restatable}[Properties of $V_{p,c}^\sigma$]{theorem}{propOfVc} \label{thm:eq_descr_Vc} For $\sigma\in \Sigma$, $p$, and $V_c : {\mathcal I}^\textnormal{aug}_p \to \mathbb{R}$, the following are equivalent: \begin{enumerate}[(1')] \item $(\forall I \in {\mathcal I}^\textnormal{aug}_p) : V_c(I) = \sum_{h\in I} v_{p,c}^\sigma(h)$ \hfill (and this is equal to $\sum_{h\in I} \eta_{-p}^\sigma (h) v_p^\sigma(h)$ ), \label{case:vc_formula} \item $(\forall z \in \mathcal Z ) \! : \! V_c(z) = \eta^\sigma_{-p}(z) u_p(z)$ and $(\forall \{z\} \neq I \in {\mathcal I}^\textnormal{aug}_p) : V_c(I) = \sum_{ J \in \textnormal{ims}(I) } \eta^\sigma_p (I,J) V_c(J)$,\label{case:vc_ims} \item $V_c = V_{p,c}^\sigma = \eta^\sigma_{-p}(\cdot) V_p^\sigma$ is the counterfactual value from \cite{CFR}. \setcounter{resumeCounter}{\value{enumi}} \end{enumerate} Moreover, (1)-(3) implies $V_c(\textnormal{root}) = u_p(\sigma)$, $V_c(I) \in [ \eta^\sigma_{-p}(I) \min u_p (z), \eta^\sigma_{-p}(I) \max u_p (z)]$, and \begin{enumerate}[(1')] \setcounter{enumi}{\value{resumeCounter}} \item $(\forall I \in {\mathcal I}^\textnormal{aug}_p) (\forall SL \textnormal{ slice below }I) : V_c(I) = \sum_{J \in SL} \eta^\sigma_p(I,J) V_c(J)$. \label{case:vc_slice} \end{enumerate} \end{restatable} \noindent The proof of this theorem is analogous to the proof of Theorem~\ref{thm:eq_descr_V}. \subsection{Proofs}\label{sec:app:proofs} In this section, we give the full proofs for the theoretical results presented in the paper. \sosProps* \begin{proof} (i): Suppose that a restriction of some $\sigma$ is not a NE in $G(S,r)$. Since the game starts by a chance node, there must be some chance action $a_h$ at the root s.t. one of the players can change their action at $I_p(h)$ or at one of the infosets below it. This is equivalent to $V_p^\sigma(I_p(h))$ not being equal to $\max \{ V_{p}^{\sigma'_p, \sigma_{-p}}(I_p(h)) \mid \sigma'_p \in \Sigma_p \}$, and thus $\sigma$ doesn't belong to $\textrm{CROS} (S,r)$. (ii): This follows from the fact that the root utility in $G(S,r)$ is equal to $\sum_{I \in \mathcal I_p(S)} \eta^\sigma(\textnormal{root},I) V_p^\sigma(I)$, which can further be rewritten as $\sum_{I \in \mathcal I_p(S)} \frac{\eta^\sigma(I)}{\eta^\sigma(S} V_p^\sigma(I)$ (where $\sigma$ the $G(S,r)$ strategy extended in a way that is compatible with $r$). If the strategy $\sigma$ is fully mixed above $S$, each of the fractions is non-zero, and each of the $V_p^\sigma(I)$-s has to be maximal. (iii): Let $\mu$ be a strategy satisfying $\textnormal{rng}^\mu(S)=r$. For $n \in \mathbb{N}$, denote by $\mu^t$ the fully mixed strategy defined as $\mu^t(I,a) := (1-\frac{1}{n}) \mu(I,a) + \frac{1}{n} \frac{1}{| \mathcal A(I) |}$ and by $r^n$ the corresponding range at $S$. Moreover, let $\rho^n$ be some NE of $G(S,r^n)$ and denote by $\sigma^n$ the strategy obtained by replacing $\mu^n$ by $\sigma^n$ in the subgame $G(S)$. Since the space of strategies is compact, we can select a sub-sequence $(\sigma^{n_k})_{k\in \mathbb{N}}$ that converges to some $\sigma \in \Sigma$ (to simplify the notation, we assume that $n_k=k$, so $\sigma_n \to \sigma$). We shall prove that $\sigma \in \textrm{CROS} (S,r)$. Firstly, we have $\textnormal{rng}^\sigma(S)=r$ since $\mu^n$ coincides with $\sigma^n$ above $S$ (and we have $\mu^n \to \mu$ and $\textnormal{rng}^\mu(S)=r$. Moreover, each $\sigma^n$ belongs to $\textrm{CROS} (S,r^n)$ by (ii), so we have $V_p^{\sigma^n}(I) = \max \{ V_{p}^{\sigma'_p, \sigma^n_{-p}}(I_p(h)) \mid \sigma'_p \in \Sigma_p \}$. Since the function $V_p^{(\cdot)}(I)$ is continuous in the strategy parameter, we get $V_p^{\sigma}(I) = \max \{ V_{p}^{\sigma'_p, \sigma_{-p}}(I_p(h)) \mid \sigma'_p \in \Sigma_p \}$, which concludes the proof. \end{proof} \CFRDwithNN* \begin{proof} Recall that a counterfactual best-response of player 1 to $\sigma$ is a strategy satisfying $V_{1,c}^{CBR_1(\sigma_2), \sigma_2}(I) = \max_{\sigma'_p} V_{1,c}^{\sigma'_p, \sigma_2}(I)$ Note that the conclusion of the proposition isn't trivial since a convex combination of cf. values $\lambda V^{\sigma'}_{p,c} + (1-\lambda) V^{\sigma''}_{p,c}$ typically \emph{isn't} equal to $V_{p,c}^{\lambda \sigma' + (1-\lambda) \sigma''}$. Firstly, observe that any pair $(W_1, \sigma_2)$ satisfies ``$\sigma_2 \in \Sigma_2$ is a part of NE and $W_1(I) = V_{1,c}^{CBR_1(\sigma_2), \sigma_2}(I)$ for each $I\in \mathcal I_1$'' if and only if $(W_1, r_2(\sigma_2) )$ is a solution to the sequence form dual linear program (LP) (see \cite[(5.10-5.13)]{MAS}), where $r_2(\sigma_2)$ denotes the realization plan corresponding to $\sigma_2$. (The NE part is proven in \cite{MAS}. The CBR part easily follows from \cite[(5.10-5.11)]{MAS} by backward induction.) Denote by $(C)$ the constraint ``a realization plan coincides with $r_2(\sigma)$ outside of $G(S)$''. It follows that a vector $W$ satisfies Eq. \eqref{eq:CFR-D_assumptions} if and only if there is some strategy $\sigma$ for which $(W_1,r_2(\sigma))$ is a solution of the LP (5.10-5.14)\&$(C)$, and analogously for $(W_2, r_1(\sigma))$. Let $\lambda \in (0,1)$, $V'$, $V''$ be as in the proposition, and let $\sigma'$ be s.t. $V'_p(I) = V_p^{CBR_p(\sigma'_{-i}), \sigma'_{-i}} (I)$ for each $I\in \hat S(i)$. Denoting $V'_p(I) := V_p^{CBR_p(\sigma'_{-i}), \sigma'_{-i}} (I)$ for all $I$, we have that the pair $(V'_1, r_2(\sigma') )$ is a solution to $(5.10-5.14)$ \& $(C)$. The same will then hold for $V''$ and (the analogously defined) $\sigma''$. Since the space of all solutions of an LP is convex, the pair $( \lambda V'_1 + (1-\lambda)V''_1, \lambda r_2(\sigma') + (1-\lambda)r_2(\sigma'') )$ is also a solution to this LP. Since $V_1 = \lambda V'_1 + (1-\lambda)V''_1$, the same holds for $V_1$. Since an analogous result is true for $V_2$, the observation we made earlier implies that $V$ is a valid output for the \texttt{SolveSubgame} method. \end{proof} \wellDefined* \begin{proof} By definition of $\textrm{SOS}$, $\sigma$ has to satisfy $V_p^\sigma(I) = \max_{\sigma'_p} V_p^{\sigma'_p, \sigma_{-p}}(I)$ for each $I \in \mathcal I^\textnormal{aug}_p(S)$, and analogous formula holds for $\mu$. Since $\sigma_{-p} = \mu_{-p}$, we get the first part of the proposition. By definition of $\textrm{CBR}$, we have $V_{p,c}^{\textrm{CBR}_p(\sigma_{-p}), \sigma_{-p}}(I) = \max_{\sigma'_p} V_{p,c}^{\sigma'_p, \sigma_{-p}}(I)$. Since $V_{p,c}^{(\cdot)}(I) = \eta_p^{(\cdot)}(I) V_p^{(\cdot)}(I)$, we get the second part as well. \end{proof} \histValAmbig* \begin{proof} This can be witnessed on simple one-player game (Figure~\ref{fig:value_not_unique_2}, left), where the root is a chance node with two actions $A$, $B$ and uniform strategy, where the following two nodes belong to the same $I\in \mathcal I_p$ and have actions $L$, $R$. The utilities are $0$, $1$ for $AL$, $AR$ and $1$, $0$ for $BL$, $BR$. Any strategy in this game is an equilibrium with counterfactual value $V_{1,c}^\sigma(I) = 0.5$, but any $\sigma\neq \nu$ will have different expected utilities and counterfactual values for histories (i.e. $v_{1,c}^\sigma(A)\neq v_{1,c}^\nu(A)$, $v_{1,c}^\sigma(A)\neq v_{1,c}^\nu(A)$, and likewise for $B$). \end{proof} \wholeRangeDep* \begin{proof} Let $G$, $S$, $h_0$, $r$ and $g$ be as in Theorem~\ref{thm:wholeRangeDep}. We set $r'(g) := 0$ (and $r'(h) := r(h)$ for $h\neq g$). We shall prove the theorem by constructing $\widetilde G$ and showing that it has the desired properties. We start by making two simplifying assumptions. First, we assume that each $h\in S$ only has one legal (dummy) action that we denote $d$. In the general case, each $ha$, $hb$ would be extended in the identical manner, complicating the notation, but not introducing any actual challenges. Since the public state cannot be further refined, there exists a sequence of histories satisfying $h_0 \sim h_1 \sim \dots \sim h_n = g$ in $S$. We assume that $h_p \neq h_j$ for $i\neq j$. We only show the proof in the case where both $h_0, h_1$ and $h_{n-1}, h_n$ are indistinguishable by the first player (the proofs of the remaining three cases are similar). (Note that the proof actually only requires the range to be non-zero on each of the histories $h_p$, rather than on the whole $S$.) The game $\widetilde G$ is identical to $G$ at $( \mathcal H \setminus G(S) ) \cup S$, and is defined as follows at $\{ hd \mid h\in S\}$ and below: \begin{itemize} \item For $h \in S \setminus \{h_p \mid i=0,\dots,n \}$, $hd$ is a terminal node with utility 0 (for all strategic considerations, this replaces $S$ by $\{h_p \mid i=0,\dots,n \}$). \item For $h_p$, $i=0,\dots,n-1$, $h_pd$ leads to a matching pennies game (a matrix game with actions $U$, $D$ for player 1, actions $L$, $R$ for player 2, and corresponding utilities $1$ for $U,L$ and $D,R$, resp. $0$ for $U,R$ and $D,L$). \item For $h_n$, $h_nd$ leads to a game where only player 1 acts, choosing between $U$ (utility 0) and $D$ (utility 1). \item The information sets below $h_p$ are defined in such a way that player 1 has to use the same strategy below $h_0$ and $h_1$, $h_2$ and $h_3$, \dots, $h_{n-1}$ and $h_n$, and player 2 has to use the same strategy below $h_1$ and $h_2$, $h_3$ and $h_4$, \dots, $h_{n-2}$ and $h_{n-1}$ (player 2 strategy below $h_0$ is independent of everything else). \end{itemize} Since $h_n$ is unreachable under $r'$, $\widetilde G(S,r')$ is effectively a collection of (interconnected) matching pennies games. It follows that the uniform strategy of both players is a Nash equilibrium (clearly, no player can improve his overall utility). On the other hand, it is \emph{not} a NE strategy in $\widetilde G(S,r)$ (since player 1 could improve his utility be deviating to ``$D$ everywhere''). In particular, $0.5$ is an expected utility of $h_0$ under some NE strategy in $\widetilde G(S,r')$. Suppose that some NE strategy $\sigma$ in $\widetilde G(S,r)$ has $v_1^\sigma(h_0)=0.5$. We will show that such $\sigma$ has to be uniformly random, and thus prove the theorem by contradiction. Firstly, if $\sigma_1$ wasn't uniformly random at the information set $\{h_0d,h_1d\}$, player 2 could increase his overall utility by changing his strategy below $h_0$ to either $L$ or $R$, and thus $\sigma$ wouldn't be a NE. We proceed inductively. We know that $u^\sigma_1(h_0) = 0.5$, and that in $\{h_0d,h_1d\}$, $\sigma_1$ takes both $U$ and $D$ with non-zero probability. If $\sigma_1$ is to be a NE, player 1 has to be indifferent between playing $U$ and $D$ in $\{h_0d,h_1d\}$. Since $v^\sigma_1(h_0) = 0.5$, this can only be achieved if $\sigma_2$ takes both $L$ and $R$ below $h_1$ with the same probability. In particular, $u^\sigma_1(h_1)=0.5$. Since $\widetilde G$ forces the strategy of player 2 to be the same below $h_1$ and $h_2$, we get that $\sigma_2$ is uniformly random below $h_2$ as well. We repeat the argument above for each $h_p$, eventually showing that if the players are to be indifferent between the actions they take with non-zero probability, $\sigma_1$ has to be uniformly random in the whole $\widetilde G(S)$ and $\sigma_2$ has to be uniformly random below $h_1,\dots,h_{n-1}$. Finally, if $\sigma_1$ wasn't uniform below $h_0$ (but was below $h_1$), player 1 could increase his utility by deviating to either $U$ or $D$. This implies that the whole $\sigma$ is uniformly random, which contradicts our earlier observation. \end{proof} \begin{figure} \centering \forestset{ matrix_game/.style = {align=center, rectangle, draw, tier=MG } } \begin{forest} [root, chance, s sep+=0.3\nodesize, [$h_0$,pl1,name=0 [1 0\\0 1, matrix_game ] ] [,pl1 [0] ] [$h_1$,pl1,name=1 [1 0\\0 1, matrix_game ] ] [$h_2$,chance,name=2 [1 0\\0 1, matrix_game ] ] [$h_3$,pl2,name=3 [1 0\\0 1, matrix_game ] ] [$h_4$,pl2,name=4 [1 0\\0 1, matrix_game ] ] [$h_5$,chance,name=5 [0\\1, matrix_game ] ] ] \node [pl1_cl_infoset, fit=(\corners{0})(\corners{1})] {}; \node [infoset, augmented, fit=(2)(\corners{3})] {}; \node [infoset, augmented, fit=(\corners{4})(5)] {}; \node [infoset, opponent, augmented, fit=(\corners{1})(2), inner xsep = 0.1\nodesize] {}; \node [infoset, opponent, fit=(\corners{3})(\corners{4}), inner xsep = 0.1\nodesize] {}; \draw [line_infoset] (0!1) to (1!1); \draw [line_infoset] (2!1) to (3!1); \draw [line_infoset] (4!1) to (5!1); \draw [line_infoset, opponent, bend right] (1!1.south) to (2!1.south); \draw [line_infoset, opponent, bend right] (3!1.south) to (4!1.south); \node[xshift=7em, yshift=-1em, align=right] {choose according to\\$r(h)/\sum_S r(h')$}; \end{forest} \caption{An example of a game $\widetilde G$ used in the proof of Theorem~\ref{thm:wholeRangeDep}.} \label{fig:wholeRangeDep} \end{figure} \begin{figure} \begin{forest} [, chance, l sep-=0.5\nodesize, [A,pl1,name=A, [0] [1] ] [B,pl1,name=B, [1] [0] ] ] \node [pl1_cl_infoset, fit=(\corners{A})(\corners{B})] {}; \end{forest} \hfill \begin{forest} [, pl2, l sep-=0.5\nodesize, [,chance, edge label={node[midway,sloped,above]{PfA}} [,pl1, edge label={node[near start,left]{A}}, [0] ] [,pl1, edge label={node[near start,right]{B}}, [1] ] ] [,chance, edge label={node[midway,sloped,above]{PfB}} [,pl1, edge label={node[near start,left]{A}}, [1] ] [,pl1, edge label={node[near start,right]{B}}, [0] ] ] ] \begin{pgfonlayer}{bg} \draw [line_infoset, bend right] (!11.south) to (!21.south); \node[above,yshift=-0.3em] at ($(!121)!.5!(!211)$) {$I_A$}; \draw [line_infoset, bend left] (!12.north) to (!22.north); \node[above,yshift=0.8\nodesize] at ($(!12)!.5!(!21)$) {$I_B$}; \end{pgfonlayer} \end{forest} \caption{Games where different equilibria produce different expected utilities (left) and information-set values (right). The chance strategies are uniform. (Repeated from the main text.)\label{fig:value_not_unique_appendix}} \end{figure} \optValuesNotUnique* \begin{proof} Indeed, consider $G$ from the right side of Figure~\ref{fig:value_not_unique_appendix}: first to act is the player 2, who decides between preparing for A (PfA) and B (PfB). A chance outcome then randomly (50:50) chooses which of the options A and B actually comes to pass. Finally, player 1 has a dummy action\footnote{While the actions of player 1 are irrelevant in $G$, one can easily modify it such that the inclusion of player 1 is meaningful.} where he observes the chance outcome, but not the action of player 2. Player 1 then receives 0 utility if player 2 guessed the chance event correctly and 1 utility if he guessed incorrectly. The structure of the game implies that any strategy of player 2 is optimal. Moreover, we have $V_1^\sigma(I) \neq V_1^{\sigma'}(I)$ whenever $\sigma_2$ and $\sigma'_2$ are distinct. \end{proof} \section{Revisiting reach probabilities and values} In this section, we take a closer look at reach probabilities, list particularly useful versions of this concept, and use them to give several equivalent definitions of the notion of range. We also clarify the properties of and the relationship between expected utilities and counterfactual values. \subsection{Reach probabilities} We start by introducing the notation related to reach probabilities in EFGs. The~\defword{reach probability} of a history $h\in \mathcal H$ under a strategy $\sigma$ is defined as $\eta^{\sigma}(h)$ the~product of probabilities of taking each action between the root and $h$. The~\defword{counterfactual reach probability} $\eta^\sigma_{-p}(h)$ is defined analogously, except that player $p$ now aims to reach $h$, so the probabilities of his actions are replaced by 1. Finally, player \defword{$p$'s reach probability} $\eta_p^\sigma(h)$ is the probability that they will play to reach $h$, i.e. the quantity missing in $\eta^\sigma_{-p}(h)$ (so we have $\eta^\sigma(h) = \eta^\sigma_p(h) \eta^\sigma_{-p}(h)$). We now extend this notation to ${\mathcal I}^\textnormal{aug}_p$. Note that naively defining $\eta^\sigma_{(\cdot)}(A) := \sum_{h\in A} \eta^\sigma_{(\cdot)}(h)$ for general $A\subset \mathcal H$, such as $\eta_p^\sigma(I)$ for an information set $I$ \emph{not} belonging to $p$, will often result in ``reach probabilities'' that behave nothing like actual probabilities (e.g. having values over 1). The non-problematic part is the (counterfactual) probability of reaching $I\in \mathcal I^\textnormal{aug}_p$, which we simply denote as $\eta^\sigma(I) := \sum_{h \in I} \eta^\sigma(h)$, resp. $\eta^\sigma_{-p}(I) := \sum_{h \in I} \eta^\sigma_{-p}(h)$. Some care needs to be taken with $\eta_p^\sigma(I)$: rather than defining it as the sum over $h\in I$, we set $\eta_p^\sigma(I) := \eta^\sigma_p(h_I)$, where $h_I \in I$ is chosen arbitrarily (since $I\in \mathcal I^\textnormal{aug}_p$, $\eta^\sigma_p(h)$ is the same for all $h\in I$). This ensures that $\eta^\sigma(I) = \eta^\sigma_{-p}(I) \eta^\sigma_p(I)$. For $g\sqsubset h$, $\eta^\sigma_{(\cdot)}(g,h)$ denotes the probability of reaching $h$ conditional on already being in $g$. We compute it analogously to $\eta^\sigma_{(\cdot)}(h)$, except that we only take the product of probabilities of actions between $g$ and $h$. For $h \in I\sqsubset J$ (where $I,J\in {\mathcal I}^\textnormal{aug}_p$) we define the \defword{conditional reach probabilities} as $\eta^\sigma_{(\cdot)}(I,J) := \eta^\sigma_{(\cdot)}(J) / \eta^\sigma_{(\cdot)}(I)$ and denote \begin{equation}\label{eq:cond_reach_p} \eta^\sigma(h|I) := \frac{ \eta^\sigma(h) }{ \eta^\sigma(I) } = \frac{ \eta^\sigma_{-p}(h) }{ \eta^\sigma_{-p} (I) } =: \eta^\sigma_{-p}(h|I) . \end{equation} While the denominator in $\eta^\sigma_{(\cdot)}(I,J)$ and \eqref{eq:cond_reach_p} can be 0, we can extend both notions even to unreachable $I$ (Section~\ref{sec:app:reach_probs}). \subsection{Range in general imperfect information games} In poker, range can be (informally and ambiguously) defined as ``the likelihood of having various private cards in a given situation''. However, a useful formalization of this concept isn't obvious, in particular in EFGs other than poker. One option would be to set ``range of $p$ at $S$ := $\left( \eta^\sigma(I) / \eta^\sigma(S) \right)_{I \in \mathcal I^\textnormal{aug}_p(S)}$'' -- in other words, ``the probability of being in each $I$, conditional on being in the current public state''. However, this definition depends on the strategy of the opponent, and thus a player wouldn't know their own range. (Indeed, just consider the difference between an opponent who plays randomly and an opponent who will always fold unless he is holding two aces.) \begin{restatable}[Equivalent definitions of range]{proposition}{equivRange}\label{prop:range} With the knowledge of $\sigma_1$ and the game rules, we can calculate the following range-like variables for $S\in \mathcal S$ ((4) and (5) are two-player games only): \begin{enumerate}[(1)] \item $\eta^\sigma_1(I)$ for $I\in \mathcal I^\textnormal{aug}_1(S))$ \hfill (information set reach probabilities for player 1), \item $\eta^\sigma_1(h)$ for $h\in S$ \hfill (history reach probabilities for player 1), \item $\eta^\sigma_1(h)$ and $\eta^\sigma_c(h)$ for $h\in S$ \hfill (history reach probabilities for player $1$ and chance), \item $\eta^\sigma_{-2}(J)$ for $J\in \mathcal I^\textnormal{aug}_2(S)$ \hfill (the opponent's counterfactual reach probabilities), \item $\eta^\sigma(h|J)$ for $h\in J \in \mathcal I^\textnormal{aug}_2(S)$ \hfill (conditional probabilities for the opponent's information sets). \end{enumerate} If we forget $\sigma_1$, any of the lines (1)-(3) can be used to recover (1)-(5) via a simple calculation. \end{restatable} \begin{proof} The ``derivations'' $(3) \to (2) \to (1)$ and $(1) \to (2)$ are trivial, since $\eta^\sigma_1(I)$ is defined as $\eta^\sigma_1(h_I)$ for arbitrary choice of $h_I \in I$ (and $\eta^\sigma_1(h)$ is the same for all $h\in I \in {\mathcal I}^\textnormal{aug}_1$). $\eta^\sigma_c(h)$ can always be recovered from the rules of the game, which gives $(2) \to (3)$. $(3) \to (4)$ holds because $\eta^\sigma_{-2}(J) = \sum_{h\in J} \eta^\sigma_c(h) \eta^\sigma_1(h)$. $(3) \to (5)$ holds because $\eta^\sigma(h|J) = \eta^\sigma(h) / \eta^\sigma(J) = \eta^\sigma_{-2}(h) / \eta^\sigma_{-2} (J)$. \end{proof} \noindent The corollary of Proposition~\ref{prop:range} is that among (1)-(3), we are free to use whichever option suits us the best --- (3) is the most descriptive, while (1) requires the least space to store. This becomes relevant for example when using range as an input for a neural network. \begin{definition}[Range]\label{def:range} For $\sigma\in\Sigma$, $\textnormal{rng}^\sigma (S) := \left( \, \eta^\sigma_1(h), \eta^\sigma_2(h), \eta_c(h) \, \right)_{S}$ and $\left( \pi^\sigma(h) \right)_{S}$ denote the \defword{separated} and \defword{joint range} at $S$. The \defword{compact representation} of a range is the tuple $\left( \eta^\sigma_p(I) \right)_{I\in \mathcal I^\textnormal{aug}_p(S)}$ for $p\in \mathcal N$. \end{definition} \subsection{Values of non-optimal strategies} We now define standard and counterfactual values \emph{for a given, typically sub-optimal, strategy}. We start with histories and history-action pairs and, since the players cannot observe histories directly, proceed by extending the notation to augmented information sets and action-infoset pairs. We then list the properties of these values. The use of letters $v$ and $q$ is inspired by and consistent with \cite{srinivasan2018actor} and (apart from using capital letters to differentiate between values of infosets and histories). Player $p$'s \defword{value of} the \defword{history} $h\in \mathcal H$ under $\sigma \in \Sigma$ is the expected utility conditional on visiting $h$: \begin{align*} v^\sigma_p(h) := & \mathbf{E}_{z\sim \sigma} \left[ u_p(z) \mid h \textnormal{ reached} \right] = \sum_{z \sqsupset h} \eta^\sigma(h,z) u_p(z). \end{align*} Analogously, we define the \defword{value of an action} $a\in \mathcal A_p(h)$ taken at $h\in \mathcal H_p$ under $\sigma$: \begin{align*} q^\sigma_p(h,a) := \mathbf{E}_{z\sim \sigma} \left[ u_i(z) \mid h \textnormal{ reached, $a$ taken} \right] = \sum_{z \sqsupset ha} \eta^\sigma(ha,z) u_i(z). \end{align*} \noindent As in MDPs, we have $v^\sigma_{p}(h) := \sum_{a\in \mathcal A_p(h)} \sigma_p(h,a) q^\sigma_{p}(h,a)$. A very useful variant of these concepts are the \defword{counterfactual values} \citep{CFR}, defined as $v^\sigma_{p,c}(h) := \eta^\sigma_{-p}(h) v^\sigma_{p}(h)$ and $q^\sigma_{p,c}(h) := \eta^\sigma_{-p}(h) q^\sigma_{p}(h,a)$. To extend the notation for $I \in {\mathcal I}^\textnormal{aug}_p$, we define $V^\sigma_p(I)$ as the weighted average of $v^\sigma_p(h)$, $h\in I$: \begin{align*} V^\sigma_p(I) := \ & \mathbf{E}_{z\sim \sigma} \left[ u_i(z) \mid I \textnormal{ reached} \right] = \sum_{h\in I} \eta^\sigma(h | I) v_p^\sigma(h). \end{align*} We define $V^\sigma_{p,c}(I) := \eta^\sigma_{-p}(I) V^\sigma_{p}(I)$. The Q-values $Q^\sigma_p(I,a)$ and $Q^\sigma_{p,c}(I,a)$ are defined analogously and satisfy $V^\sigma_{p}(I) = \sum_{a\in \mathcal A_p(I)} \sigma_p(I,a) Q^\sigma_{p} (I,a)$ and $V^\sigma_{p,c}(I) = \sum_{a\in \mathcal A_p(I)} \sigma_p(I,a) Q^\sigma_{p,c} (I,a)$. \section{Optimal Value functions in zero-sum games}\label{sec:theory} While the previous section already describes the notion of value \emph{of a specific strategy}, depth-limited solving requires the notion of ``what would happen if we played this strategy for the next few moves \emph{and then started playing optimally}''. To investigate this stronger notion of a value, we restrict our attention to two-player zero-sum EFGs. \subsection{The definition of optimal values} We first define a set of strategies that are compatible with what has happened in the game so far and ``optimal'' for the upcoming decisions. To get a robust notion of an optimal value, we focus on strategies that not only find the NE of the current subgame, but also play optimally even in the whole root of the game (even its unreachable parts). It suffices to use a slightly relaxed version of ``subgame perfection'', where the strategy \begin{definition}[Compatible root-optimal strategy] Let $r$ be a range at $S\in \mathcal S$. By $\textrm{CROS} (S,r)$ we denote the set of strategies $\sigma \in \Sigma$ that satisfy $\textnormal{rng}^\sigma(S)=r$ and for which $V_{p}^\sigma(I) = \max \{ V_{p}^{\sigma'_p, \sigma_{-p}}(I) \mid \sigma'_p \in \Sigma_p \}$ holds for each $I \in \mathcal I_p^{\textnormal{aug}}(S)$, $p=1,2$. \end{definition} By $G(S,r)$ we denote the ``\defword{unsafe resolving subgame}'' (\cite{Neil_thesis}) obtained by taking $G(S)$ and turning it into a proper game by adding a chance node $\textnormal{root}_S$. This root connects to each (topmost, \cite{MCCR}) $h \in S$ via some action $a_h$ whose probability is proportional to $\eta^\mu(h)$. For fully mixed ranges, there is a straightforward connection between $\textrm{CROS}(S,r)$ and $G(S,r)$. Lemma~\ref{lem:SOS_props}~\eqref{case:existence_optS} uses this connection to prove the existence of $\textrm{CROS}(S,r)$ strategies for general $r$. \begin{restatable}[Properties of SOS]{lemma}{sosProps}\label{lem:SOS_props} For every $r$ and $S$, $\textrm{CROS}(S,r)$ satisfies the following: \begin{enumerate}[(i)] \item The restriction $\sigma |_{G(S)}$ of any $\sigma \in \textrm{CROS}(S,r)$ is a NE in $G(S,r)$.\label{case:restrict_optS} \item For fully mixed $r$, any NE in $G(S,r)$ extends into a $\textrm{CROS}(S,r)$ strategy.\label{case:mixed_optS} \item $\textrm{CROS}(S,r)$ is non-empty.\label{case:existence_optS} \end{enumerate} \end{restatable} This justifies the following definition of optimal value functions: \begin{definition}[Optimal value functions]\label{def:opt_VF} Let $\mu$ be a strategy defined in some trunk $T \subset \mathcal H$. A function $V^{\mu,*}_p : \mathcal S \times {\mathcal I}^\textnormal{aug}_p \to \mathbb{R}$ is said to be a \defword{optimal value function} for $p$ and $\mu$ if it satisfies \begin{align*} \left( \forall S \in \mathcal S \textnormal{ at the bottom of } T \right) \left( \exists \sigma \in \textrm{CROS}(S, \textnormal{rng}^{\mu}(S)) \right) \left( \forall I \in {\mathcal I}^\textnormal{aug}_p \right) : V^{\mu,*}_p (S,I) = V^\sigma_p(I) . \end{align*} An optimal value function $v^{\mu,*}_p : \mathcal S \times \mathcal H \to \mathbb{R}$ for histories is defined analogously, replacing $V^{\mu,*}_p (S,I) = V^\sigma_p(I)$ by $v^{\mu,*}_p (S,h) = v^\sigma_p(h)$. The \defword{optimal counterfactual value functions} $V^{\mu,*}_{c,p}$ and $v^{\mu,*}_{c,p}$ are defined analogously, adding a $c$ subscript into the condition above. \end{definition} \subsection{Properties of the optimal values} Our definition coincides with other standard definitions of value: Indeed, if $G$ is in fact also an (acyclic) MDP (i.e. it has perfect information and no player 2 nodes), then public states coincide with states, their optimal value is uniquely defined, and hence both $V^{\sigma,*}_p$ and $v^{\sigma,*}_p$ coincide with the standard MDP state-value $v^*$ \citep{sutton2018reinforcement} (independently of $\sigma$). If $G$ is a two-player zero-sum perfect-information game, then $V^{\sigma,*}_p$ and $v^{\sigma,*}_p$ again coincide and are equal to the minimax value of the state. This is true even when $G$ admits simultaneous moves \cite{bosansky2016algorithms}. These coincidences are the main reason for considering the normalized values. On the other hand, the non-normalized values are more straightforward to compute. By Proposition~\ref{prop:VF_CFR-D}, \texttt{IS\_Values} can be applied in depth-limited solving, which proves that it is indeed a useful notion of a value function: \begin{restatable}[$V^{\sigma,*}_{c,p}$ can be used for depth-limited solving]{proposition}{CFRDwithVF} \label{prop:VF_CFR-D} For every trunk strategy $\mu$, any optimal counterfactual value function $V^{\sigma,*}_{c,p}$ satisfies Equation \eqref{eq:CFR-D_assumptions}. \end{restatable} \begin{proof} By Definition~\ref{def:opt_VF}, we have $V^{\sigma,*}_{c,p}(S,I) = V_{p,c}^\sigma(I)$ for some $\sigma \in \textrm{CROS}$. By definition of $\textrm{CROS}$, $\sigma$ has satisfies $\textnormal{rng}^{\sigma}(S)=r$, $\sigma|_{G(S)} \in \textrm{NE}(G(S,r))$ and $V_p^\sigma(I) = \max_{\sigma'_p} V_p^{\sigma'_p, \sigma_{-p}}(I)$ for each $I \in \mathcal I_p^{\textnormal{aug}}(S)$. Since $V_{p,c}^{(\cdot)}(I) = \eta_p^{(\cdot)}(I) V_p^{(\cdot)}(I)$, we get $V_{p,c}^\sigma(I) = \max_{\sigma'_p} V_{p,c}^{\sigma'_p, \sigma_{-p}}(I)$ as well. \end{proof} To make the computation of values feasible, we use two practical tweaks: Firstly, for a fixed range, we do not use the subgame-optimal strategies, but instead solve the subgame by CFR (w.r.t. the counterfactual values \emph{in the whole game}). A solution $\sigma$ found by CFR doesn't necessarily have the properties of $\textrm{CROS}(S,r)$, but, in the limit, it is still good enough for depth-limited resolving (i.e. the corresponding mapping $I \mapsto V_{p,c}^\sigma(I)$ is optimal in the sense of Eq. \eqref{eq:CFR-D_assumptions}). Second, we approximate the $I \mapsto V^\sigma_{p,c}(I)$ mapping by a neural network. Because of numerical instability, very similar ranges might correspond to very different (but still optimal) values. The neural network will converge to a convex combination of these values. The following result shows that both of this tweak still produce data useful for depth-limited solving. \begin{restatable}[Approximating $V_{c,p}^{\mu,*}$ by a neural net]{proposition}{CFRDwithNN} \label{prop:convexity} Let $r$ be a range at $S \in \mathcal S$ and $p\in\{1,2\}$. If $V$ and $V'$ are two mappings satisfying Eq. \eqref{eq:CFR-D_assumptions}, then so does their convex combination $W = \lambda V + (1-\lambda) V'$ for any $\lambda \in (0,1)$.\end{restatable} \noindent This proves the correctness of the function-approximation step of DeepStack \citep{DeepStack}. Using infoset values over history values is often beneficial, not only because it reduces the dimension of value-vector, but also because it removes some of the ambiguity: \begin{restatable}[Infoset aggregation reduces ambiguity]{proposition}{wellDefined}\label{prop:V_function_well_def} If $\sigma, \mu \in \textrm{CROS}(S,r)$ satisfy $\sigma_{-p} = \mu_{-p}$, then we have $V_p^\sigma(I) = V_p^\mu(I)$ and $V_{p,c}^\sigma(I) = V_{p,c}^\mu(I) = V_{p,c}^{\textnormal{CBR}_p(\sigma_{-p}), \sigma_{-p}}(I)$ for each $I\in \mathcal I_p^{\textnormal{aug}}(S)$. \end{restatable} \noindent In other words, the optimal infoset values are uniquely determined by the opponent's strategy. \subsection{The rationale behind our definition} \begin{figure}[b] \centering \newcommand{\tikz \draw[-triangle 90] (0,0) -- +(.1,0);}{\tikz \draw[-triangle 90] (0,0) -- +(.1,0);} \begin{forest} for tree={ grow=east, l+= 3em } [root,chance, [$g_2$,pl1, l+=-1em, edge={draw=none}, [$h_2$,pl2, edge={draw=none}, yshift=-0.00\nodesize [end,terminal, text=white, fill=black, scale=0.75, yshift=-0.35\nodesize, edge={draw=none}] ] ] [$g_1$,pl1, l+=-1em, edge={draw=none}, [$h_1$,pl2, edge={draw=none}, yshift=-0.00\nodesize [end,terminal, text=white, fill=black, scale=0.75, yshift=-0.35\nodesize, edge={draw=none}] ] ] ] \node [pl1_cl_infoset, fit=(\corners{!1})(\corners{!2})] {}; \node [above, xshift=-0.75\nodesize, yshift=0.25\nodesize] at (!2) {$I$}; \node [pl2_cl_infoset, fit=(\corners{!11})(\corners{!21})] {}; \begin{pgfonlayer}{bg} \foreach \x/\A/\B/\C/\D/\upperYshift/\lowerYshift/\direction in {1/+1/0/-1/0/-0.5/-2/right, 2/0/+1/0/-1/.7/-.9/left}{ \draw [bend \direction] (!) to node {\tikz \draw[-triangle 90] (0,0) -- +(.1,0);} (!\x); \draw [bend left] (!\x1.center) to node {\tikz \draw[-triangle 90] (0,0) -- +(.1,0);} (!\x11); \draw [bend right] (!\x1.center) to node {\tikz \draw[-triangle 90] (0,0) -- +(.1,0);} (!\x11); \draw [bend left] (!\x.center) to node {\tikz \draw[-triangle 90] (0,0) -- +(.1,0);} (!\x1); \draw [bend right] (!\x.center) to node {\tikz \draw[-triangle 90] (0,0) -- +(.1,0);} (!\x1); \node[above,yshift=\upperYshift em] at ($(!\x)!.6!(!\x1)$) {\A}; \node[above,yshift=\lowerYshift em] at ($(!\x)!.6!(!\x1)$) {\B};/ \node[above,yshift=\upperYshift em] at ($(!\x1)!.6!(!\x11)$) {\C}; \node[above,yshift=\lowerYshift em] at ($(!\x1)!.6!(!\x11)$) {\D}; } \end{pgfonlayer} \end{forest} \caption{A zero-sum game where different equilibria produce different expected utilities. The utility of player 1 is the sum of the obtained rewards.} \label{fig:value_not_unique} \end{figure} We now compare our definition of optimal value functions with values in other models, note the ways in which it is more complicated, and illustrate on examples why these complications are necessary. Consider the minimax value of a history $h$ in a perfect-information zero-sum game. This value is uniquely defined, depends only on $h$ (and the subgame below it), and corresponds to any-and-all NE strategies in the subgame rooted at $h$. In contrast, we have made no claims about the uniqueness of $v^{\sigma,*}_{p}(S,h)$, this value depends on the strategy above $h$, and in fact above the whole $S$, and requires not just any NE, but its particular refinement. We now explain why these these complications are necessary. Firstly, it is possible to define a single-number value for the whole $S$ and range as the value of the corresponding game $G(S,r)$. This is similar to the approach taken by \cite{wiggers2016structure} in partially-observable stochastic games, where beliefs serve a similar purpose as ranges in EFGs. We choose our definition partly because knowing the value of each individual history/information set seems inherently interesting, but more importantly because unlike public-state values, these values are sufficiently informative to enable depth-limited solving (Proposition~\ref{prop:VF_CFR-D}). Second, why does the definition of our values use a \emph{refinement} of Nash equilibrium, and not just any NE? We want our definition of value to capture the notion of ``what would have happened, if the game actually reached a specific history/information set?''. However, each $h$ in the root of $G(S,r)$ is weighted proportionally to $r(h)$, implying that $G(S,r)$ effectively ignores the parts of $G(S)$ that have zero probability under $r$. To avoid distorting the values of such $h$, we only consider the $\textrm{CROS}(S,r)$ strategies, under which even unreachable histories in $S$ have optimal values. For a specific example of this behavior, see the game from Figure~\ref{fig:value_not_unique_2} (c): The bolded-out strategy $(L, B)$ is a NE, but if player 1 took this to mean that he is free to play $R$ because the ``value of $L$ = value of $R$ = 1'', they would be in for an unpleasant surprise -- upon reaching $X$, a rational player 2 would not play the ``bad'' action $B$. Intuitively, the correct strategy is $(L,G)$, which yields ``value of $L$ = 1, value of $R$ = 0''. This aligns with our definition of value, since the range at $S=\{L,R\}$ corresponding to $L$ is $(1,0)$, and we have $(L,G) \in \textrm{CROS}(\{L,R\},(1,0))$, but $(L,B) \notin \textrm{CROS}(\{L,R\},(1,0))$. Moreover, a value of a history depends on the \emph{whole} range: \begin{restatable}[Values depend on whole ranges]{theorem}{wholeRangeDep}\label{thm:wholeRangeDep} Let $G$ be an EFG, $S\in \mathcal S$ a common-knowledge public state\footnote{The common-knowledge public states, defined by \cite{MCCR} as the equivalence classes of $\sim$, are public states that cannot be further split into smaller ones.}, $h_0 \in S$, and $r$ a joint range at $S$. Assume that $S$ isn't thick and $r$ is fully mixed\footnote{That is, $r(h)>0$ holds for each $h\in S$.}. Then for each $g\in S$, there is $r'$ that only differs from $r$ at $g$, and an EFG $\widetilde G$ which only differs from $G$ below $S$, s.t. $\{ v_1^\sigma(h_0) \mid \sigma \in \widetilde{\textrm{CROS}}(S,r) \} \neq \{ v_1^\sigma(h_0) \mid \sigma \in \widetilde{\textrm{CROS}}(S,r') \}$. \end{restatable} \noindent The intuition behind $\widetilde G$ is that until we have understood $G$, we cannot be certain it doesn't behave like $\widetilde G$. One could prove a more general version of the statement for thick $S$ and (nearly) arbitrary $r$ and $r'$. However, we believe Theorem~\ref{thm:wholeRangeDep} illustrates the need for full range sufficiently. Even for a fixed range, the value of a history might be different under different equilibrium strategies: \begin{restatable}{example}{histValAmbig}\label{ex:non_unique} $\textrm{CROS}(S,r)$ strategies that have the same range can still have different history values. \end{restatable} \noindent This is readily witnessed by the game from Figure~\ref{fig:value_not_unique}, where any player can make a trade-off between the expected utilities at $g_1$ and $g_2$ (while still playing optimally). By Proposition~\ref{prop:V_function_well_def}, the ambiguity of values can be reduced by aggregating values over information sets. The game from Figure~\ref{fig:value_not_unique_2} (a) shows that even this aggregation doesn't fully resolve the ambiguity, since the opponent can still make tradeoffs between states that he can't tell apart, but we can (in the depicted game, player 1 has perfect information and hence $\{A\}$ and $\{B\}$ are his information sets, but different NE strategies give different values for $A$ and $B$): \begin{example}\label{ex:non_unique_I} Distinct $\textrm{CROS}(S,r)$ strategies can, for some $I\in \mathcal I_p^{\textnormal{aug}}(S)$, have different values of $I$. \end{example} One could also wonder whether it perhaps doesn't suffice to only consider ranges that correspond to Nash equilibria, and whether these might not all lead to the same value function. When running CFR-D, the trunk strategy will often be highly sub-optimal --- in this sense, we truly do need values even for non-optimal ranges. The game depicted in Figure~\ref{fig:value_not_unique_2} (b) shows that the latter property doesn't hold either: \begin{restatable}{example}{optValuesNotUnique} Suppose that trunk strategies $\sigma$ and $\sigma'$ can both be extended into NE in the full game and $V^{\sigma,*}_p$ is an optimal value function for $\sigma$. Then $V^{\sigma,*}_p$ might not be optimal for $\sigma'$. \end{restatable} \begin{figure}[b] \begin{forest} [, chance, l sep-=0.5\nodesize, [A,pl2,name=a, [0] [1] ] [B,pl2,name=b, [1] [0] ] ] \begin{pgfonlayer}{bg} \draw [line_infoset, opponent, bend right] (!1) to (!2); \end{pgfonlayer} \node [infoset, augmented, fit=(\corners{a})] {}; \node [infoset, augmented, fit=(\corners{b})] {}; \end{forest} \hfill \begin{forest} [, pl2, l sep-=0.5\nodesize, [,chance, edge label={node[midway,sloped,above]{PfA}} [,pl1, edge label={node[near start,left]{A}}, [0] ] [,pl1, edge label={node[near start,right]{B}}, [1] ] ] [,chance, edge label={node[midway,sloped,above]{PfB}} [,pl1, edge label={node[near start,left]{A}}, [1] ] [,pl1, edge label={node[near start,right]{B}}, [0] ] ] ] \begin{pgfonlayer}{bg} \draw [line_infoset, bend right] (!11.south) to (!21.south); \node[above,yshift=-0.3em] at ($(!121)!.5!(!211)$) {$I_A$}; \draw [line_infoset, bend left] (!12.north) to (!22.north); \node[above,yshift=0.8\nodesize] at ($(!12)!.5!(!21)$) {$I_B$}; \end{pgfonlayer} \end{forest} \hfill \begin{forest} [, pl1, for descendants={l sep-=0.25\nodesize}, [L,pl2,name=a, edge label={node[midway,left]{\textbf{L}}}, [1] ] [R,pl2,name=b, edge label={node[midway,right]{R}} [X, pl2, [0, edge label={node[midway,left]{G}}] [1, edge label={node[midway,right]{\textbf{B}}}] ] ] ] \begin{pgfonlayer}{bg} \draw [line_infoset, opponent, bend right] (!1) to (!2); \end{pgfonlayer} \end{forest} \caption{(a) Different NE produce different infoset values. (b) Different NE ranges lead to different values. (c) Subgame-optimal strategy produces accurate values, an ordinary ``subgame NE'' doesn't.} \label{fig:value_not_unique_2} \end{figure} \subsection{Multi-valued states} \emph{Multi-valued states} is an approach to value estimation in imperfect-information games developed by \cite{brown2018depth}. The authors propose to fix some equilibrium strategy $\sigma_1$ and remember, for each $h$ whose ``value'' we might need, the vector of values $v_1^{\sigma_1, \nu_2}(h)$ for undominated pure strategies $\nu_2$ of player 2 below $h$. The part of the game below $h$ is replaced by a single decision where player 2 picks $\nu_2$, and receives the corresponding utility. Section 7 of \cite{brown2018depth} contains a nice comparison of multi-valued states and the approach of \cite{DeepStack}. For our purposes, the key differences are that multi-valued states are easier to learn, but require the prior knowledge of an approximate equilibrium strategy $\sigma_1$ in the full game $G$. This assumption is very unrealistic, since the whole point of solving $G$ is to find such $\sigma_1$. However, the approach works well -- at least for poker -- even when $\sigma_1$ is sub-optimal \cite{brown2018depth}. Ultimately, both approaches deserve further investigation, since their effectiveness might vary depending on the specific domain and setting.
{'timestamp': '2019-06-18T02:02:49', 'yymm': '1906', 'arxiv_id': '1906.06412', 'language': 'en', 'url': 'https://arxiv.org/abs/1906.06412'}
arxiv
\section*{Declaration of Competing Interest} The authors state that there is no conflict of interest \section*{Acknowledgemnts} We would like to show our gratitude to Dr. Yoshinobu Igarashi (Laboratory of Toxicogenomics Informatics, NIBIOHN) for his valuable suggestions and comments. However, the statements made here are solely the responsibility of the authors. No external funding was utilized in this study. \section{Introduction} Adverse drug reaction (ADR) or event is defined as any unintended or undesired effect of a drug \cite{Coleman2016,Katzung2012}. ADRs are responsible for a high number of visits to emergency departments and in-hospital admissions. The Japan Adverse Drug Events (JADE) study reported around 17 adverse drug events per 1000 patient days. 1.6\% were fatal, 4.9\% were life-threatening, and 33\% were serious \cite{Morimoto2010}; these observations underscore the importance of toxicity assessment of any medication, especially in the early stages of drug discovery. \textit{In--silico} approaches to ADR prediction have been promising in terms of accuracy and underlying mechanisms understanding. Researchers have variously utilized multiple data types ranging from chemical structures to literature mining to predict ADRs \cite{Ho2016}. Machine learning methods can play a significant role in the interpretation of various data types to predict ADRs. Deep learning \cite{Wang2020}, a subset of machine learning in Artificial intelligence (AI), has emerged as a promising and highly effective approach that can combine and interrogate diverse biological data types to generate new hypotheses. Deep learning methods are used extensively in the field of drug discovery and drug repurposing; however, their applications in ADR prediction are rather limited \cite{Dana2018,Vamathevan2019, Zhang2017}. Open TG–GATEs \cite{Igarashi2014} is a large--scale toxicogenomics database that collects gene expression profiles of \textit{in vivo} as well as \textit{in vitro} samples that have been treated with various drugs. These expression profiles are an outcome of the Japanese Toxicogenomics Project \cite{Uehara2009}, which aimed to build an extensive database of drug toxicities for drug discovery. It also collects physiological, biochemical, and pathological measurements of the treated animals. Similar databases that aim to profile compund toxicities have also been developed \cite{AlexanderDann2018, Chen2012}. In contrast with other databases, such as (LINCS) \cite{Subramanian2017}, which have been used to predict multiple ADRs in a single study\cite{Wang2016}, {Open TG--GATEs} has been used to investigate individual/specific toxicities \cite{RuedaZrate2017}. To the best of our knowledge, no multiple ADR predictions have been attempted using Open TG--GATEs. The design of Open TG-Gates has several advantages over the {LINCS} database, chiefly the inclusion of \textit{in vivo} samples with different doses and durations of administration. Therefore, we designed our analysis to encompass multiple samples with different dosages and duration for each compound, necessitating additional noise-removal steps in the data set. In this study, we describe our deep learning-based, systematic ADR prediction models that combine ADR occurrence data, including frequency details, from the FAERS (FDA Adverse Event Reporting System) database, with the gene expression profiles from Open TG-GATEs. We aim to improve the models' performance by applying recently developed feature selection and hyper-parameter optimization algorithms. The methodologies and models described in our study offer useful tools for assessing the likelihood of ADRs and for incorporation into new drug development pipelines. \section{Materials and Methods} \subsection{Overview} An overview of this study's methodology is shown in Figure:~\ref{fig:flowchart}. First, we retrieved the relevant data from the above-described two databases (open TG--GATEs and FAERS). We pre-processed the gene expression data to filter out noisy profiles by using a simple classification model, and retained only the significant ADR-drug associations (p<0.05; Fisher's exact test). Next, gene expression profile datasets were created by assigning positive and negative compounds for each ADR. We split the datasets into training and validation sets five times. We used the training set data to perform feature selection and build deep neural network models with hyper-parameter tuning using the Optuna package (see below). Finally, we evaluated the performances of the individual models on the validation set. We discuss these steps in detail below: \begin{figure} \centering \includegraphics[width=0.5\hsize]{side_effects_flow_chart.pdf} \caption{Overall analysis flowchart} \label{fig:flowchart} \end{figure} \subsection{Data retrieval and processing:} \subsubsection{Open TG--GATEs database:} We extracted the \textit{in--vivo} gene expression profiles of rat liver samples from the Open TG--GATEs database \cite{Igarashi2014, Uehara2009}. We selected the rat \textit{in-vivo} data for our analysis chiefly because the \textit{in-vivo} dataset included more compounds and a greater number of time points as compared with the \textit{in-vitro} data (rat and human). However, our methodology can be easily extended to the other datasets. This dataset was comprised of single-dose experiments and repeated-dose experiments. Single-dose experiments included injection-to-sacrifice periods of 3, 6, 9, or 24 hours, whereas, in the repeated dose experiments, rats were injected once daily for 4, 8, 15, or 29 days. In the repeated-dose experiments, all rats were sacrificed 24 hours after the last dose \cite{Igarashi2014}. In Open TG--GATEs, gene expression profiles were measured using Microarray technology (Affymetrix GeneChip). The Affymetrix CEL files were downloaded from \url{http://toxico.nibiohn.go.jp}, and were preprocessed using the affy package \cite{Gautier2004} from R Bioconductor (\url{https://bioconductor.org/}); Affymetrix Microarray Suite algorithm version 5 (mas5) was applied with the default parameters provided in affy, wherein normalization = TRUE. The resulting normalized dataset -- hereafter referred to as ``the raw dataset'' -- was used for all the subsequent analyses. Next, the fold change values were calculated for each probe set by dividing the raw dataset by the mean intensities of corresponding control samples; these values were then log2 transformed, hereafter referred to as the ``log2FC dataset''. Since the experiment design contained multiple dosages and durations of exposure, the drugs had varied effects on the gene expression profiles. To reduce the noise, we clustered all the samples to classify them as either treated or control using general linear modeling with Lasso penalty machine learning model (GLMNET package from R \cite{Friedman2010}.). We used the whole raw dataset as the training set with a two-class classification (treated and control). We fed through all the microarray data of the same duration to a single model, creating one model for each exposure set duration. Next, we estimated the probability of being classified as a treated sample for all the training sets. Only those samples with a probability of higher than 92\% were included in our analysis. The remaining samples were considered to fall within the gray zone between treated and control, and they were discarded. We chose a cut-off of 92\% because, at this threshold, no control samples were misclassified as treated. \subsubsection{Standardized FAERS data:} FAERS (FDA Adverse Event Reporting System) is ``a database that collects adverse event reports, medication error reports, and product quality complaints resulting in adverse events that were submitted to FDA'' (\url{https://open.fda.gov/data/faers/}). Since the terms used in the FAERS database are left to the reporter to decide, inaccurate descriptions can often be incorporated, such as using general, vague terms to describe adverse events or treatments \cite{Wong2015}. To surmount this issue, we used the portion of the FAERS dataset standardized by Banda et al. \cite{Banda2016}. They had curated and standardized the entries of the FAERS database for 11 years (2004 to 2015) following Medical Dictionary for Regulatory Activities ({MedDRA}) terms \cite{Wood1994}. We extracted all the compound-ADR combinations (70,553,900) from the total number of reports (4.8 million). Among the difficulties of using the FAERS database in ADRs` prediction models is the presence of reports with multiple drugs used (Multipharma), which is expected in patients with chronic diseases. Such cases introduce unreliable associations added to the data noise. To solve this issue, we used only the association in which the drug is assigned as the primary suspect (PS) (15,377,900). We calculated the number of reports for each compound-adverse drug event combination and calculated the total number of reports of the compound in question and also the total number of reports of the adverse event. Using this data, we performed the Fisher test \cite{Ghosh1988} using ``fisher.test'' function from R with the parameter (alternative = ``greater''). This option returns a significant P-value only in the event of a positive association, in contrast to ``two.sides'' test, which assesses both positive and negative associations Table~\ref{tab:fisherexplain}. \begin{table}[H] \caption{Fisher exact test: a: the number of reports of that the compound cause the ADE, b: the number of reports of the compound that does not report the cause of ADE, c: the number of all positive reports of the ADE for all compounds other than the specific compound, e: the number of all negative reports of all compound other than the specific compound. } \label{tab:fisherexplain} \centering \begin{tabular}{|l|c|c|c|} \toprule & Positive & Negative & Row total \\ \midrule compound & a & b & a+b \\ \midrule all other compounds & c & d & c+d \\ \midrule Column total & a+c & b+d & all reports \\ \bottomrule \end{tabular} \end{table} \subsection{Model building and training} The training set included only treated samples (excluding all controls). For each model, we designated the compounds with the most significant associations as positive compounds, (p--value threshold $<$ 0.05) and the least significantly associated compounds as negative compounds. We evenly balanced the number of positive and negative compounds for each model. When assembling the training and validation sets, we imposed two criteria: 1) the data-sets were balanced, i.e., the number of positive and negative samples were equal in both the sets and; 2) no compounds were commonly shared between training and validation. Instead of following a standardized cross-validation method, we created five models for each side effect by exploring all combinations of compounds in training and validation sets. However, we kept only those that comply with the previous conditions. To prevent information leakage between the validation set and the training set, feature selection was performed using the training set data only, validation set data was not involved at all. Moreover, the hyper-parameter optimization was also done using the information from the training set only, and validation set accuracy was only used to identify the best model. For feature selection, we used Boruta \cite{Kursa2010} implementation in Python \url{https://github.com/scikit-learn-contrib/boruta_py} , that is based on the random forest classifier from scikit-learn \cite{Pedregosa2011} python package with default parameters. Boruta algorithm utilizes the random forest classifier variable importance feature. To remove the effect of randomness and improve the accuracy of important feature detection, Boruta creates extra shadow variables by shuffling the values of the original features, then the feature importance is measured. Features with significantly higher importance than the shadow variables are considered important, while those with less importance are considered less important. This procedure was repeated 100 times to detect the important features more accurately.\cite{Kursa2010} Then we used {TensorFlow 2}\cite{Abadi2016} to construct deep learning models. The input of the deep learning model is constructed of two dimensional matrix with samples in rows and genes on columns. Each model consists of three groups of layers, input, output, and hidden layers. We applied Optuna \cite{Akiba2019} for hyperparameters tuning. Optuna uses the trial and error method for optimization, by randomly assigning values to the model hyperparameters from a range of values or choices offered by the author for a pre-determined number of trials. Subsequently, the results of all the trials can be examined to determine the most optimal parameters. The parameters that were optimized included: ``depth'': corresponds to the number of densely connected layers (number of hidden layers aka DNN depth); the possible values are [1, 2, 5, 10, 30]. ``width'': corresponds to the number of nodes per layer, the possible values were [100, 250, 500, 700]. To reduce the likelihood of over fitting, we used two measures. The first measure ``drop'' is to drop some nodes before going to the next layer. It took one of these values [0.2, 0.3, 0.4, 0.5], (0.2 means 20\% of nodes are dropped). The second measure is the introduction of noise: the value of introduced gaussian noise [0.2, 0.3, 0.4, 0.5]. Other hyperparameters included: ``activation'': corresponds to the activation function of the final layer (output layer); possible values: ['sigmoid', 'linear'], ``learning rate'' for Adam optimizer \cite{Diederik2014} was selected among [0.001, 0.0005, 0.00001]. The models with highest validation set accuracy were chosen. \begin{table}[H] \caption{Optuna hyper--parameter choices} \label{tab:optunaexplain} \centering \begin{tabular}{l l} \toprule Parameter & choices \\ \midrule depth & 1, 2, 5, 10, 30 \\ width & 100, 250, 500, 700 \\ drop percentage & 0.2, 0.3, 0.4, 0.7 \\ gaussian noise & 0.2, 0.3, 0.4, 0.5 \\ activation & sigmoid, linear \\ learning rate & 0.001, 0.0005, 0.00001 \\ \bottomrule \end{tabular} \end{table} The maximum number of epochs was set at 800; however, we applied the ``early stopping'' strategy if the accuracy did not improve for 75 epochs. The best models were saved for each Optuna trial. The best parameters are shown in the Supplementary Table: S1. \begin{figure} \centering \includegraphics[width=\hsize]{dnn_structure.pdf} \caption{DNN structures} \label{fig:dnnstructure} \end{figure} \subsection{Evaluation and enrichment analysis} Model performances were evaluated by testing the performance of the validation set prediction. We estimated the accuracy of the validation set and the area under the ROC (Receiver operating characteristic) curve using the scikit-learn \cite{Pedregosa2011} package from Python. TargetMine data analysis platform was used for enrichment analysis and gene annotation\cite{Chen2019}. Databases used for enrichment analysis were KEGG, Reactome, and NCI. \textit{P--values} were calculated in TargetMine using one-tailed Fisher's exact test. Multiple test correction was set to Benjamini Hochberg, with \textit{p-value} significance threshold of 0.05. \section{Results} \subsection{Data processing} To reduce the data dispersion caused by multiple dose levels and injection durations (sacrifice period) in Open TG-GATEs, we filtered out low quality/unsuitable samples. To do that, we used Lasso to classify the samples to either treated or control classes. A total of 6619 of 10573 treated samples, chiefly belonging to the ``Low'' dose level category, were classified as controls and eventually excluded. Samples that were correctly classified as treated (3953 samples) remained for subsequent analysis. (Table~\ref{tab:includedsamplesinformation}). \begin{table}[H] \caption{The number of Open TG-GATEs samples included in the analysis after clustering using Lasso, dose level and sacrifice period details are shown.} \label{tab:includedsamplesinformation} \centering \begin{tabular}{llrr} \toprule & & Original & Included \\ \midrule Dose Level & Low & 3540 & 421 \\ & Middle & 3537 & 1212 \\ & High & 3496 & 2320 \\ \midrule Sacrifice Period & 24 hr & 1408 & 762 \\ & 9 hr & 1371 & 556 \\ & 6 hr & 1371 & 533 \\ & 3 hr & 1368 & 518 \\ & 4 day & 1275 & 254 \\ & 8 day & 1275 & 472 \\ & 15 day & 1266 & 500 \\ & 29 day & 1239 & 358 \\ \bottomrule \end{tabular} \end{table} \subsection{Model building and training} We created a total of 14 models (Table:~\ref{tab:createdmodels}). The number of compounds used to create each model ranged from 10 to 18. We equalized the number of positive compounds and negative compounds to generate balanced models. \begin{table}[H] \caption{The number of compounds, and samples used to create ADRs prediction models. (AGEP: Acute generalized exanthematous pustulosis, ECG: Electrocardiogram). (+): Positive , (-): Negative} \label{tab:createdmodels} \centering \begin{tabular}{lcccc} \toprule ADR & \multicolumn{2}{c}{Drugs} & \multicolumn{2}{c}{Samples} \\ & + & - & + & - \\ \midrule AGEP & 5 & 5 & 203 & 87 \\ Bone marrow failure & 5 & 5 & 125 & 178 \\ Catatonia & 5 & 5 & 169 & 130 \\ Duodenal ulcer & 6 & 6 & 122 & 178 \\ ECG qt prolonged & 5 & 5 & 105 & 152 \\ Febrile neutropenia & 5 & 5 & 62 & 141 \\ Gastric haemorrhage & 5 & 5 & 124 & 161 \\ Hepatitis fulminant & 5 & 5 & 193 & 126 \\ Liver transplant & 9 & 9 & 297 & 244 \\ Lymphocytosis & 5 & 5 & 196 & 128 \\ Neutropenic sepsis & 6 & 6 & 89 & 165 \\ Optic atrophy & 6 & 6 & 122 & 139 \\ Torsade de pointes & 7 & 7 & 144 & 219 \\ Toxic epidermal necrolysis & 5 & 5 & 136 & 99 \\ \bottomrule \end{tabular} \end{table} \subsection{Model evaluation} The Average accuracy for all models was 85.71\% [minimum$=$67.9\%, and maximum=100\%, standard error=0.1]. The validation accuracies of the models are shown in Figure~\ref{fig:validationaccuracy}. The area under the Receiver Operating Characteristic (ROC) curve is shown in Figure:~\ref{fig:auc}. \begin{figure} \centering \includegraphics[width=\hsize]{accuracies.pdf} \caption{Validation accuracy of the created models} \label{fig:validationaccuracy} \end{figure} \begin{figure} \centering \includegraphics[width=\hsize]{auc.pdf} \caption{Area under ROC curves for the created models.} \label{fig:auc} \end{figure} \subsection{Case study: Duodenal Ulcer} To highlight the effectiveness of our approach, we describe below our observations on the development of the duodenal ulcer ADR prediction model. Duodenal ulcer is a type of peptic ulcer disease characterized by the emergence of open sores on the duodenum's inner lining of the duodenum \cite{Kuna2019}. It is mainly caused by the failure of gastrointestinal system inner coating protection, and the most common causing agents are \textit{Helicobacter Pylori} infection and NSAIDs (Non-steroidal anti-inflammatory drugs). It can lead to serious bleeding or perforation. \subsubsection{Duodenal ulcer model description} Using the FAERS database, the six most significantly associated drugs with duodenal ulcer were identified using Fisher test (positive drugs: Aspirin, Diclofenac, Ibuprofen, Indomethacin, Meloxicam, Naproxen) and the least associated drugs were also identified (negative drugs: Acetaminophen, Amiodarone, Bortezomib, Carbamazepine, Ciprofloxacin, Cyclophosphamide). Subsequently, the open TG--Gates samples of these drugs were used to build the prediction models. Details of the compounds used, the number of the gene expression samples associated with these compounds, and the results of the Fisher test (see Methods) are shown in Table~\ref{tab:dudataset}. The ROC curves and the area under them for the five models of duodenal ulcer (each trained on a different training set) are shown in Figure~\ref{fig:duroc}. The performance of these models showed that the area under the curve ranges from 0.94 to 0.99. The number of the features (genes) commonly selected among the five duodenal ulcer models were 108. \begin{table} \caption{Details of the data set for the duodenal ulcer model (compounds, the number of the samples, the p-value of the Fisher test and the class in the training or test sets). Positive class compounds are those that can cause doudenal ulcer, while Negative class compounds are controls. Entries were ordered alphabetically} \label{tab:dudataset} \centering \begin{tabular}{lrrl} \toprule {} & Fisher (\textit{p}) & No & Class \\ \midrule Acetaminophen & \SI{4.88e-01} & 50 & negative \\ Amiodarone & \SI{9.35e-01} & 31 & negative \\ Aspirin & \SI{4.67e-233} & 45 & positive \\ Bortezomib & \SI{3.57e-01} & 24 & negative \\ Carbamazepine & \SI{9.99e-01} & 45 & negative \\ Ciprofloxacin & \SI{9.67e-01} & 7 & negative \\ Cyclophosphamide & \SI{8.29e-01} & 21 & negative \\ Diclofenac & \SI{1.3e-66} & 9 & positive \\ Ibuprofen & \SI{1.22e-112} & 24 & positive \\ Indomethacin & \SI{5.40e-15} & 12 & positive \\ Meloxicam & \SI{2.15e-35} & 10 & positive \\ Naproxen & \SI{2.02e-78} & 22 & positive \\ \bottomrule \end{tabular} \end{table} \begin{figure} \centering \includegraphics[width=\hsize]{roc_with_model_numbers.pdf} \caption{Area under ROC curves for duodenal ulcer models. Each color corresponds to a different model.} \label{fig:duroc} \end{figure} \subsubsection{Enrichment Analysis} Pathway enrichment analysis (see Methods) using the duodenal ulcer-selected features (Table: S2) clearly highlighted the involvement of bleeding cascade and complement function (Table:~\ref{tab:enrichmentanalysis}). The manifestation of a duodenal ulcer activates the complement cascade, which is probably due to the inflammation caused by the acid effect on the intestinal mucosa. Bleeding is also linked with the duodenal ulcer disease. The enrichment of the Fatty acid degradation pathway is consistent with the fact that the majority of the compounds that cause duodenal ulcers are NSAIDs that inhibit Arachidonic acid metabolism, which is a part of the Fatty acid metabolism pathway. \begin{table}[H] \caption{The enrichment analysis results of duodenal ulcer model, showing the involvement of both complement and coagulation functions} \label{tab:enrichmentanalysis} \centering \begin{tabular}{p{5cm}lp{0.01cm}} \toprule Pathway & \textit{P}value & \\ \midrule Complement and coagulation cascades [rno04610] & \SI{1.86e-11} & \\ Regulation of Complement cascade [R-RNO-977606] & \SI{1.56e-5} &\\ Complement cascade [R-RNO-166658] & \SI{9.16e-5} &\\ Pertussis (rno05133) & \SI{3.84e-3} & \\ Fatty acid degradation (rno00071) & \SI{4.83e-3} &\\ \bottomrule \end{tabular} \end{table} \section{Discussion} We have described a novel approach that combined toxicogenomics gene expression profiles extracted from Open TG-GATEs and ADRs reports extracted from FAERS to predict the likelihood of ADRs. This integration of two highly distinct data types allowed us to predict ADRs successfully. Moreover, it led to creating a novel dataset that associated drug-induced gene expression profiles with ADRs. To overcome the significant challenges in combining the two datasets, we first sought to extract the individual drug-induced gene expression signature from Open TG-GATEs. Next, we extracted the ADR occurrence frequencies for these drugs and estimated their statistical significance to eventually combine the two datasets. Moreover, due to multiple dose-levels and sacrifice periods and the presence of repeated and single injection events, the drug-induced gene expression profiles were fairly noisy. We generated a simple model to classify all the samples as either control or treated classes using Lasso to filter out this noise. We performed a rigorous statistical assessment to narrow down suitable samples for subsequent analyses (see Methods for details). Recently, deep learning has gathered an increasing usage in the field of drug discovery \cite{Zhang2017, Lee2019}. In this study we have used deep learning together with feature selection to reduce the data dimensionality and avoid overfitting due to limited samples. Previously, Wang et al. \cite{Wang2016} utilized multiple cell lines to develop predictive models for multiple ADRs. Another study \cite{Joseph2013} demonstrated that blood transcriptomics could be used to examine other organ toxicities. Our results have supported this notion by exhibiting robust prediction models with high accuracy using liver samples. Liver is a vital organ for drug metabolism and receives a significant amount of blood, and hence, it is widely used in drug toxicity studies. Moreover, even in the absence of pathological responses to the compound toxicity, cells still display differences in gene expression profiles. We did not apply the leave-p-out or k-fold cross-validation protocols to the gene expression samples because: 1) the training and validation sets should be assigned based on compounds segregation, i.e., the same compound should not span training and validation sets, and 2) the number of samples differed from compound to compound and thus, creating balanced sets was impossible. We instead adopted the approach of creating five models with different training and validation sets. We also performed feature selection for each of the set combinations. This study utilized \textit{in vivo} gene expression data in contrast with another study \cite{Wang2016} that utilized the data from the {LINCS} database \cite{Subramanian2017}, a collection of \textit{in vitro} gene expression profiles from human cell lines. Our approach is easily applicable to other publicly available collections of toxicogenomics data, such as those from Drug Matrix \cite{drugmatrix}. Another difference is that Wang \textit{et al.} \cite{Wang2016} combined chemical structure and Gene Ontology (GO) term associations in their models. They also selected only a single gene expression profile to represent the compound effects; in contrast, our method analyzed multiple samples with different doses and durations of each compound's exposure. Hence, our method is better equipped to account for the biological variations that are inherent in drug-induced physiological and phenotypic responses. Indeed, our models performed better than Wang \textit{et al.} 's gene expression data-only models \cite{Wang2016}. This difference in performances may probably be attributed to our utilization of multiple samples for each compound. Using the Optuna optimization package \cite{Akiba2019} made these prediction models' creation computationally expensive; hence, only a limited number of models were built. However, our approach can help generate models to serve specific applications using other data resources such as DrugMatrix, depending on the user's needs. In conclusion, we have developed 14 Deep learning models to predict adverse drug events utilizing the public available Open TG–Gates and FAERS databases. These models can be used to examine if a new drug candidate can cause these side effects. Moreover, following the same feature selection and model building and tuning steps, other models can be created for other ADRs.
{'timestamp': '2020-10-13T02:27:18', 'yymm': '2010', 'arxiv_id': '2010.05411', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05411'}
arxiv
\section*{Appendices} \subsection{Evaluaton Method} \input{method} \subsection{Datasets} \input{test_sets} \subsection{Experimental Setup} \input{setup} \subsection{Human Evaluation} \input{evaluation} \subsection{Results and Discussion} \input{results} \subsection{Candidate Extraction} Our approach assumes that the desired key points can be found among the given comments. We start by collecting concise, high quality candidates. We consider only single sentences, and filter out sentences whose length exceed a certain number of tokens. In order to ensure the high quality and argumentative nature of the selected comments, we use the publicly available \emph{IBM-ArgQ-Rank-30kArgs} dataset of \citet{gretz2019largescale}, which consists of around 30k arguments annotated for point-wise quality to train an argument quality ranking model. We then use this model to compute the argument quality score of each comment, and include only high quality candidates. In addition, we filter out sentences starting with pronouns in order to keep the key points self-contained. \subsection{Key Point Selection} \label{sec:selection} After the set of candidates is extracted, we use the matching model described in Section~\ref{sec:mapping} to obtain a match score between each comment and candidate, and between each pair of candidates. First, to achieve high coverage of the selected key points, we match comments to candidates by applying the BM+TH selection policy using the matching model and a threshold $t$, and sort the candidates in descending order according to their coverage, i.e., the number of matched comments. Second, in order to avoid redundancy among the selected key points, we traverse the candidates and remove from the list each candidate whose matching score with a higher-ranked candidate exceeded the threshold.\footnote{As the match scoring function is not symmetric, we compute the match score in both directions and take the average.} The removed candidates and their matched comments are then matched to the remaining candidates. Finally, the candidates are resorted to form a ranked list of top key points. The pseudo-code of the algorithm can be found in Appendix~B. \section{Introduction} \input{introduction} \section{Matching Comments to Key Points} \input{mapping} \section{Key Point Extraction} \input{extraction} \section{Experiments} \input{experiments} \section{Related Work} \input{related_work} \section{Conclusion} \input{conclusion} \bibliographystyle{acl_natbib}
{'timestamp': '2020-10-13T02:26:13', 'yymm': '2010', 'arxiv_id': '2010.05369', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05369'}
arxiv
\section{Introduction} Methods based on conditional independencies are a well-established framework for causal structure learning from observational data \citep{Spirtes00,Pearl09,Drton17,Heinze17,Petersbook,Malinsky18,Glymour19}. Orientation rules based on conditional independencies allow constructing a partially oriented graph \citep{Zhang08c} representing the equivalence class of all causal structures compatible with the set of conditional independencies present in the distribution of the observable variables (the so-called Markov equivalence class). However, the power of these methods is limited by a lack of independencies, e.g.\,in highly interdependent systems or in the presence of hidden variables. Beyond conditional independencies, the causal structure of a system also imposes further equality \citep{Tian2002b} and inequality \citep{Kang06} constraints, which can be used to test if a concrete causal model is compatible with some given observational data. To further discriminate within the Markov equivalence classes, other methods exploit specific properties associated with certain forms of the functional equations generating the variables, such as linear models with non-Gaussian noise \citep{Shimizu11}, or additive-noise models \citep{Hoyer2009, Zhang09, Chicharro19}, and hence can only provide additional causal knowledge when the system contains equations with the required form. We here propose a method to augment the power of structure learning algorithms based on conditional independencies by identifying endogenous sufficient statistics present in the generative mechanisms of a system. The causal structure of a system corresponds to the set of variables (parents) constituting the arguments of the functional equations characterizing the generative mechanisms of each variable. Because the shape of these equations is determined by the physical laws ruling the system, often the dependence of a variable on several parents is structured in subfunctions embedded within its functional equation. For example, it is common that several parents contribute additively, such that it is their sum rather than their individual value that is informative about the variable generated by the functional equation. Such a subfunction hence deterministically determines an endogenous variable which acts as a sufficient statistic \citep{Casella02}, containing all the information its arguments have about the generated variable. Therefore, finding sufficient statistics within the functional equations uncovers additional conditional independencies useful to further discriminate which causal structures are compatible with the data. Importantly, inferring the form of a sufficient statistic does not require modeling the full functional equation of a variable, as it is done in score-based approaches to structure learning \citep{Chickering2002,Chickering03}. A subfunction creating a functional sufficient statistic may be much simpler than the full functional equation, which may involve a higher number of variables than the subequation, or may even be non-identifiable, in the presence of hidden variables. Structure learning in the presence of deterministic relations has been studied before \citep{Geiger90,Spirtes00,Lemeire2012,Mabrouk2014}. However, this previous work considered deterministic relations between variables of the system, which hinder causal learning because they create independencies unfaithful to the causal structure. Conversely, the presence of endogenous functional sufficient statistics implies not deterministic relations between the variables of the system, but only with the hidden variables corresponding to the statistics. In this regard, whether a sufficient statistic is conceived as a meaningful hidden variable or simply as an auxiliary construct resulting from the form of the functional equation where it is embodied is not relevant. What matters is that the sufficient statistics create new conditional independencies between observable variables beneficiary to infer the causal structure. Accordingly, our proposal also differs substantially from other previous approaches to detect hidden variables \citep{Elidan2000,Silva06}. These approaches rely on detecting patterns of full connectivity between observable variables that could be explained by an unobserved common parent. A hidden common parent is conceived as an actual variable in the system, with its own functional equation, generally non-deterministic. Oppositely, sufficient statistics appear embedded within the functional equation of (most usually) a single observable variable, and hence do not operate as a hidden common parent. We here propose to identify sufficient statistics from the new conditional independencies they create. The information bottleneck (IB) method \citep{Tishby99} is especially suited to infer sufficient statistics, since it determines low dimensional representations of a set of variables preserving the information about another target variable, in the way a functional sufficient statistic has to contain all the information some parents have about the variable in whose functional equation the statistic is embedded. This use of the IB method substantially differs from its application to model low dimensional latent common causes of multiple observable variables \citep{Elidan2005}. To our knowledge, sufficient statistics have not been previously exploited to extend the applicability of standard causal orientation rules based on conditional independencies. This paper is organized as follows. Section \ref{ss1} reviews the basic causal orientation rules at the core of standard structure learning algorithms based on conditional independencies \citep{Spirtes00}. In Section \ref{ss2}, we provide a general presentation of functional sufficient sets of statistics and their application for structure learning from observational data in the presence of hidden variables; we introduce new orientation rules using sufficient statistics. In Section \ref{ss3} we describe how to use the IB method to find potential sufficient sets of statistics, and a general procedure to determine which identified statistics fulfill the necessary criteria to apply the causal orientation rules. We call this procedure the Information Bottleneck Sufficient Statistics Inference method, the IBSSI method. In Section \ref{ss4} we validate the applicability of the method to identify underlying sufficient statistics with high true positive rates and low false positive rates. We first study systems specifically designed to contain different types of sufficient sets of statistics. We then also apply the method to a concrete model of Boolean regulatory rules which has already previously been shown to accurately model a biological signal transduction network \citep{Li06}, and in whose structure we identify the presence of sufficient statistics. In Section \ref{ss5} we use sufficient statistics for structure learning in the presence of selection bias \citep{Spirtes96}, counteracting the selection bias by recovering conditional independencies between variables for which the bias introduced a dependence. In Section \ref{ss6} we further explore the combination of the IBSSI method with the identification of causal interventions, which can create new independencies \citep{Shpitser08}. Finally, in the Appendix, we provide further examples to illustrate the performance of the IBSSI method, we show in detail how the new rules are integrated within a standard algorithm \--such as the Causal Inference (CI) algorithm of \cite{Spirtes00}\--, and we describe how the standard faithfulness assumption \citep{Spirtes00,Pearl09} that ensures an isomorphic relation between conditional independencies and the causal structure can be equally formulated as an assumption of faithfulness between probability distributions from systems containing sufficient statistics and augmented causal graphs representing also those statistics. \section{Preliminaries} \label{ss1} We first review the basic elements of structure learning from conditional independencies that underpin our application of sufficient statistics. We start with some basic notation for Directed Acyclic Graphs (DAGs). We use bold letters for sets and vectors. Consider a set of random variables $\mathbf{V} = \{ \mathrm{V}_1,...,\mathrm{V}_p\}$. A graph $G = (\mathbf{V}; \mathcal{E})$ consists of nodes $\mathbf{V}$ and edges $\mathcal{E}$ between the nodes. $(\mathrm{V}; \mathrm{V}) \notin \mathcal{E}$ for any $\mathrm{V} \in \mathbf{V}$. We write $\mathrm{V}_i \rightarrow \mathrm{V}_j$ for $(\mathrm{V}_i;\mathrm{V}_j)\in \mathcal{E}$. We denote by $\mathrm{V}$ both variable $\mathrm{V}$ and its corresponding node. A node $\mathrm{V}_i$ is called a parent of $\mathrm{V}_j$ if $(\mathrm{V}_i;\mathrm{V}_j)\in \mathcal{E}$. The set of parents of $\mathrm{V}_j$ is denoted by $\mathbf{Pa}_{\mathrm{V}_j}$. Two nodes $\mathrm{V}_i$ and $\mathrm{V}_j$ are adjacent if either $(\mathrm{V}_i; \mathrm{V}_j) \in \mathcal{E}$ or $(\mathrm{V}_j; \mathrm{V}_i) \in \mathcal{E}$. A path in $G$ is a sequence of (at least two) distinct nodes $\mathrm{V}_1, ... , \mathrm{V}_n,$ such that there is an edge between $\mathrm{V}_k$ and $\mathrm{V}_{k+1}$ for all $k = 1, ... , n-1 $. If all edges are $\mathrm{V}_k \rightarrow \mathrm{V}_{k+1}$ the path is a causal or directed path. The set of descendants $\mathbf{D}_{\mathrm{V}_i}$ of node $\mathrm{V}_i$ comprises those variables that can be reached going forward through causal pathways from $\mathrm{V}_i$. The set of non-descendants $\mathbf{ND}_{\mathrm{V}_i}$ is complementary to it. Since the graph is acyclic no node is its own descendant. A node $\mathrm{V}_i$ is a collider in a path if it has incoming arrows $\mathrm{V}_{i-1} \rightarrow \mathrm{V}_i \leftarrow \mathrm{V}_{i+1}$ and is a noncollider otherwise. Assume that for a system the generative mechanisms of each variable $\mathrm{V}_i \in \mathbf{V}$ can be captured by a functional equation $\mathrm{V}_i := f_{\mathrm{V}_i}(\mathbf{Pa}_{\mathrm{V}_i}, \varepsilon_{\mathrm{V}_i})$, where $\varepsilon_{\mathrm{V}_i}$ represents exogenous noises and $\mathbf{Pa}_{\mathrm{V}_i}$ indicates that in the associated DAG representing the causal structure of the system each variable is connected by an incoming arrow to all and only the arguments of its functional equation. Structure learning from conditional independencies relies on the possibility to relate the causal structure to conditional independencies in the joint probability distribution of the variables. The keystone for this connection is the concept of \emph{d-separation} \citep{Pearl86}, which defines a graphical criterion of separability between nodes analogous to the statistical criterion of independence between variables. Two nodes $\mathrm{X}$ and $\mathrm{Y}$ are \emph{d-separated} given a set of nodes $\mathbf{S}$ if and only if no $\mathbf{S}$-active paths exist between $\mathrm{X}$ and $\mathrm{Y}$ \citep{Pearl86}. A path is active given the set of conditioning variables $\mathbf{S}$ ($\mathbf{S}$-active) if no noncollider in the path belongs to $\mathbf{S}$ and every collider either is in $\mathbf{S}$ or has a descendant in $\mathbf{S}$. Assuming that a causal structure $G$ and a generated probability distribution $p(\mathbf{V})$ are \emph{faithful} to one another, a conditional independence between $\mathrm{X}$ and $\mathrm{Y}$ given $\mathbf{S}$ \--denoted by $(\mathrm{X} \perp \mathrm{Y}|\mathbf{S})_{P}$\-- holds if and only if there is no $\mathbf{S}$-active path between them, that is, if $\mathrm{X}$ and $\mathrm{Y}$ are d-separated given $\mathbf{S}$ \--denoted by $(\mathrm{X} \perp \mathrm{Y}|\mathbf{S})_{G}$. Under this faithfulness assumption \citep{Spirtes00}, an isomorphic relation holds between $(\mathrm{X} \perp \mathrm{Y}|\mathbf{S})_{P}$ and $(\mathrm{X} \perp \mathrm{Y}|\mathbf{S})_{G}$, which can both simply be denoted by $\mathrm{X} \perp \mathrm{Y}|\mathbf{S}$. When only a subset of the variables are observable, two types of graphs have been used to represent only the causal relations between the observable variables, without explicitly including the hidden variables, namely the so-called Inducing Path Graphs (IPGs) \citep{Spirtes00} and Maximal Ancestral Graphs (MAGs) \citep{Richardson2002}. Despite their difference, it here suffices to say that they both represent with bidirected arrows ($\leftrightarrow$) the existence of paths between observable variables only containing hidden nodes, and that, incorporating $\leftrightarrow$ to the type of edges that create colliders and noncolliders, for these graphs the same graphical criterion of separation serves to connect conditional dependencies to the existence of active paths between variables. See Appendix A for a more formal review of causal models and the faithfulness assumption, which we also extend to systems containing sufficient statistics. Structure learning algorithms based on conditional independencies use the connection between the independencies and the causal structure to construct a partially oriented graph which represents the class of causal structures that result in the same observed conditional independencies, the so-called Markov equivalence class \citep{Spirtes00, Pearl09}. The graph represents the causal properties common to any causal structure in the same class. An edge $\mathrm{V}_i \-- \mathrm{V}_j$ indicates that no conditioning set $\mathbf{S}$ can create an independence between $\mathrm{V}_i$ and $\mathrm{V}_j$, that is, that they are nonseparable. In these partially oriented graphs, like for IPGs and MAGs, in the presence of hidden variables nonseparability may also be due to active paths between the variables conformed by hidden variables, e.g.\,due to a hidden common cause ($\mathrm{V}_i \leftrightarrow \mathrm{V}_j$). The algorithms use orientation rules to infer the presence or lack of arrows from combinations of conditional dependencies and independencies. We use the notation $\bullet \--$ to refer to an edge in the partially oriented graph whose end is undetermined and we use $* \--$ as a placeholder for either $\bullet \--$, $\--$, or $\leftarrow$. Accordingly, $\mathrm{V}_i * \rightarrow \mathrm{V}_j$ indicates that an arrow pointing to $\mathrm{V}_j$ has been inferred, while the other end of the edge can have an arrow ($ \leftrightarrow $), no arrow ($\rightarrow $), or be undetermined ($\bullet\rightarrow$). Furthermore, $*-\underline{*\mathrm{V}_i*}-*$ indicates that it has been inferred that $\mathrm{V}_i$ is a noncollider. \cite{Zhang08c} introduced additional orientation rules to the set used in the original FCI algorithm \citep{Spirtes00} and proved the completeness of that extended set to exploit all the causal information from conditional independencies. That set of rules \--or a subset of it\-- is at the core of all the structure learning algorithms based on conditional independencies. Many proposals in the literature have contributed refining the algorithms implementing these rules \citep[see][for a review]{Drton17,Heinze17,Petersbook,Malinsky18,Glymour19}. In this work our aim is to introduce additional rules that can be added to the complete set of standard rules, and which can then be included in any of the specific implementations. For this reason, we now focus on reviewing the two basic rules at the core of the complete set of rules of \cite{Zhang08c}. These two basic rules follow directly from the definition of d-separation \citep{Pearl86} and exploit the different effect of colliders and noncolliders in the propagation of dependencies, as stated in the following propositions: \vspace*{2mm} \noindent \textbf{Proposition 1}: \emph{Consider variables} $\mathrm{X}$, $\mathrm{Y}$, \emph{and} $\mathrm{Z}$, \emph{with} $\mathrm{X} \-- \mathrm{Y}$ \emph{and} $\mathrm{Y} \-- \mathrm{Z}$ \emph{nonseparable}. \emph{If} $\exists \mathbf{S}$ \emph{nonoverlapping with} $\{ \mathrm{X}, \mathrm{Y}, \mathrm{Z}\}$ \emph{such that} $ \mathrm{X} \perp \mathrm{Z} |\mathbf{S}$, \emph{then in the underlying causal structure} $\mathrm{Y}$ \emph{is a collider in the junction of any $\mathbf{S}$-active path} $\mathrm{X} \cdot \cdot \cdot \mathrm{Y}$ \emph{and any $\mathbf{S}$-active path} $\mathrm{Y} \cdot \cdot \cdot \mathrm{Z}$. \vspace*{1mm} \noindent \textbf{Proposition 2}: \emph{Consider variables $\mathrm{X}$, $\mathrm{Y}$, and $\mathrm{Z}$ with $\mathrm{X} \-- \mathrm{Y}$ and $\mathrm{Y} \-- \mathrm{Z}$ nonseparable. If $\exists \mathbf{S}$ \emph{nonoverlapping with} $\{ \mathrm{X}, \mathrm{Y}, \mathrm{Z}\}$ \emph{such that} $\mathrm{X} \notperp \mathrm{Z} |\mathbf{S}$ and $ \mathrm{X} \perp \mathrm{Z} |\mathbf{S},\mathrm{Y}$, then in the underlying causal structure $\mathrm{Y}$ is a noncollider in the junction of any $\mathbf{S}$-active path $\mathrm{X} \cdot \cdot \cdot \mathrm{Y}$ and $\mathbf{S}$-active path $\mathrm{Y} \cdot \cdot \cdot \mathrm{Z}$}. These propositions reflect that conditioning has the effect of activating colliders and inactivating noncolliders. The logic of Proposition 1 is that, since $\mathrm{Y}$ is not separable from $\mathrm{X}$ and $\mathrm{Z}$, for any conditioning set $\mathbf{S}$ there must be some active path between $\mathrm{X}$ and $\mathrm{Y}$ and between $\mathrm{Y}$ and $\mathrm{Z}$. If $\mathbf{S}$ does not include $\mathrm{Y}$, the concatenation of any $\mathbf{S}$-active path between $\mathrm{X}$ and $\mathrm{Y}$ and any $\mathbf{S}$-active path between $\mathrm{Y}$ and $\mathrm{Z}$ would result in an $\mathbf{S}$-active path between $\mathrm{X}$ and $\mathrm{Z}$, unless $\mathrm{Y}$ is a collider between those paths. In the case of Proposition 2, since it is the addition of $\mathrm{Y}$ to the conditioning set what creates the independence $ \mathrm{X} \perp \mathrm{Z} |\mathbf{S},\mathrm{Y}$, conditioning on $\mathrm{Y}$ must deactivate the $\mathbf{S}$-active paths responsible for $ \mathrm{X} \notperp \mathrm{Z} |\mathbf{S}$, which means that $\mathrm{Y}$ has to be a noncollider in those paths. These propositions indicate whether $\mathrm{Y}$ is a collider or a noncollider in specific $\mathbf{S}$-active paths, but in general determining which paths are $\mathbf{S}$-active in itself requires additional knowledge of the causal structure along those paths. However, the nonseparability of $\mathrm{X}$ and $\mathrm{Y}$ indicates that there is some path between $\mathrm{X}$ and $\mathrm{Y}$ active for $\mathbf{S} = \emptyset$ , which cannot be deactivated with any set $\mathbf{S}$ without simultaneously activating a $\mathbf{S}$-active path, and analogously from the nonseparability of $\mathrm{Z}$ and $\mathrm{Y}$. This means that, irrespectively of which $\mathbf{S}$ is selected, propositions 1 and 2 apply to those paths corresponding to the direct links $\mathrm{X} \-- \mathrm{Y}$ and $ \mathrm{Y} \-- \mathrm{Z}$ in the partially oriented graph. Therefore, under the assumption of faithfulness between conditional independencies and the causal structure, the propositions allow inferring whether $\mathrm{Y}$ is a collider or noncollider in the paths corresponding to the concatenation of $\mathrm{X} \-- \mathrm{Y}$ and $ \mathrm{Y} \-- \mathrm{Z}$: \vspace*{2mm} \noindent \textbf{Rule $\mathbf{R.c}$}\ \ \textbf{Inference of a collider}: \emph{Consider variables $\mathrm{X}$, $\mathrm{Y}$, and $\mathrm{Z}$, with $\mathrm{X} \-- \mathrm{Y}$ and $\mathrm{Y} \-- \mathrm{Z}$ nonseparable. If $\exists \mathbf{S}$ nonoverlapping with $\{ \mathrm{X}, \mathrm{Y}, \mathrm{Z}\}$ such that $ \mathrm{X} \perp \mathrm{Z} |\mathbf{S}$, then orient $\mathrm{X} *\--*\mathrm{Y} *\--* \mathrm{Z}$ as $\mathrm{X} *\rightarrow \mathrm{Y} \leftarrow* \mathrm{Z}$}. \vspace*{1mm} \noindent \textbf{Rule $\mathbf{R.nc}$}\ \ \textbf{Inference of a noncollider}: \emph{Consider variables $\mathrm{X}$, $\mathrm{Y}$, and $\mathrm{Z}$ with $\mathrm{X} \-- \mathrm{Y}$ and $\mathrm{Y} \-- \mathrm{Z}$ nonseparable. If $\exists \mathbf{S}$ nonoverlapping with $\{ \mathrm{X}, \mathrm{Y}, \mathrm{Z}\}$ such that $\mathrm{X} \notperp \mathrm{Z} |\mathbf{S}$ and $ \mathrm{X} \perp \mathrm{Z} |\mathbf{S},\mathrm{Y}$, then mark $\mathrm{X} *\--*\mathrm{Y} *\--* \mathrm{Z}$ as $\mathrm{X} *-\underline{*\mathrm{Y}*}-* \mathrm{Z}$}. \vspace*{1mm} These two rules are at the core of the structure learning algorithms based on conditional independencies. For example, they correspond to step C) of the Causal Inference (CI) algorithm of \cite{Spirtes00}. Importantly, these rules can only be applied because $\mathrm{X}$ and $\mathrm{Z}$ are separable. The sufficient statistics will allow us to formulate analogous rules for cases in which they are not separable. \section{Structure Learning with Sufficient Statistics} \label{ss2} We here present the general formulation of the use of sufficient statistics to augment the inferential power of structure learning algorithms based on conditional independencies. We will introduce counterparts of rules R.c and R.nc that do not require that $\mathrm{X}$ and $\mathrm{Z}$ are separable when conditioning on a set of observable variables, but alternatively use sufficient statistics to separate them. These additional rules can then be added to the set used in any standard structure learning algorithm that uses conditional independencies to infer causal relations in systems possibly containing hidden variables. \begin{figure* \begin{center} \scalebox{0.5}{\includegraphics*{F0.pdf}} \end{center} \caption{Sufficient statistics provide new causal information by creating new conditional independencies. \textbf{A}) Example of a DAG representing the causal structure of a system. \textbf{B}) Partially oriented graph obtained applying the standard rules of causal orientation. No edge can be oriented, all ends of the edges are undetermined, as denoted by $\bullet\--$. The only conditional independence is $\mathrm{V} \perp \mathrm{Y}| \mathrm{X},\mathrm{Z}$ which using rule R.nc provides the only causal information that can be extracted in this case, namely the presence of the noncolliders $\mathrm{V} \bullet-\underline{\bullet\mathrm{X}\bullet}-\bullet \mathrm{Y}$ and $\mathrm{V} \bullet-\underline{\bullet\mathrm{Z}\bullet}-\bullet \mathrm{Y}$. \textbf{C}) Graph with the same causal structure of the DAG in A) but explicitly representing an underlying sufficient statistic $\theta$ embodied in the functional equation of $\mathrm{Z}$. \textbf{D}) Partially oriented graph obtained when inferring the causal structure in A) complementing the standard rules of causal orientation with causal knowledge that can be learned from the new conditional independence $\mathrm{Z} \perp \mathrm{X} \mathrm{V}| \theta$ created by the sufficient statistic. In comparison to B), the collider $\mathrm{Z} \bullet\rightarrow \mathrm{Y} \leftarrow\bullet \mathrm{X}$ is identified.} \label{f0} \end{figure*} We start examining a concrete example of the use of sufficient statistics for structure learning. Figure \ref{f0}A shows a causal structure for which the standard orientation rules do not allow orienting any edge (Figure \ref{f0}B). The only independence is $\mathrm{V} \perp \mathrm{Y}| \mathrm{X},\mathrm{Z}$ which using rule R.nc determines the noncolliders $\mathrm{V} \bullet-\underline{\bullet\mathrm{X}\bullet}-\bullet \mathrm{Y}$ and $\mathrm{V} \bullet-\underline{\bullet\mathrm{Z}\bullet}-\bullet \mathrm{Y}$. Consider now that in the functional equation $f_\mathrm{z}(\mathrm{X},\mathrm{V}, \varepsilon_\mathrm{z})$, the role of $\mathrm{X}$ and $\mathrm{V}$ can be jointly captured by a single function $\theta = g(\mathrm{X}, \mathrm{V})$, that is, $f_\mathrm{z}(\mathrm{X},\mathrm{V},\varepsilon_\mathrm{z})$ can be expressed as $f_\mathrm{z}(\theta, \varepsilon_\mathrm{z})$. For example, $g(\mathrm{X}, \mathrm{V})$ could be $a\mathrm{X} +b\mathrm{V}$, $a\mathrm{X} -b\mathrm{V}$ \--with arbitrary coefficients $a,b$\--, could be $\mathrm{X}\cdot\mathrm{V}$, $\mathrm{X}/\mathrm{V}$, or more complicate functions, e.g. $\cos(\mathrm{X})+ \exp(\mathrm{V}^2)$. The key point is that \--in this case both $\mathrm{X}$ and $\mathrm{V}$\--, only determine $\mathrm{Z}$ through $\theta$. The function $f_\mathrm{z}$ can have an arbitrarily complex form as a function of $\theta$, but once a value $\theta = \theta_0$ is fixed, $\mathrm{Z}$ becomes independent of $\mathrm{X}$ and $\mathrm{V}$, that is, $\theta$ is a sufficient statistic for $\mathrm{X}$ and $\mathrm{V}$. In Figure \ref{f0}C we graphically represent the sufficient statistic. Below we will explain which is in general the relation between a graph $G$ representing the causal structure of the variables of a system and an augmented graph $G^+_{\theta}$ representing also the sufficient statistics present in the system. We will use the graphical representations of the statistics to visualize the conditional independencies they create. In particular, in Figure \ref{f0}C, $\mathrm{Z}$ is d-separated from both $\mathrm{X}$ and $\mathrm{V}$ given $\theta$. As we will see, a rule analogous to rule R.c can exploit the independence $\mathrm{Z} \perp \mathrm{X}| \theta$ to orient the collider $\mathrm{Z} \bullet\rightarrow \mathrm{Y} \leftarrow\bullet \mathrm{X}$ (Figure \ref{f0}D). We now define when, within the generative functional equation of a variable, a sufficient statistic exists for one of its parents. \vspace*{1mm} \noindent \textbf{Definition 1}\ \textbf{Sufficient statistic in a functional equation}: \emph{A functional sufficient statistic $\theta_z(\mathrm{X}; \tilde{\mathbf{V}})$ for $\mathrm{X} \in \mathbf{Pa}_z$ exists if there is a set $\tilde{\mathbf{V} }= \{\tilde{\mathrm{V}}_1,...,\tilde{\mathrm{V}}_m\} \subset \mathbf{Pa}_z$ such that a function $\theta_z = g(\mathrm{X}, \tilde{\mathbf{V}})$ exists that allows reparameterizing the functional equation $\mathrm{Z}:= f_z(\mathbf{Pa}_z, \varepsilon_z)$ to $\mathrm{Z}:= f_z(\mathbf{Pa}_z \backslash \mathrm{X}, \theta_z(\mathrm{X}; \tilde{\mathbf{V}}), \varepsilon_z)$.} \vspace*{1mm} The sufficient statistic is a function $g(\mathrm{X}, \tilde{\mathbf{V}})$ of some parents of $\mathrm{Z}$, including $\mathrm{X}$, embedded within the functional equation of $\mathrm{Z}$. Trivially, $\mathrm{X}$ is a sufficient statistic for itself if it is a parent of $\mathrm{Z}$. However, in this case and generally if the relation between the statistic and $\mathrm{X}$ is invertible, the statistic will not be useful to create a conditional independence between $\mathrm{X}$ and $\mathrm{Z}$ when conditioning on it, since the entropy $H(\mathrm{X}|\theta_z)$ is zero. In Section \ref{ss3} we will discuss criteria to select sufficient statistics useful for structure learning. \begin{figure*}[t] \begin{center} \scalebox{0.34}{\includegraphics*{F1b.pdf}} \end{center} \caption{Structure learning with sufficient statistics. Examples of causal structures in which $\mathrm{X}$ and $\mathrm{Z}$ are nonseparable and the standard rules of causal orientation cannot determine whether $\mathrm{Y}$ is a collider or a noncollider in $\mathrm{X} \-- \mathrm{Y} \-- \mathrm{Z}$, while the existence of sufficient statistics provides this additional causal information. In each column the upper graph $G$ is a standard graph representing the causal structure of the system. The lower graph $G^+_{\theta}$ also represents the functional sufficient statistics present in the systems (see text for details on the relation between $G$ and $G^+_{\theta}$). \textbf{A-B}) Systems with a functional sufficient statistic $\theta$ for $\mathrm{X}$ in the functional equation of $\mathrm{Z}$. \textbf{C}) System with a functional statistics' sufficient set for $\mathrm{X}$ in the equation of $\mathrm{Z}$, formed by two functional statistics. \textbf{D}) System in which, apart from a functional statistic $\theta$ for $\mathrm{X}$ in the functional equation of $\mathrm{Z}$, there is also an auxiliary functional statistic $\gamma$ that reduces the conditioning set $\mathbf{S}$ needed to create an independence. See main text for definitions and further explanations.} \label{f1} \end{figure*} Figure \ref{f1}A-B show two more examples of systems with a sufficient statistic for $\mathrm{X}$ in the functional equation of $\mathrm{Z}$. In both columns, the graph $G$ on the top corresponds to a standard DAG representing the causal structure of the system. The bottom graph provides a graphical representation of the functional sufficient statistics using an augmented graph $G^+_{\theta}$ which incorporates the structure of the statistics to the graph. We will use this type of graphs only for visualization of the statistics and of the independencies they create. The purpose is still to infer a partially oriented graph associated with the causal structure of the observable variables. A graph $G^+_{\theta}$ associated with a graph $G$ has the same causal structure as $G$, except that it explicitly represents a sufficient statistic $\theta$ as a node with incoming arrows from all the variables corresponding to the arguments in the subfunction that defines it, and an outgoing arrow to the variable (or variables) in which functional equation the statistic is embedded. Therefore, the parenthood structure of $G^+_{\theta}$ is the same as the one of $G$, except that each node has also as parents the sufficient statistics embodied in its functional equation, while those variables that only appear in the functional equation of another through sufficient statistics lose their parenthood status. This means that by construction d-separation graphically represents also the conditional independencies created conditioning on the sufficient statistics. In Appendix A we formalize the concept of causal models with sufficient statistics and we formalize the connection between a graph $G$ and the augmented graph $G^+_{\theta}$ that also represents sufficient statistics (Definition S4). If not stated otherwise, we will refer to adjacency and parenthood relations as determined in $G$, and not in the associated $G^+_{\theta}$. The same procedure to construct $G^+_{\theta}$ is applicable independently of whether $\mathrm{G}$ is a DAG containing only directed arrows or an IPG, in which hidden variables are not represented and their presence is represented with bidirected arrows. Similarly, given that for any DAG there is a unique MAG that represents the conditional independencies and causal relations embodied in the DAG \citep{Richardson2002}, the augmented graphs can be constructed for MAGs with the same procedure. In Figure \ref{f1}A, $\mathrm{X}$ only determines $\mathrm{Z}$ through $\theta = g(\mathrm{X}, \mathrm{V}_1)$. Similarly, in Figure \ref{f1}B, $\theta = g(\mathrm{X}, \mathrm{V}_1, \mathrm{V}_2, \mathrm{V}_3)$. In more general cases, it may be needed more than one functional statistic to capture the effect of $\mathrm{X}$ on $\mathrm{Z}$. We therefore extend the definition to a sufficient set of statistics. \vspace*{1mm} \noindent \textbf{Definition 2}\ \textbf{Sufficient set of statistics in a functional equation}: \emph{In the functional equation of $\mathrm{Z}$, there is a sufficient set of K functional statistics (fss-set) $\Theta_z(\mathrm{X}; \alpha) = \{\theta_{z1}(\mathrm{X}; \tilde{\mathbf{V}}_1),...,\theta_{zK}(\mathrm{X}; \tilde{\mathbf{V}}_K) \}$ for $\mathrm{X} \in \mathbf{Pa}_z$ if there is a set $\alpha = \{\tilde{\mathbf{V}}_1,...,\tilde{\mathbf{V}}_K\}$ such that a set of functions $\theta_{zi} = g_i(\mathrm{X}, \tilde{\mathbf{V}}_i)$ $\forall \theta_{zi} \in \Theta_z(\mathrm{X}; \alpha)$ exists, with $\tilde{\mathbf{V}_i }= \{\tilde{\mathrm{V}}_1,...\tilde{\mathrm{V}}_{m_i}\} \subset \mathbf{Pa}_z$, which allow reparameterizing $f_z(\mathbf{Pa}_z, \varepsilon_z)$ to $f_z(\mathbf{Pa}_z \backslash \mathrm{X}, \Theta_z(\mathrm{X}; \alpha) , \varepsilon_z)$.} Figure \ref{f1}C shows a fss-set $\Theta_z(\mathrm{X}; \alpha) = \{ \theta_1, \theta_2\}$, with $\tilde{\mathbf{V}}_1 = \mathrm{V}_1$ and $\tilde{\mathbf{V}}_2 = \mathrm{V}_2$. Importantly, a fss-set $\Theta_z(\mathrm{X}; \alpha)$ creates a new conditional independence, separating $\mathrm{Z}$ from $\mathrm{X}$. \vspace*{1mm} \noindent \textbf{Proposition 3}\ \textbf{Conditional independence with functional sufficient statistics}: \emph{If the functional equation of $\mathrm{Z}$ has an fss-set $\Theta_z(\mathrm{X}; \alpha)$ for $\mathrm{X} \in \mathbf{Pa}_z$ there is at least one set $\mathbf{S}$ disjoint to $\{\mathrm{X}, \mathrm{Z}\}$ such that for $\mathbf{S}_{\Theta_z} = \{ \Theta_z(\mathrm{X};\alpha), \mathbf{S}\}$, $\mathrm{Z} \perp \mathrm{X} | \mathbf{S}_{\Theta_z}$.} \vspace*{1mm} \noindent Proof: By definition of a sufficient set of functional statistics, $\mathrm{Z}$ and $\mathrm{X}$ are conditionally independent given $\mathbf{S}_{\Theta_z} = \{ \Theta_z(\mathrm{X};\alpha), \mathbf{Pa}_z \backslash \mathrm{X}\}$.\ \ $\Box$ Given the existence of the fss-set $\Theta_z(\mathrm{X}; \alpha)$ for $\mathrm{X}$ in the functional equation of $\mathrm{Z}$, in the augmented graph $G^+_{\theta}$ node $\mathrm{X}$ is not anymore a parent of node $\mathrm{Z}$, and the new set of parents comprises $\Theta_z(\mathrm{X};\alpha)$. As described above, the parenthood structure of $G^+_{\theta}$ is constructed so that, despite the deterministic relations defining the sufficient statistics, d-separation can also be used to read the new conditional independencies created when conditioning on sets comprising sufficient statistics. This is in contrast to the case in which deterministic relations exist between the variables of the system, which generally requires an extended criterion of graphical separability \citep{Geiger90}. Like with standard algorithms such as the FCI, we assume that no deterministic relations exist between the variables in the system, that is, that the only deterministic relations are the ones defining the sufficient statistics. See Appendix A for a comparison of how deterministic relations between variables of the system or in the definition of the statistics affect the connection between conditional independencies and criteria of graphical separability. The existence of a sufficient set of statistics in general does not only create the conditional independence corresponding to using $\{ \Theta_z(\mathrm{X};\alpha), \mathbf{Pa}_z \backslash \mathrm{X}\}$ to separate $\mathrm{Z}$ and $\mathrm{X}$. As we will discuss below, a small conditioning set $\mathbf{S}$ is desirable in order to not constrain $\mathrm{X}$. In Figure \ref{f1}A, $\mathbf{S} = \mathrm{V}_2$ leads to $\mathrm{Z} \perp \mathrm{X} | \theta, \mathrm{V}_2$. In Figure \ref{f1}B, both with $\mathbf{S} = \{\mathrm{Y}, \mathrm{V}_1, \mathrm{V}_4, \mathrm{V}_6\}$ and $\mathbf{S} = \{\mathrm{Y}, \mathrm{V}_1, \mathrm{V}_3, \mathrm{V}_5\}$, the set $\{\theta, \mathbf{S}\}$ separates $\mathrm{Z}$ and $\mathrm{X}$. Similarly $\mathrm{Z} \perp \mathrm{X} | \theta_1, \theta_2, \mathrm{V}_3$ in Figure \ref{f1}C. As seen from these examples, the set $\mathbf{S}$ may include other parents of $\mathrm{Z}$, and also other variables that inactivate paths between $\mathrm{X}$ and $\mathrm{Z}$ (such as $\mathrm{V}_6$ in Figure \ref{f1}B). The definitions above use knowledge about the functional equation of $\mathrm{Z}$ and its parents which is not directly available from the data. We therefore define a sufficient condition for the existence of a sufficient set of statistics for a pair of variables without requiring any knowledge about the functional structure. \vspace*{1mm} \noindent \textbf{Definition 3}\ \textbf{Sufficient set of statistics for a pair of variables}: \emph{Two nonseparable variables $\mathrm{X},\mathrm{Z}$ have a sufficient set of K statistics (ss-set) $\Psi_{x,z}(\alpha) = \{\psi_1(\mathrm{X},\mathrm{Z}; \tilde{\mathbf{V}}_1) ,...,$ $\psi_K(\mathrm{X},\mathrm{Z}; \tilde{\mathbf{V}}_K)\}$ if there is a set $\alpha = \{ \tilde{\mathbf{V}}_1,...,\tilde{\mathbf{V}}_K\}$ such that $\mathrm{X}, \mathrm{Z} \notin \bigcup \alpha$, a set of functions $\psi_i = g_i(\mathrm{W}_i, \tilde{\mathbf{V}}_i)$ $\forall \psi_i \in \Psi_{x,z}(\alpha)$ exists, with $\mathrm{W}_i= \mathrm{Z}\ \forall i$ or $\mathrm{W}_i= \mathrm{X}\ \forall i$, and there is a set $\mathbf{S}$ nonoverlapping with $\{\mathrm{X},\mathrm{Z}\}$ such that $\mathrm{Z} \perp \mathrm{X} | \mathbf{S}_{\Psi_{x,z}}$, where $\mathbf{S}_{\Psi_{x,z}} = \{ \Psi_{x,z}(\alpha), \mathbf{S}\}$.} \vspace*{1mm} The union $\bigcup \alpha$ indicates the union of all elements in the sets composing set $\alpha$, that is, $\mathrm{X}, \mathrm{Z} \notin \bigcup \alpha$, indicates that $\forall \tilde{\mathbf{V}}_i \in \alpha \ \mathrm{X}, \mathrm{Z} \notin \tilde{\mathbf{V}}_i $. Definition 3 does not rely on information about the causal structure, and defines the statistics' sufficient set $\Psi_{x,z}(\alpha)$ based on the conditional independence $\mathrm{Z} \perp \mathrm{X} | \mathbf{S}_{\Psi_{x,z}}$ it creates. This means that, to be able to use sufficient sets of statistics for structure learning, we need to extend the standard faithfulness assumption to enforce also an isomorphic relation between conditional independencies that can be created inferring sufficient sets of statistics from the distribution $p(\mathbf{V})$ of observable variables and the form of underlying functional sufficient statistics existing in the system. Accordingly, if a graph $G$ is used to represent the causal structure of a system and an augmented graph $G^+_{\theta}$ is built as mentioned above to represent the sufficient statistics existing in the system, the extended faithfulness assumption serves to guarantee that $\mathrm{X} \perp \mathrm{Z}| \mathbf{S}_{\Psi_{x,z}}$ is embodied in $p(\mathbf{V})$ if and only if the causal structure and the form of the sufficient statistics embodied in the functional equations is consistent with the form of $\Psi_{x,z}(\alpha)$. See Appendix A for a formalization of this extended faithfulness assumption (Definition S6). Under the extended faithfulness assumption, $\Psi_{x,z}(\alpha)$ corresponds to an underlying sufficient set of functional statistics, which may be a fss-set $\Theta_z(\mathrm{X}; \alpha)$ within the functional equation of $\mathrm{Z}$, a fss-set $\Theta_x(\mathrm{Z}; \alpha)$ within the functional equation of $\mathrm{X}$, or also may reflect the presence of statistics in the functional equation of an intermediate variable that is both a collider and a noncollider in paths between $\mathrm{X}$ and $\mathrm{Z}$, rendering them nonseparable. For example, in a system with $\mathrm{X} \rightarrow \mathrm{V} \rightarrow \mathrm{Z}$ and $\mathrm{V} \leftrightarrow \mathrm{Z}$, conditioning on $\mathrm{V}$ to inactivate the directed path in which it is a noncollider activates the path through the bidirected arc, in which it is a collider, rendering $\mathrm{X}$ and $\mathrm{Z}$ nonseparable. Sufficient statistics embodied in the functional equation of $\mathrm{V}$ would allow inactivating the causal path without activating the collider in $\mathrm{V}$. Furthermore, as we will see in Section \ref{ss5}, in the presence of selection bias a sufficient set of statistics may exist also in the functional equation of a hidden variable which is conditioned. Regardless of within which functional equations the statistics are located, the utility of $\Psi_{x,z}(\alpha)$ lies in separating $\mathrm{Z}$ and $\mathrm{X}$ with $\mathbf{S}_{\Psi_{x,z}}$. Under the extended faithfulness assumption that guarantees an isomorphic relation between conditional independencies and both the causal structure of the observable variables and the structure of existing sufficient statistics, the new conditional independencies created by the statistics allow extending the rules of inference to the case in which the variables are nonseparable without sufficient statistics. \vspace*{1mm} \noindent \textbf{Rule $\mathbf{R.c-ss}$}\ \ \textbf{Inference of a collider with sufficient statistics}: \emph{Consider variables $\mathrm{X}$, $\mathrm{Y}$, $\mathrm{Z}$, all nonseparable. Find a sufficient set of statistics $\Psi_{x,z}(\alpha)$ and a set $\mathbf{S}$ nonoverlapping with $\{ \mathrm{X}, \mathrm{Y}, \mathrm{Z}\}$ such that $\mathrm{Y} \notin \bigcup \alpha$ and, for $\mathbf{S}_{\Psi_{x,z}} = \{\mathbf{S}, \Psi_{x,z}(\alpha)\}$, it holds that $\mathrm{X} \notperp \mathrm{Y} |\mathbf{S}_{\Psi_{x,z}}$, $\mathrm{Y} \notperp \mathrm{Z} |\mathbf{S}_{\Psi_{x,z}}$, and $\mathrm{X} \perp \mathrm{Z} |\mathbf{S}_{\Psi_{x,z}}$, then orient $\mathrm{X} *\--*\mathrm{Y} *\--* \mathrm{Z}$ as $\mathrm{X} *\rightarrow \mathrm{Y} \leftarrow* \mathrm{Z}$.} \vspace*{1mm} \noindent Proof: Conditions $\mathrm{X} \notperp \mathrm{Y} |\mathbf{S}_{\Psi_{x,z}}$ and $\mathrm{Y} \notperp \mathrm{Z} |\mathbf{S}_{\Psi_{x,z}}$ ensure that $\mathrm{X}$ and $\mathrm{Z}$ are still nonseparable from $\mathrm{Y}$ with a conditioning set $\mathbf{S}_{\Psi_{x,z}}$ that apart from the observable variables in $\mathbf{S}$ also includes $\Psi_{x,z}(\alpha)$. This discards that the set $\Psi_{x,z}(\alpha)$ does include not only a sufficient set of statistics to separate $\mathrm{X}$ and $\mathrm{Z}$, but also statistics that separate $\mathrm{X}$ or $\mathrm{Z}$ from $\mathrm{Y}$. With the nonseparability of $\mathrm{X}$ and $\mathrm{Z}$ from $\mathrm{Y}$ preserved, the conditional independence $\mathrm{X} \perp \mathrm{Z} |\mathbf{S}_{\Psi_{x,z}}$ is only compatible with $\mathrm{Y}$ being a collider between $\mathrm{X}$ and $\mathrm{Z}$, since $\mathrm{Y} \notin \bigcup \alpha$ and $\mathbf{S}$ does not include $\mathrm{Y}$, and hence $\mathrm{Y}$ is not necessary to avoid that the dependencies between $\mathrm{X}$ and $\mathrm{Y}$ and between $\mathrm{Y}$ and $\mathrm{Z}$ result in a dependence between $\mathrm{X}$ and $\mathrm{Z}$. $\ \ \Box$ \vspace*{1mm} \noindent \textbf{Rule $\mathbf{R.nc-ss}$}\ \textbf{Inference of a noncollider with sufficient statistics}: \emph{Consider variables $\mathrm{X}$, $\mathrm{Y}$, $\mathrm{Z}$, all nonseparable. Find a sufficient set of statistics $\Psi_{x,z}(\alpha)$ and a set $\mathbf{S}_0$ nonoverlapping with $\{ \mathrm{X}, \mathrm{Y}, \mathrm{Z}\}$ such that, for $\mathbf{S} = \{ \mathbf{S}_0, \mathrm{Y}\}$, $\mathbf{S}_{\Psi_{x,z}} = \{\mathbf{S}, \Psi_{x,z}(\alpha) \}$, and $\mathbf{\Psi}^{(y)}_{x,z}(\alpha)$ the subset of statistics in $\Psi_{x,z}(\alpha)$ which have $\mathrm{Y}$ as an argument, it holds that $\mathrm{X} \notperp \mathrm{Y} |\mathbf{S}'$, $\mathrm{Y} \notperp \mathrm{Z} |\mathbf{S}'$, $\forall \mathbf{S}' \subseteq \mathbf{S}_{\Psi_{x,z}} \backslash \{\mathrm{Y}, \mathbf{\Psi}^{(y)}_{x,z}(\alpha) \}$, $\mathrm{X} \notperp \mathrm{Z} |\mathbf{S}_{\Psi_{x,z}} \backslash \{\mathrm{Y}, \mathbf{\Psi}^{(y)}_{x,z}(\alpha) \}$, and at least $\mathrm{X} \perp \mathrm{Z} |\mathbf{S}_{\Psi_{x,z}}$ or $\mathrm{X} \perp \mathrm{Z} |\mathbf{S}_{\Psi_{x,z}} \backslash \mathrm{Y}$, then mark $\mathrm{X} *\--*\mathrm{Y} *\--* \mathrm{Z}$ as $\mathrm{X} *-\underline{*\mathrm{Y}*}-* \mathrm{Z}$.} \vspace*{1mm} \noindent Proof: The combination of $\mathrm{X} \notperp \mathrm{Z} |\mathbf{S}_{\Psi_{x,z}} \backslash \{\mathrm{Y}, \mathbf{\Psi}^{(y)}_{x,z}(\alpha)\}$ and at least $\mathrm{X} \perp \mathrm{Z} |\mathbf{S}_{\Psi_{x,z}}$ or $\mathrm{X} \perp \mathrm{Z} |\mathbf{S}_{\Psi_{x,z}} \backslash \mathrm{Y}$ indicates that it is the fact of further adding $\{\mathrm{Y}, \mathbf{\Psi}^{(y)}_{x,z}(\alpha)\}$ or $\mathbf{\Psi}^{(y)}_{x,z}(\alpha)$ to the conditioning set what creates the independence. This means that at least $\mathrm{Y}$ or a sufficient statistic having it as an argument is required to inactivate paths that were leading to $\mathrm{X} \notperp \mathrm{Z} |\mathbf{S}_{\Psi_{x,z}} \backslash \{\mathrm{Y}, \mathbf{\Psi}^{(y)}_{x,z}(\alpha) \}$, and hence it has to be a noncollider in those paths, since only conditioning on noncolliders deactivates dependencies. The fact that $\mathrm{X} \notperp \mathrm{Y} |\mathbf{S}'$, $\mathrm{Y} \notperp \mathrm{Z} |\mathbf{S}'$, $\forall \mathbf{S}' \subseteq \mathbf{S}_{\Psi_{x,z}} \backslash \{\mathrm{Y}, \mathbf{\Psi}^{(y)}_{x,z}(\alpha) \}$ discards that the use of sufficient statistics included in $\mathbf{S}_{\Psi_{x,z}} \backslash \{\mathrm{Y}, \mathbf{\Psi}^{(y)}_{x,z}(\alpha) \}$ allows inactivating all the paths that were creating the adjacency $\mathrm{X}\--\mathrm{Y}$ or $\mathrm{Y}\--\mathrm{Z}$ when no statistics were used. This discards that there is a set $\mathbf{S}^* \subset \mathbf{S}_{\Psi_{x,z}} \backslash \{\mathrm{Y}, \mathbf{\Psi}^{(y)}_{x,z}(\alpha) \}$ for which at least $\mathrm{X} \perp \mathrm{Y} |\mathbf{S}^*$ or $\mathrm{Y} \perp \mathrm{Z} |\mathbf{S}^* $, and that it is only because of further adding to $\mathbf{S}^*$ some additional variables $\mathrm{V}^* \in \mathbf{S}_{\Psi_{x,z}} \backslash \{\mathrm{Y}, \mathbf{\Psi}^{(y)}_{x,z}(\alpha), \mathbf{S}^* \}$ that a dependence $\mathrm{X} \notperp \mathrm{Y} |\mathbf{S}_{\Psi_{x,z}} \backslash \{\mathrm{Y}, \mathbf{\Psi}^{(y)}_{x,z}(\alpha) \}$ or $\mathrm{Y} \notperp \mathrm{Z} |\mathbf{S}_{\Psi_{x,z}} \backslash \{\mathrm{Y}, \mathbf{\Psi}^{(y)}_{x,z}(\alpha) \}$ exists, because of variables in $\mathrm{V}^*$ activating some paths in which they are colliders. This discards that conditioning on $\{\mathrm{Y}, \mathbf{\Psi}^{(y)}_{x,z}(\alpha) \}$ or $\mathbf{\Psi}^{(y)}_{x,z}(\alpha)$ creates the independence $\mathrm{X} \perp \mathrm{Z} |\mathbf{S}_{\Psi_{x,z}}$ or $\mathrm{X} \perp \mathrm{Z} |\mathbf{S}_{\Psi_{x,z}} \backslash \mathrm{Y}$ from $\mathrm{X} \notperp \mathrm{Z} |\mathbf{S}_{\Psi_{x,z}} \backslash \{\mathrm{Y}, \mathbf{\Psi}^{(y)}_{x,z}(\alpha)\}$ only because inactivating the paths activated by conditioning on $\mathrm{V}^*$. The fact that the use of sufficient statistics included in $\mathbf{S}_{\Psi_{x,z}} \backslash \{\mathrm{Y}, \mathbf{\Psi}^{(y)}_{x,z}(\alpha) \}$ does not inactivate all the paths that were creating the adjacency $\mathrm{X}\--\mathrm{Y}$ or $\mathrm{Y}\--\mathrm{Z}$ when no statistics were used, also ensures that it cannot exist a collider in $\mathrm{Y}$ \--activated when conditioning on $\mathrm{Y}$ or $\mathbf{\Psi}^{(y)}_{x,z}(\alpha)$\--, which does not create a dependence between $\mathrm{X}$ and $\mathrm{Z}$ only because conditioning on the sufficient statistics in $\mathbf{S}_{\Psi_{x,z}} \backslash \{\mathrm{Y}, \mathbf{\Psi}^{(y)}_{x,z}(\alpha) \}$ inactivated all paths between $\mathrm{Y}$ and $\mathrm{X}$ or between $\mathrm{Y}$ and $\mathrm{Z}$ incoming to $\mathrm{Y}$. This means that not only $\mathrm{Y}$ has to be a noncollider in some path corresponding to $\mathrm{X} *\--*\mathrm{Y} *\--* \mathrm{Z}$, but also that it cannot be a collider in any of those paths, meaning that it has to be a noncollider in all paths corresponding to $\mathrm{X} *\--*\mathrm{Y} *\--* \mathrm{Z}$. $\ \ \Box$ These new rules are analogous to R.c and R.nc, but use the sufficient statistics to obtain a conditional independence between $\mathrm{X}$ and $\mathrm{Z}$ even when $\mathrm{X}$ and $\mathrm{Z}$ are nonseparable, that is, when a conditional independence cannot be obtained conditioning only on observable variables. As mentioned above, even if the new orientation rules exploit sufficient statistics, the purpose is, like with the standard rules, to determine the partially oriented graph representing inferred causal relationships between the observable variables. In more detail, in R.c-ss the condition $\mathrm{X} \perp \mathrm{Z} |\mathbf{S}_{\Psi_{x,z}}$ is analogous to $\mathrm{X} \perp \mathrm{Z} |\mathbf{S}$ in R.c, and the conditions $\mathrm{X} \notperp \mathrm{Y} |\mathbf{S}_{\Psi_{x,z}}$ and $\mathrm{Y} \notperp \mathrm{Z} |\mathbf{S}_{\Psi_{x,z}}$ play the role that in R.c plays the nonseparability of $\mathrm{Y}$ with $\mathrm{X}$ and $\mathrm{Z}$, which already guarantees that $\mathrm{X} \notperp \mathrm{Y} |\mathbf{S}$ and $\mathrm{Y} \notperp \mathrm{Z} |\mathbf{S}$. In R.nc-ss, $\mathrm{X} \notperp \mathrm{Z} |\mathbf{S}_{\Psi_{x,z}} \backslash \{\mathrm{Y}, \mathbf{\Psi}^{(y)}_{x,z}(\alpha) \}$, and at least $\mathrm{X} \perp \mathrm{Z} |\mathbf{S}_{\Psi_{x,z}}$ or $\mathrm{X} \perp \mathrm{Z} |\mathbf{S}_{\Psi_{x,z}} \backslash \mathrm{Y} $ are analogous to $\mathrm{X} \notperp \mathrm{Z} |\mathbf{S}$, and $\mathrm{X} \perp \mathrm{Z} |\mathbf{S}, \mathrm{Y}$ in R.nc, and $\mathrm{X} \notperp \mathrm{Y} |\mathbf{S}'$, $\mathrm{Y} \notperp \mathrm{Z} |\mathbf{S}'$, $\forall \mathbf{S}' \subseteq \mathbf{S}_{\Psi_{x,z}} \backslash \{\mathrm{Y}, \mathbf{\Psi}^{(y)}_{x,z}(\alpha) \}$ is already guaranteed in the standard rule by the nonseparability of $\mathrm{Y}$ with $\mathrm{X}$ and $\mathrm{Z}$. To be able to apply these rules it is required that the dependencies and independencies involved in the rules can be evaluated, and hence that the conditional entropies of the variables when conditioning on the sets including sufficient statistics are nonzero, that is, that some uncertainty remains after conditioning. In all examples of Figure \ref{f1} $\mathrm{X}$ and $\mathrm{Z}$ are nonseparable, and hence rules R.c and R.nc are not applicable. In fact, for all these examples a standard algorithm such as the FCI \citep{Spirtes00} cannot determine whether $\mathrm{Y}$ is a collider or a noncollider in $\mathrm{X} \-- \mathrm{Y} \-- \mathrm{Z}$. Conversely, in Figure \ref{f1}A, rule R.c-ss determines that $\mathrm{Y}$ is a collider using that $\mathrm{X} \perp \mathrm{Z}| \theta, \mathrm{V}_2$, that is, $\mathbf{S}_{\Psi_{x,z}} = \{ \theta, \mathrm{V}_2 \}$. Similarly, in Figure \ref{f1}C rule R.c-ss can be applied with $\mathbf{S}_{\Psi_{x,z}} = \{ \theta_1, \theta_2, \mathrm{V}_3 \}$. In Figure \ref{f1}B, rule R.nc-ss can be applied with $\mathbf{S}_{\Psi_{x,z}} = \{ \mathrm{Y}, \theta, \mathrm{V}_1, \mathrm{V}_4, \mathrm{V}_6 \}$. Note that, despite providing a sufficient condition for the existence of a sufficient set of statistics, Definition 3 is limited by the requirement that either $\mathrm{X}$ or $\mathrm{Z}$ appears as an argument in the functions $\psi_i = g_i(\mathrm{W}_i, \tilde{\mathbf{V}}_i)$ defining the statistics. More generally, sufficient statistics that do not have any of the two variables as an argument can also contribute to create a new conditional independence between $\mathrm{X}$ and $\mathrm{Z}$. We call this type of additional statistics \emph{auxiliary} statistics. Figure \ref{f1}D shows an example of an auxiliary statistic. Consider that in the system only the functional sufficient statistic $\theta = g_{\theta}(\mathrm{X}, \mathrm{V}_1)$ existed. Conditioning on $\theta$ inactivates the direct path from $\mathrm{X}$ to $\mathrm{Z}$, but not the indirect path from $\mathrm{X}$ to $\mathrm{Z}$ through $\mathrm{V}_1$, so $\mathrm{V}_1$ would need to be conditioned. However, conditioning on $\mathrm{V}_1$, the deterministic constraint $\theta_0 = g_\theta(\mathrm{X}, \mathrm{v}_1)$, for fixed values $\theta= \theta_0$ and $\mathrm{V}_1 = \mathrm{v}_1$, may result in a small space of solutions for $\mathrm{X}$, or even a unique value of $\mathrm{X}$ if $g_{\theta}(\mathrm{X}, \mathrm{V}_1 = \mathrm{v}_1)$ is invertible. A small or null entropy $H(\mathrm{X}| \theta, \mathrm{V}_1)$ would complicate or impede the evaluation of the dependencies and independencies as required in the new rules. The auxiliary statistic $\gamma = g_\gamma(\mathrm{V}_1,\mathrm{V}_2,\mathrm{V}_3)$ allows weakening the constraint imposed by conditioning on $\theta, \mathrm{V}_1$. This is because, using $\gamma$, the set $\mathbf{S}_{\Psi_{x,z}} = \{ \theta, \mathrm{V}_1, \mathrm{V}_2, \mathrm{V}_3 \}$ can be replaced by $\mathbf{S}_{\Psi_{x,z}} = \{ \theta, \gamma, \mathrm{V}_3\}$. The constraint $\gamma_0 = g_\gamma(\mathrm{V}_1,\mathrm{V}_2, \mathrm{v}_3)$ may be compatible with a higher number of solutions for $\mathrm{V}_1$, which in turn may increase the number of solutions for $\mathrm{X}$ in $\theta_0 = g_\theta(\mathrm{X}, \mathrm{V}_1)$. In general, an auxiliary set of statistics can allow using a set $\mathbf{S}_{\Psi_{x,z}}$ that increases the entropy $H(\mathrm{X} | \mathbf{S}_{\Psi_{x,z}})$, hence facilitating, or even enabling, the application of the rules. As we will explain and exemplify below, the IB method is powerful enough to identify sufficient statistics without any \emph{a priori} assumption of whether they contain $\mathrm{X}$ or $\mathrm{Z}$ as an argument or they are auxiliary statistics. For simplicity, we leave the formal definition of a sufficient set of statistics that includes auxiliary statistics for Appendix B. We have here introduced new orientation rules to extract causal information from conditional independencies created by sufficient sets of statistics. Importantly, these additional rules are not to be used in isolation, as an alternative to the standard set of orientation rules. On the contrary, the new rules are to be inserted within the algorithms already implementing the standard rules, such that in the presence of sufficient statistics additional information about the causal structure is inferred, while in the lack of sufficient statistics the standard Markov equivalence class is identified. To illustrate this, in Appendix C we show in detail how to insert R.c-ss and R.nc-ss in a particular standard algorithm, such as the Causal Inference (CI) algorithm of \cite{Spirtes00}. The new rules could be alternatively incorporated to any of the refined algorithms proposed to improve the implementation of the standard rules \citep[see][for a review]{Drton17,Heinze17,Petersbook,Malinsky18,Glymour19}. In Appendix C we also further introduce a counterpart based on sufficient statistics for another standard rule, and we discuss the synergies created by the combination of the standard and new rules. In the rest of the main article we will focus on how the IB method can be used to infer sufficient sets of statistics to implement rules R.c-ss and R.nc-ss. \section{Identification and selection of sufficient statistics} \label{ss3} We now address the question of how to identify and select sufficient sets of statistics with the IB method. Despite the fact that the concept of sufficient set of statistics and the rules introduced above are valid also for continuous variables, we will from now on focus on the original implementation of the IB method by \cite{Tishby99}, which works for discrete variables. In Appendix F we briefly discuss model-based approaches alternative to the IB method. \subsection{Identification of sufficient statistics with the information bottleneck method} \label{ss32} Traditionally, in the context of estimation theory, a sufficient statistic $\mathrm{T}(\mathbf{X})$ is conceived as a function of the sampled data $\mathbf{X}$ which contains all the information of those data to estimate an underlying parameter $\mu$ of the generative model \citep{Casella02}. That is, the sufficient statistic creates a conditional independence $\mu \perp \mathbf{X} | \mathrm{T}(\mathbf{X})$, or equivalently $p(\mu|\mathrm{T}(\mathbf{X}), \mathbf{X})= p(\mu|\mathrm{T}(\mathbf{X}))$. The IB method generalizes the concept of sufficient statistic from parametric to arbitrary distributions. It formulates the finding of sufficient statistics as a problem of data compression, implemented via a cost function minimization. Consider a possibly multivariate variable $\mathbf{X}$ to be compressed into a lower dimensional variable $\tilde{\mathbf{X}}$, while preserving the information about another target variable $\mathrm{Z}$. \citet{Tishby99} introduced an algorithm to define $\tilde{\mathbf{X}}$ finding the mapping $p(\tilde{\mathbf{X}}|\mathbf{X})$ optimized as \begin{subequations} \begin{align} p(\tilde{\mathbf{X}}|\mathbf{X}) & \equiv \mathrm{argmin}\ I(\tilde{\mathbf{X}};\mathbf{X})-\beta I(\tilde{\mathbf{X}};\mathrm{Z}) \label{e20}\\ & = \mathrm{argmin}\ I(\tilde{\mathbf{X}};\mathbf{X}) + \beta I(\mathbf{X};\mathrm{Z}|\tilde{\mathbf{X}}), \label{e21} \end{align} \end{subequations} where the parameter $\beta$ determines the tradeoff between compression (low mutual information $I(\tilde{\mathbf{X}};\mathbf{X})$) and information preservation (high $I(\tilde{\mathbf{X}};\mathrm{Z})$, or equivalently low $I(\mathbf{X};\mathrm{Z}|\tilde{\mathbf{X}})$). The IB algorithm proposed by \citet{Tishby99} iteratively updates the projection $p(\tilde{\mathbf{X}}|\mathbf{X})$ according to a set of self-consistent equations for $p(\tilde{\mathbf{X}}|\mathbf{X})$, $p(\mathrm{Z}|\tilde{\mathbf{X}})$, and $p(\tilde{\mathbf{X}})$, analogously to the Blahut-Arimoto algorithm used to estimate compression distortion rates \citep{Cover06}. In each iteration $p(\tilde{\mathbf{X}}|\mathbf{X})$ is iteratively updated according to \begin{equation} \label{IBeq} p(\tilde{\mathbf{X}}|\mathbf{X}) = \frac{p(\tilde{\mathbf{X}})}{Z(\mathbf{X}, \beta)} \exp \left [ -\beta \mathrm{KL}(p(\mathrm{Z}|\mathbf{X}); p(\mathrm{Z}|\tilde{\mathbf{X}})) \right ], \end{equation} where $Z(\mathbf{X}, \beta)$ is a normalization factor and $\mathrm{KL}(p(\mathrm{Z}|\mathbf{X}); p(\mathrm{Z}|\tilde{\mathbf{X}}))$ is the Kullback-Leibler divergence \citep{Kullback1959} between the conditional distribution $p(\mathrm{Z}|\mathbf{X})$ and the distribution $p(\mathrm{Z}|\tilde{\mathbf{X}})$ resulting from $p(\tilde{\mathbf{X}}|\mathbf{X})$. The final $p(\tilde{\mathbf{X}}|\mathbf{X})$ defines the output $\tilde{\mathbf{X}}$ of the algorithm. See \citet{Tishby99} for more details. In common applications of the IB method, $\mathbf{X}$ is a set of variables predetermined a priori. Conversely, when the IB method is used to identify sufficient statistics for causal inference, the selection of $\mathbf{X}$ is part of the process of determining between which variables and with which conditioning set a new conditional independence can be created identifying a sufficient set of statistics. To see this, we now examine the relation between the term $I(\mathbf{X};\mathrm{Z}|\tilde{\mathbf{X}})$ to be minimized in the IB method (Eq.\,\ref{e21}) and a mutual information of the form $I(\mathrm{X}; \mathrm{Z}| \mathbf{S}_{\Psi_{x,z}})$, which would quantify $\mathrm{X} \perp \mathrm{Z} |\mathbf{S}_{\Psi_{x,z}}$ as tested in R.c-ss or R.nc-ss. For simplicity, we consider first the case of a single sufficient statistic $\theta_z = g(\mathrm{X}, \tilde{\mathbf{V}})$, which given a set $\mathbf{S}$ creates the independence $\mathrm{X} \perp \mathrm{Z} |\mathbf{S}, \theta_z$. Since the function $\theta_z = g(\mathrm{X}, \tilde{\mathbf{V}})$ creates a dependence between $\mathrm{X}$ and any variable in $\tilde{\mathbf{V}}$ when conditioning on $\theta_z$, any variable $\mathrm{V}_i \in \tilde{\mathbf{V}}$ for which $\mathrm{Z} \notperp \mathrm{V}_i | \mathbf{S} \backslash \mathrm{V}_i, \theta_z$ must be included in $\mathbf{S}$ to obtain $\mathrm{X} \perp \mathrm{Z} |\mathbf{S}, \theta_z$. Accordingly, the sufficient statistic does not only create the independence $\mathrm{X} \perp \mathrm{Z} | \mathbf{S}, \theta_z$, but more generally $\{\mathrm{X}, \tilde{\mathbf{V}} \backslash \mathbf{S} \}\perp \mathrm{Z} | \mathbf{S}, \theta_z$. This conditional independence leads to $I(\mathrm{X}, \tilde{\mathbf{V}}, \mathbf{S}; \mathrm{Z}|\mathbf{S}, \theta_z)=0$, since this mutual information can be decomposed into $I(\mathbf{S}; \mathrm{Z}|\mathbf{S}, \theta_z)$, which is zero by construction, and $I(\mathrm{X}, \tilde{\mathbf{V}} \backslash \mathbf{S} ; \mathrm{Z}|\mathbf{S}, \theta_z)$, which is zero due to the independence $\{\mathrm{X}, \tilde{\mathbf{V}} \backslash \mathbf{S} \}\perp \mathrm{Z} | \mathbf{S}, \theta_z$. We can now map $I(\mathrm{X}, \tilde{\mathbf{V}}, \mathbf{S}; \mathrm{Z}|\mathbf{S}, \theta_z)$ to $I(\mathbf{X};\mathrm{Z}|\tilde{\mathbf{X}})$ from Eq.\,\ref{e21}. The input to the IB algorithm must be at least $\mathbf{X}= \{ \mathrm{X}, \tilde{\mathbf{V}}, \mathbf{S} \}$, and the output for this selection of $\mathbf{X}$, if the algorithm performs correctly, would be $\tilde{\mathbf{X}} = \{\mathbf{S}, \theta_z\}$ . The same logic to select $\mathbf{X}$ holds in general. The input must at least be $\mathbf{X} = \{ \mathrm{X}, \mathbf{S}, \alpha \}$. That is, the input must include the variable $\mathrm{X}$ for which the sufficient set of statistics has to be identified, the collection $\alpha$ of all the other arguments of the statistics, and the required conditioning set $\mathbf{S}$. If the algorithm performs correctly, the output for this $\mathbf{X}$ will be $\tilde{\mathbf{X}} = \mathbf{S}_{\Psi_{x,z}}$ or $\tilde{\mathbf{X}} = \mathbf{S}_{\Psi_{x,z}} \backslash \mathrm{Y}$, for $\mathrm{X} \perp \mathrm{Z}| \mathbf{S}_{\Psi_{x,z}}$ and $\mathrm{X} \perp \mathrm{Z}| \mathbf{S}_{\Psi_{x,z}} \backslash \mathrm{Y}$, respectively. Accordingly, what we will call the IB sufficient statistic $\theta_{IB} \equiv \tilde{\mathbf{X}}$ does not correspond only to the sufficient set of statistics $\Psi_{x,z}(\alpha)$, but to the whole conditioning set required to create the new conditional independence. In the case that auxiliary statistics are part of the sufficient set, the input $\mathbf{X}$ must also include their arguments (see Appendix B for details). Note that the fact that the input $\mathbf{X} = \{ \mathrm{X}, \mathbf{S}, \alpha \}$ jointly includes without distinction the arguments of all statistics \--and potentially of auxiliary statistics\-- as well as the conditioning set indicates that the IB algorithm estimates $\theta_{IB}$ in the space of all underlying sufficient statistics, without requiring an assumption about how many statistics exist, a distinction of which are auxiliary, or of which arguments of the statistics also belong to the conditioning set $\mathbf{S}$. From now on we will use $\theta_{IB}$ to refer to the correct output that the IB algorithm should return given a certain system and input $\mathbf{X}$, and we will use $\hat{\theta}_{IB}$ to refer to the actual output from the algorithm, which is an estimate of the underlying $\theta_{IB}$. Given the relation between $I(\mathrm{X}; \mathrm{Z}| \mathbf{S}_{\Psi_{x,z}})$ and $I(\mathrm{X}; \mathrm{Z}| \theta_{IB})$ described above, the rules R.c-ss and R.nc-ss can be implemented as follows: \vspace*{1mm} \noindent \textbf{Implementation of rule $\mathbf{R.c-ss}$ with the IB method}: \emph{Consider variables $\mathrm{X}$, $\mathrm{Y}$, $\mathrm{Z}$, all nonseparable. For $\mathrm{Z}$ the target variable, find an input $\mathbf{X}$ for the IB method with $\mathrm{X} \in \mathbf{X}$ nonoverlapping with $\{\mathrm{Z}, \mathrm{Y} \}$ such that, given the output $\hat{\theta}_{IB}$, $\mathrm{X} \notperp \mathrm{Y}| \hat{\theta}_{IB}$, $\mathrm{Y} \notperp \mathrm{Z}| \hat{\theta}_{IB}$, and $\mathrm{X} \perp \mathrm{Z}| \hat{\theta}_{IB}$, then orient $\mathrm{X} *\--*\mathrm{Y} *\--* \mathrm{Z}$ as $\mathrm{X} *\rightarrow \mathrm{Y} \leftarrow* \mathrm{Z}$.} \vspace*{1mm} \noindent \textbf{Implementation of rule $\mathbf{R.nc-ss}$ with the IB method}: \emph{Consider variables $\mathrm{X}$, $\mathrm{Y}$, $\mathrm{Z}$, all nonseparable. For $\mathrm{Z}$ the target variable, find an input $\mathbf{X}$ for the IB method with $\mathrm{X} \in \mathbf{X}$ and $\mathrm{Y} \in \mathbf{X}$ nonoverlapping with $\mathrm{Z}$ such that, given the output $\hat{\theta}_{IB}$, $\mathrm{X} \perp \mathrm{Z}| \hat{\theta}_{IB}$. Check that, for $\mathrm{Z}$ the target variable, using as input $\mathbf{X} \backslash \mathrm{Y}$ the output $\hat{\theta}'_{IB}$ leads to $\mathrm{X} \notperp \mathrm{Z}| \hat{\theta}'_{IB}$ or to $H(\mathrm{X}|\hat{\theta}'_{IB})=0$ and that, for $\mathrm{Y}$ the target variable, for all inputs $\mathbf{X}' \subseteq \mathbf{X} \backslash \mathrm{Y}$ the output $\hat{\theta}''_{IB}$ leads to $\mathrm{X} \notperp \mathrm{Y}| \hat{\theta}''_{IB}$ or $H(\mathrm{X}|\hat{\theta}''_{IB})=0$. Then mark $\mathrm{X} *\--*\mathrm{Y} *\--* \mathrm{Z}$ as $\mathrm{X} *-\underline{*\mathrm{Y}*}-* \mathrm{Z}$.} \vspace*{1mm} For R.c-ss, the conditions $\mathrm{X} \notperp \mathrm{Y}| \hat{\theta}_{IB}$, $\mathrm{Y} \notperp \mathrm{Z}| \hat{\theta}_{IB}$, and $\mathrm{X} \perp \mathrm{Z}| \hat{\theta}_{IB}$ correspond to $\mathrm{X} \notperp \mathrm{Y} |\mathbf{S}_{\Psi_{x,z}}$, $\mathrm{Y} \notperp \mathrm{Z} |\mathbf{S}_{\Psi_{x,z}}$, and $\mathrm{X} \perp \mathrm{Z} |\mathbf{S}_{\Psi_{x,z}}$. The requirement in R.c-ss that $\mathbf{S}$ is nonoverlapping with $\{ \mathrm{Y}, \mathrm{Z}\}$ and $\mathrm{Y} \notin \bigcup \alpha$, is implemented by excluding $\{\mathrm{Y}, \mathrm{Z}\}$ from the input $\mathbf{X}$. Since $\mathrm{X} \in \mathbf{X}$, it is not excluded a priori that $\mathrm{X} \in \mathbf{S}$ as required in R.c-ss, but in that case the entropy $H(\mathrm{X} | \hat{\theta}_{IB})=0$ would invalidate $\hat{\theta}_{IB}$ as a useful statistic. For R.nc-ss, the conditions $\mathrm{X} \notperp \mathrm{Z}| \hat{\theta}'_{IB}$ or $H(\mathrm{X}|\hat{\theta}'_{IB})=0$ and $\mathrm{X} \perp \mathrm{Z}| \hat{\theta}_{IB}$ implement $\mathrm{X} \notperp \mathrm{Z} |\mathbf{S}_{\Psi_{x,z}} \backslash \{\mathrm{Y}, \mathbf{\Psi}^{(y)}_{x,z}(\alpha)\}$ and at least $\mathrm{X} \perp \mathrm{Z} |\mathbf{S}_{\Psi_{x,z}}$ or $\mathrm{X} \perp \mathrm{Z} |\mathbf{S}_{\Psi_{x,z}} \backslash \mathrm{Y}$. The condition $H(\mathrm{X}|\hat{\theta}'_{IB})=0$ covers the case in which $\hat{\theta}'_{IB}$ includes $\mathrm{X}$ itself and $\mathrm{X} \notperp \mathrm{Z}| \hat{\theta}'_{IB}$ cannot be evaluated. The IB algorithm will include $\mathrm{Y}$ in $\hat{\theta}_{IB}$ only if $\mathrm{Z} \notperp \mathrm{Y}| \mathbf{S}_{\Psi_{x,z}} \backslash \mathrm{Y}$. In more detail, rule R.nc-ss checks that it is necessary the addition of $\{\mathrm{Y}, \mathbf{\Psi}^{(y)}_{x,z}(\alpha)\}$ or $\mathbf{\Psi}^{(y)}_{x,z}(\alpha)$ to the conditioning set to separate $\mathrm{X}$ and $\mathrm{Z}$. A direct implementation of the rule would need some procedure to identify the structure of $\hat{\theta}_{IB}$ corresponding to $\mathbf{\Psi}^{(y)}_{x,z}(\alpha)$. However, this is avoided by combining $\hat{\theta}_{IB}$ from input $\mathbf{X}$ and $\hat{\theta}_{IB}'$ from input $\mathbf{X} \backslash \mathrm{Y}$, since not including $\mathrm{Y}$ in the input excludes both that $\mathrm{Y}$ can be part of $\hat{\theta}'_{IB}$ and that the IB method can identify any statistic that has $\mathrm{Y}$ as an argument. Similarly, for the target variable being $\mathrm{Y}$, using all inputs $\mathbf{X}' \subseteq \mathbf{X} \backslash \mathrm{Y}$ allows guaranteeing $\mathrm{X} \notperp \mathrm{Y}|\mathbf{S}'$ $\forall \mathbf{S}' \subseteq \mathbf{S}_{\Psi_{x,z}} \backslash \{\mathrm{Y}, \mathbf{\Psi}^{(y)}_{x,z}(\alpha)\}$ from $\mathrm{X} \notperp \mathrm{Y}| \hat{\theta}''_{IB}$ or $H(\mathrm{X}|\hat{\theta}''_{IB})=0$ $\forall \hat{\theta}''_{IB}$. Furthermore, since the IB method is applied with $\mathrm{Z}$ and not $\mathrm{X}$ as the target variable, $\hat{\theta}_{IB}$ cannot comprise any sufficient statistic with $\mathrm{Z}$ as an argument that could lead to $\mathrm{Y} \perp \mathrm{Z} | \mathbf{S}'$ for some $\mathbf{S}' \subseteq \mathbf{S}_{\Psi_{x,z}} \backslash \{\mathrm{Y}, \mathbf{\Psi}^{(y)}_{x,z}(\alpha)\}$. Besides the implementation of the rules, we continue discussing the implementation of the IB algorithm. Apart from $\mathbf{X}$, the other input critical to the IB algorithm is parameter $\beta$. In common applications of the IB method, $\beta$ may be selected such that some information about $\mathrm{Z}$ is lost, if this allows a desirable higher compression. This is not the case here; $\tilde{\mathbf{X}}$ has to preserve all the information to create an additional independence $I(\mathbf{X};\mathrm{Z}|\tilde{\mathbf{X}})=0$. Consider a single sufficient statistic, such that $\mathrm{Z} \perp \mathrm{X} | \mathbf{S}, \theta_z(\mathrm{X}; \tilde{\mathbf{V}})$. If the distribution $p(\mathrm{Z}, \mathrm{X}, \tilde{\mathbf{V}}, \mathbf{S})$ was estimated perfectly, a value $\beta \rightarrow \infty$ could be selected. This is because if it exists a $p(\tilde{\mathbf{X}} | \mathbf{X})$ such that $I(\mathbf{X};\mathrm{Z}|\tilde{\mathbf{X}})=0$, the minimization in Eq.\,\ref{e21} reduces to finding $\tilde{\mathbf{X}}$ such that apart from producing $I(\mathbf{X};\mathrm{Z}|\tilde{\mathbf{X}})=0$ also minimizes $I(\tilde{\mathbf{X}};\mathbf{X})$. However, with an imperfect estimation from finite data, $\beta \rightarrow \infty$ may enforce the preservation of information resulting only from differences between probability values due to the imperfect estimation, leading to a useless output $\tilde{\mathbf{X}} = \mathbf{X}$. In practice, high values of $\beta$ should be selected to prioritize information preservation over compression, but not so high that sampling fluctuations dominate the determination of $\tilde{\mathbf{X}}$. The scale to assess the magnitude of $\beta$ values is determined by the ratio $I(\mathbf{X};\mathrm{Z})/H(\mathbf{X})$, since the entropy $H(\mathbf{X})$ is the maximum possible value of $I(\tilde{\mathbf{X}};\mathbf{X})$ and $I(\mathbf{X};\mathrm{Z})$ the maximum possible value of $I(\tilde{\mathbf{X}};\mathrm{Z})$. Defining $\beta' \equiv \beta I(\mathbf{X};\mathrm{Z})/H(\mathbf{X})$, the function to be minimized to select $p(\tilde{\mathbf{X}}|\mathbf{X})$ can be reexpressed as: \small \begin{equation} \label{e22} \begin{split} p(\tilde{\mathbf{X}}|\mathbf{X}) & \equiv \mathrm{argmin}\ I(\tilde{\mathbf{X}};\mathbf{X})-\beta I(\tilde{\mathbf{X}};\mathrm{Z}) \\ & = \mathrm{argmin}\ I(\tilde{\mathbf{X}};\mathbf{X})-\beta' \frac{H(\mathbf{X})}{I(\mathbf{X};\mathrm{Z})} I(\tilde{\mathbf{X}};\mathrm{Z}) = \mathrm{argmin}\ H(\mathbf{X}) \left [ \frac{I(\tilde{\mathbf{X}};\mathbf{X})}{H(\mathbf{X})} - \beta' \frac{I(\tilde{\mathbf{X}};\mathrm{Z})}{I(\mathbf{X};\mathrm{Z})} \right ]. \end{split} \end{equation} \normalsize Because $I(\tilde{\mathbf{X}};\mathbf{X})/H(\mathbf{X}) \leq 1$ and $I(\tilde{\mathbf{X}};\mathrm{Z})/ I(\mathbf{X};\mathrm{Z}) \leq 1$, values $\beta' \gg 1$ enforce information preservation. As discussed in Section \ref{ss33} below, we will combine results from a whole set of high $\beta'$ values in order to select the sufficient statistics. Furthermore, the IB algorithm also requires as input a maximal cardinality $\max |\hat{\theta}_{IB}|$ for the output variable $\hat{\theta}_{IB} \equiv \tilde{\mathbf{X}}$, needed to initialize the projection $p(\tilde{\mathbf{X}}|\mathbf{X})$. In our procedure we also do not preselect a fixed maximal cardinality, but instead combine the results of the IB algorithm across different maximal cardinalities to identify candidate sufficient statistics $\hat{\theta}_{IB}$. Selection criteria to select these candidate statistics are detailed in Section \ref{ss33} below. More technical details of the implementation of the IB algorithm are provided in Appendix G. The IB algorithm returns a compressed representation $\tilde{\mathbf{X}}$, determined by the optimized conditional distribution $p(\tilde{\mathbf{X}}|\mathbf{X})$. In the presence of a single underlying sufficient statistic, the mapping $p(\tilde{\mathbf{X}}|\mathbf{X})$ correctly infers the form of the statistic if it approximates the deterministic relation $\theta_z = g(\mathrm{X}, \tilde{\mathbf{V}})$ so that for each value $\mathbf{X}= \mathbf{x}$ there is a value $\tilde{\mathbf{X}} = \tilde{\mathbf{x}}_0$ such that $p(\tilde{\mathbf{X}}= \tilde{\mathbf{x}}_0 |\mathbf{X}= \mathbf{x}) \simeq 1$, while $p(\tilde{\mathbf{X}}\neq \tilde{\mathbf{x}}_0 |\mathbf{X}= \mathbf{x}) \simeq 0$. Accordingly, a candidate sufficient statistic is constructed setting $p(\tilde{\mathbf{X}}= \tilde{\mathbf{x}}_0|\mathbf{X})=1 $ for $\tilde{\mathbf{x}}_0 = \mathrm{argmax}_j\ p(\tilde{\mathbf{X}}= \tilde{\mathbf{x}}_j|\mathbf{X})$ and $p(\tilde{\mathbf{X}}\neq \tilde{\mathbf{x}}_0|\mathbf{X})=0$ otherwise. This modified distribution defines the potential sufficient statistic $\hat{\theta}_{IB}$. The same procedure works with a sufficient set comprising several statistics to define $\hat{\theta}_{IB}$ in the joint space of those statistics. \subsection{Selection of sufficient statistics identified with the information bottleneck method} \label{ss33} As described above, a candidate sufficient statistic $\hat{\theta}_{IB}$ is obtained from the IB algorithm for each selection of the inputs $\mathbf{X}$, $\beta$, and $\max |\hat{\theta}_{IB}|$. We now describe a procedure to combine $\hat{\theta}_{IB}$ outputs in order to select the sufficient statistic used with rules R.c-ss and R.nc-ss. We call the proposed procedure the Information Bottleneck Sufficient Statistics Inference method, the IBSSI method. The core of the IBSSI method is a procedure to select sufficient statistics for fixed $\mathbf{X}$ and $\beta$ (see algorithm \ref{alg1}). For a fixed $\mathbf{X}$, the maximal cardinality $\max |\hat{\theta}_{IB}|$ has to be selected from the range $\{2,..., |\mathbf{X}|\}$, where $|\mathbf{X}|$ is the cardinality of the input. Algorithm \ref{alg1} starts applying the IB algorithm for $\max |\hat{\theta}_{IB}|= |\mathbf{X}|$, that is, the initial maximal dimensionality of $\tilde{\mathbf{X}}$ for the mapping $p(\tilde{\mathbf{X}}| \mathbf{X})$ is equal to $|\mathbf{X}|$. If the cardinality of the output $\hat{\theta}_{IB}$ is lower than $|\mathbf{X}|$, the algorithm iterates the IB algorithm using $\max |\hat{\theta}_{IB}|= |\mathbf{X}|-k$ for the $k$-th iteration, until one of the following things happens. First, if at iteration $k$ the output is such that $|\hat{\theta}_{IB}^{(k)}| > |\hat{\theta}_{IB}^{(k-1)}|$, the algorithm does not return any sufficient statistic. If the iterations stop because the bound $\max |\hat{\theta}_{IB}|=2$ is reached, or because $|\hat{\theta}_{IB}^{(k)}| < |\hat{\theta}_{IB}^{(k-1)}|$, it checks that the statistic retrieved in the last two iterations of equal cardinality was the same. Lines $12-14$ serve to ensure that the comparison in line $15$ is applied to the right iterations. The equality of the inferred $\hat{\theta}_{IB}$ in adjacent iterations ensures some degree of robustness of the sufficient statistics retrieved, and could be made more demanding asking not only that $\hat{\theta}_{IB}^{(k)} = \hat{\theta}_{IB}^{(k-1)}$ (line $15$), but an equality for a wider range of $\max |\hat{\theta}_{IB}|$ values. On the other hand, the requirement that already when using $\max |\hat{\theta}_{IB}|= |\mathbf{X}|$ a sufficient statistic of lower cardinality is found (line $4$) could be removed, as long as it is found for a lower value of $\max |\hat{\theta}_{IB}|$. \begin{algorithm}[H] \caption{Selection of a sufficient statistic $\hat{\theta}_{IB}$ for $\mathrm{X}$ with respect to $\mathrm{Z}$ for fixed values of $\mathbf{X}$ and $\beta$.} \label{alg1} \begin{algorithmic}[1] \renewcommand{\algorithmicrequire}{\textbf{Input:}} \renewcommand{\algorithmicensure}{\textbf{Output:}} \REQUIRE $\mathrm{X}$, $\mathrm{Z}$, $\mathbf{X}$, $\beta$, $a_{I}$, $a_{H_\mathrm{X}}$, $a_{H_\mathrm{Z}}$ \ENSURE $\hat{\theta}_{IB}$ \STATE $\hat{\theta}_{IB}$ empty \STATE $\max |\hat{\theta}_{IB}|\leftarrow |\mathbf{X}|$ \STATE $\hat{\theta}_{IB}^{(0)} \leftarrow IB(\mathrm{Z},\mathbf{X}, \beta, \max |\hat{\theta}_{IB}|)$ \IF{$|\hat{\theta}_{IB}^{(0)}|< |\mathbf{X}|$} \STATE $k \leftarrow 0$ \REPEAT \STATE $k \leftarrow k +1$ \STATE $\max |\hat{\theta}_{IB}|\leftarrow |\mathbf{X}| -k$ \STATE $\hat{\theta}_{IB}^{(k)} \leftarrow IB(\mathrm{Z},\mathbf{X}, \beta, \max |\hat{\theta}_{IB}|)$ \UNTIL{$\max |\hat{\theta}_{IB}| = 2\ \ \mathrm{OR} \ \ |\hat{\theta}_{IB}^{(k)}| \neq |\hat{\theta}_{IB}^{(k-1)}| $} \IF{$|\hat{\theta}_{IB}^{(k)}| \leq |\hat{\theta}_{IB}^{(k-1)}|$} \IF{$|\hat{\theta}_{IB}^{(k)}| < |\hat{\theta}_{IB}^{(k-1)}|$} \STATE $k \leftarrow k-1$ \ENDIF \IF{$\hat{\theta}_{IB}^{(k)} = \hat{\theta}_{IB}^{(k-1)}$} \STATE $c_\mathrm{X} \leftarrow H(\mathrm{X}|\hat{\theta}_{IB}^{(k)}) > a_{H_\mathrm{X}} H(\mathrm{X})$ \STATE $c_\mathrm{Z} \leftarrow H(\mathrm{Z}|\hat{\theta}_{IB}^{(k)}) > a_{H_\mathrm{Z}} H(\mathrm{Z})$ \STATE $c_I \leftarrow I(\mathrm{X}; \mathrm{Z}| \hat{\theta}_{IB}^{(k)}) < a_{I} I(\mathrm{X}; \mathrm{Z})$ \IF{$ c_I = c_\mathrm{X} = c_\mathrm{Z} = \mathrm{true} $} \STATE $\hat{\theta}_{IB} \leftarrow \hat{\theta}_{IB}^{(k)}$ \ENDIF \ENDIF \ENDIF \ENDIF \end{algorithmic} \end{algorithm} Finally, lines $16-18$ evaluate the Selection Criteria that make $\hat{\theta}_{IB}$ useful to apply the rules of causal learning. First, $\hat{\theta}_{IB}$ cannot be such that $H(\mathrm{X}|\hat{\theta}_{IB})=0$ or $H(\mathrm{Z}|\hat{\theta}_{IB})=0$, since this would prevent from evaluating any conditional dependence or independence as required in the rules. Because $H(\mathrm{X})$ is the maximum value that $H(\mathrm{X}|\hat{\theta}_{IB})$ can have, we require $H(\mathrm{X}|\hat{\theta}_{IB})> a_{H_\mathrm{X}} H(\mathrm{X})$, and analogously $H(\mathrm{Z}|\hat{\theta}_{IB})> a_{H_\mathrm{Z}} H(\mathrm{Z})$, where $a_{H_\mathrm{X}}$ and $a_{H_\mathrm{Z}}$ are factors determining the percentage of entropy left after conditioning. We present our results for $a_{H_\mathrm{X}} = a_{H_\mathrm{Z}} = 0.1$, and these results are robust as long as the bounds are not too close to zero. Requiring $H(\mathrm{X}|\hat{\theta}_{IB})>0$ discards that $\tilde{\mathbf{X}} = \mathbf{X}$, as may happen if $\beta$ is too high, as discussed above. Second, the condition that defines a sufficient statistic is that $I(\mathrm{X}; \mathrm{Z}| \theta_{IB})=0$, which as discussed above corresponds to $I(\mathrm{X}; \mathrm{Z}| \mathbf{S}_{\Psi_{x,z}})=0$. To assess the creation of a conditional independence we check that conditioning on $\hat{\theta}_{IB}$ reduces the mutual information $I(\mathrm{X}; \mathrm{Z})$ below a small percentage of its value. In particular, we chose $a_{I} = 0.025$. This value should be small enough to discard candidates of $\hat{\theta}_{IB}$ that do not create an independence, but cannot be too small, given that information theoretic quantities have an intrinsic positive estimation bias, which increases for conditional mutual informations due to the higher dimensionality \citep{Panzeri2007}. The selection criteria of lines $16-18$ are to be evaluated in a testing set different from the training data set used to infer $\hat{\theta}_{IB}$ with the IB algorithm, in order to avoid selecting sufficient statistics due to overfitting. Since these selection criteria constitute a step previous to the evaluation of all conditional dependencies and independencies involved in the rules, further tests of significance can be applied subsequently. The testing of conditional independencies is not specific to our new rules, but an issue common to standard rules, and it is not our objective here to optimize the tests. Accordingly, the criterion of line $18$ based on mutual information stands for any analogous test of a conditional independence created by $\hat{\theta}_{IB}$. In a subsequent step, we need to combine the sufficient statistics $\hat{\theta}_{IB}$ obtained for different inputs $\mathbf{X}$ and $\beta$. The IBSSI method proceeds selecting a set of high $\beta$ values and accepting any statistic found for any $\beta$ value within the set. As discussed above, given $\beta = \beta' H(\mathbf{X})/ I(\mathbf{X};\mathrm{Z})$, the high $\beta$ values are determined by $\beta' \gg 1$. The selection criteria imposed in algorithm \ref{alg1} make the procedure robust to the $\beta'$ range. If $\beta'$ is too low, allowing for an excess of compression, the condition $c_I = \mathrm{true}$ (line 18 in the algorithm) will not be fulfilled. Similarly, if $\beta'$ is too high and $\tilde{{\mathbf{X}}} = \mathbf{X}$ is retrieved, the condition $c_\mathrm{X} = \mathrm{true}$ (line 16) will not be fulfilled. Nonetheless, because the results depend on the estimation of the information theoretic quantities and the particular selection of the thresholds $a_{I}$ and $a_{H_\mathrm{X}}$, the selection of lower or higher $\beta'$ values determines a tradeoff between sensitivity and specificity identifying sufficient statistics, as we will illustrate comparing performance results for two sets $\beta' \in \{25, 50 , 75, 100\}$ and $\beta' \in \{50 , 75, 100\}$. Instead of accepting any statistic found for any $\beta'$ value, a more conservative approach would be to check that the identity of $\hat{\theta}_{IB}$ is the same across a certain range of $\beta'$ values, analogously to how algorithm \ref{alg1} checks that the same $\hat{\theta}_{IB}$ is inferred with different $\max |\hat{\theta}_{IB}|$ values (line 15). Again, the preferred implementation depends on the tradeoff between sensitivity and specificity, and the same principles can be applied adjusting for various robustness requirements. As a last step, a criterion is needed to select the inputs $\mathbf{X}$. As explained in Section 4.1, apart from variable $\mathrm{X}$, for which the existence of a sufficient set of statistics with respect to $\mathrm{Z}$ is hypothesized, $\mathbf{X}$ should comprise the variables hypothesized to be the other arguments of the sufficient statistics, and the variables hypothesized to belong to $\mathbf{S}$, a required conditioning set. In this work we will analyze examples involving only few variables, and adopt the simplest strategy of starting with the lowest possible set $\mathbf{X}$ and consider larger sets if a valid sufficient set of statistics is not found. In general, the selection of a conditioning set $\mathbf{S}$ is an issue common to the standard algorithms, and strategies to select it have been studied before. The FCI algorithm \citep{Spirtes00} has a procedure to establish the order in which different conditioning sets are tested and subsequent refinements to make the application of the rules order-independent have been proposed \citep{Colombo14}. The selection of candidate variables $\mathrm{X}$, $\mathrm{Z}$, and candidate arguments for the statistics can be informed by the partially oriented graphs obtained as the output of the standard structure learning algorithms. Note that the identification of a sufficient statistic may lead to the orientation of more edges not only because of the immediate application of rules R.c-ss and R.nc-ss. If some new edges have been oriented with R.c-ss and R.nc-ss, this new information may enable the standard rules to be applied for some instances for which they could not before. This naturally leads to conceive an iterative procedure in which at each step where to seek for candidate sufficient statistics is determined by the available causal information from previous iterations. The implementation of this iterative identification of sufficient statistics combined with a standard structure learning algorithm is out of the scope of this work. In Appendix C we provide a detailed description of the CI algorithm of \cite{Spirtes00} augmented with rules based on sufficient statistics, but under the assumption that the statistics have been already previously inferred, instead of considering an iterative identification of the statistics and application of the orientation rules. \section{Examples of identification of sufficient statistics} \label{ss4} We now study examples for which sufficient statistics are inferred with the IBSSI method. First, we analyze simulated data to study performance across different configurations of systems with common sufficient sets of statistics. For this purpose, we simulated systems in which the conditional distribution of the variables in whose functional equation the sufficient statistics are embodied has the form of Generalised Linear Models (GLMs) \citep{Nelder72}, which are widely applied in social and biological sciences. Second, we also study performance across data sets sampled from fixed configurations. For this purpose, we generated data from a concrete set of functional equations previously shown to accurately model a biological signal transduction network \citep{Li06}. The equations have the form of Boolean regulatory rules, which are widely applied to model regulatory and signaling networks in systems biology \citep{Wang12, Abou16, Chen18} and systems pharmacology \citep{Bloomingdale18}. The system we study has also previously been included \citep{Jenkins08} in the workbench designed for the Causation and Prediction Challenge of \cite{Guyon08} (http://www.causality.inf.ethz.ch). Further examples are studied in Appendix E. \subsection{Characterization of the IBSSI method with simulated data} \label{ss42} We here study the performance identifying sufficient statistics across configurations of systems with the causal structures of Figure \ref{f02}. For the sake of space, we only represent the graphs $G^+_{\theta}$ already incorporating sufficient statistics. In Figure \ref{f02}A there is a sufficient statistic $\theta$ for $\mathrm{X}$ with respect to $\mathrm{Z}$, and in Figure \ref{f02}B there is also an auxiliary statistic $\gamma$, such that in both cases the new conditional independence obtained from the statistics would allow applying rule R.c-ss to infer a collider $\mathrm{X} * \rightarrow \mathrm{Y} \leftarrow * \mathrm{Z}$. In Figure \ref{f02}C the statistic allows applying rule R.nc-ss to infer that $\mathrm{Y}$ is a noncollider. In all these three cases the nonseparability of $\mathrm{X}$ and $\mathrm{Z}$ prevents the application of rules R.c and R.nc. Finally, no statistic exists in Figure \ref{f02}D, and hence the IB algorithm should not return a valid $\hat{\theta}_{IB}$. \begin{figure*}[t] \begin{center} \scalebox{0.53}{\includegraphics*{F2.pdf}} \end{center} \caption{Concrete causal structures studied to assess the performance of the IBSSI method finding sufficient statistics useful for structure learning. \textbf{A}) Structure with a single sufficient statistic $\theta$ that allows applying rule R.c-ss to infer that $\mathrm{Y}$ is a collider. \textbf{B}) Structure with a statistic $\theta$ and an auxiliary statistic $\gamma$ that allow applying rule R.c-ss to infer that $\mathrm{Y}$ is a collider. \textbf{C}) Structure with a sufficient statistic $\theta$ that allows applying rule R.nc-ss to infer that $\mathrm{Y}$ is a noncollider. \textbf{D}) Structure with no sufficient statistics.} \label{f02} \end{figure*} We will focus on evaluating the performance in the identification of sufficient sets of statistics, and not on the full application of rules R.c-ss and R.nc-ss. We chose this strategy because the identification of a sufficient set of statistics already involves verifying the creation of a new conditional independence, which is the key distinctive component of the new rules. Furthermore, except for the system of Figure \ref{f02}C for which rule R.nc-ss applies, the application of the IBSSI method to these examples does not require specifying a functional equation for $\mathrm{Y}$, so that we can segregate the statistics' identification analysis from the \--contingent\-- selection of a functional equation for $\mathrm{Y}$. In more detail, for the systems of Figure \ref{f02}A-B, the identification of the correct $\theta_{IB}$ involves the verification of $\mathrm{X} \perp \mathrm{Z}| \hat{\theta}_{IB}$ (line 18 of algorithm 1), as required in the implementation of R.c-ss with the IB method (Section \ref{ss32}). For these two causal structures, the presence of a sufficient set of statistics only depends on the form of the functional equation of $\mathrm{Z}$, and the performance identifying the statistics will depend only on the properties of $p(\mathrm{Z},\mathrm{X},\mathrm{V}_1,\mathrm{V}_2)$, not on the properties of the functional equation of $\mathrm{Y}$ and of $p(\mathrm{Y}| \mathrm{X},\mathrm{Z})$. On the other hand, a full implementation of rule R.c-ss further requires using the inferred $\hat{\theta}_{IB}$ to check that $\mathrm{X} \notperp \mathrm{Y}| \hat{\theta}_{IB}$ and $\mathrm{Y} \notperp \mathrm{Z}| \hat{\theta}_{IB}$. The actual fulfillment of these dependencies, as well as the performance verifying them, would depend on the properties of the specific functional equation of $\mathrm{Y}$ and $p(\mathrm{Y}| \mathrm{X},\mathrm{Z})$ studied. For example, if we chose a system in which the link $\mathrm{X} \rightarrow \mathrm{Y}$ is too weak, the dependence $\mathrm{X} \notperp \mathrm{Y}| \hat{\theta}_{IB}$ may not be detected and the application of the rule would fail. However, we want to isolate the evaluation of the performance of the IBSSI method from these additional factors that affect the applicability of the new rules but that are not distinctive of these new rules. Similarly, in the case of Figure \ref{f02}D, the selection of a particular form of the functional equation of $\mathrm{Y}$ is not required to examine whether the IBSSI method avoids false positives when an underlying sufficient set of statistics does not exist. Only in the case of Figure \ref{f02}C we will explicitly model variable $\mathrm{Y}$, since it is involved in the detection of the statistic with the independence $\mathrm{Z} \perp \mathrm{X}| \theta, \mathrm{Y}$. In more detail, in this section for each of the causal structures in Figure \ref{f02} we study configurations generated from the same type of systems, with fixed generative mechanisms, and a concrete form of the corresponding sufficient statistics. Additional examples in Appendix E comprise systems generated with alternative mechanisms or with other forms of the sufficient statistics. In particular, here we study systems in which $\mathrm{Z}$ depends on its parents through a binomial GLM. $\mathrm{Z}$ is generated from a binomial distribution $B(n,p_\mathrm{z})$, where $n$ is the number of trials and $p_\mathrm{z}$ the probability of obtaining $\mathrm{Z} = 1$ in a trial, which is determined with a logit link function $p_\mathrm{z} = 1/(1+\mathrm{exp}(-h(\mathbf{Pa}_z)))$. For the systems corresponding to Figure \ref{f02}A-B, we constructed functions $h(\mathbf{Pa}_z)$ with the following form: \begin{subequations} \label{e1} \begin{align} h &= a_0+ a_1 \mathrm{V}_2 + a_2(\mathrm{X}+\mathrm{V}_1) + a_3 (\mathrm{X}+\mathrm{V}_1)^2 + a_4(\mathrm{X}+\mathrm{V}_1)\mathrm{V}_2 + a_5(\mathrm{X}+\mathrm{V}_1)^2 \mathrm{V}_2 \label{e1a} \\ h &= a_0+ a_1(\mathrm{V}_1+\mathrm{V}_2) + a_2(\mathrm{V}_1+\mathrm{V}_2)^2 + a_3(\mathrm{X}+\mathrm{V}_1) + a_4(\mathrm{X}+\mathrm{V}_1)(\mathrm{V}_1+\mathrm{V}_2) \label{e1b}\\ &\ \ \ + a_5(\mathrm{X}+\mathrm{V}_1)^2 + a_6(\mathrm{X}+\mathrm{V}_1)^2(\mathrm{V}_1+\mathrm{V}_2)^2 \notag, \end{align} \end{subequations} where $\mathrm{X}, \mathrm{V}_1$, and $\mathrm{V}_2$ are independent binary variables with values $0,1$. In Eq.\,\ref{e1a}, $\theta = \mathrm{X}+\mathrm{V}_1$ is a sufficient statistic for $\mathrm{X}$ (Fig.\,\ref{f02}A). In Eq.\,\ref{e1b}, $\theta = \mathrm{X}+\mathrm{V}_1$ is again a statistic for $\mathrm{X}$ and furthermore $\gamma = \mathrm{V}_1+\mathrm{V}_2$ is an auxiliary statistic (Fig.\,\ref{f02}B). For the systems corresponding to Figure \ref{f02}C-D, we constructed functions $h(\mathbf{Pa}_z)$ with the following form: \begin{subequations} \label{e2} \begin{align} h &= a_0+ a_1 \mathrm{Y} + a_2(\mathrm{X}+\mathrm{V}_1) + a_3 (\mathrm{X}+\mathrm{V}_1)^2 + a_4(\mathrm{X}+\mathrm{V}_1)\mathrm{Y} + a_5(\mathrm{X}+\mathrm{V}_1)^2 \mathrm{Y} \label{e2a}\\ h &= a_0+ a_1 \mathrm{V}_1 + a_2 \mathrm{V}_2 + a_3 \mathrm{X} + a_4 \mathrm{X} \mathrm{V}_1 + a_5 \mathrm{X} \mathrm{V}_2 + a_6 \mathrm{V}_1 \mathrm{V}_2, \label{e2b} \end{align} \end{subequations} where all variables are binary with values $0, 1$. In Fig.\,\ref{f02}C, the link $\mathrm{X} \rightarrow \mathrm{Y}$ was modeled by $p(\mathrm{Y} = 1| \mathrm{X} = \mathrm{x}) = 0.3 + 0.4 \mathrm{x}$ and $\theta = \mathrm{X}+\mathrm{V}_1$ is a sufficient statistic for $\mathrm{X}$. Oppositely, Eq.\,\ref{e2b} does not contain any sufficient statistic (Fig.\,\ref{f02}D). \begin{figure*}[t] \begin{center} \scalebox{0.42}{\includegraphics*{Fig1IBd.pdf}} \end{center} \caption{Identification of sufficient statistics with the Information Bottleneck method for the systems of Figure \ref{f02}. \textbf{A}) Results for configurations generated following Eq.\,\ref{e1a}. \textbf{B}-\textbf{D}) Same as A) for systems generated from Eqs.\,\ref{e1b}, \ref{e2a}, and \ref{e2b}. First column shows the average cardinality of the estimated $\hat{\theta}_{IB}$ as a function of the input maximal cardinality $\max |\hat{\theta}_{IB}|$ when the input to the IB algorithm is $\mathbf{X} = \{ \mathrm{X}, \mathrm{V}_1\}$. Second column shows the average cardinality when the input is $\mathbf{X} = \mathbf{Pa}_z$, which corresponds to $\mathbf{X} = \{ \mathrm{X}, \mathrm{V}_1, \mathrm{V}_2\}$ for all systems except $\mathbf{X} = \{ \mathrm{X}, \mathrm{V}_1, \mathrm{Y}\}$ for the system in C). Results are shown for three values of $\beta'$ (Eq.\,\ref{e22}), increasingly enforcing information preservation for higher $\beta'$. The dashed horizontal line indicates the cardinality of the subjacent sufficient statistic $\theta_{IB}$ when it exists, or the cardinality $|\mathbf{X}|$ if it does not exist. The legend specifies the cardinality $|\theta_{IB}|$ in terms of the specific $\mathbf{S}_{\Psi_{x,z}}$ that results from the input $\mathbf{X}$. The third and fourth columns show the ratio of configurations for which the candidate sufficient statistics retrieved from the IB algorithm fulfill the selection criteria (lines 16-18 in algorithm \ref{alg1}). Here and throughout the results we selected thresholds $H(\mathrm{X}|\hat{\theta}_{IB})/H(\mathrm{X})> 0.1$, $H(\mathrm{Z}|\hat{\theta}_{IB})/H(\mathrm{Z})> 0.1$, and $I(\mathrm{X};\mathrm{Z}|\hat{\theta}_{IB})/I(\mathrm{X};\mathrm{Z})< 0.025$ to select a sufficient statistic.} \label{f2} \end{figure*} For each type of system we generated a set of $1440$ configurations consistent with its causal structure and functional equation. Because we aimed to assess the performance inferring the sufficient statistics characteristic of the systems, we used faithfulness constraints to select the sets of parameters. As discussed in Section \ref{ss2}, beyond the standard faithfulness assumption \citep{Pearl86,Spirtes00,Pearl09} our extended faithfulness assumption further requires that a new conditional independence between observable variables appears by introducing a new variable $\hat{\theta}$ deterministically determined by some observable variables if and only if $\hat{\theta}$ corresponds to an underlying functional sufficient statistic. In Appendix A we discuss in more detail this extended faithfulness assumption. To ensure faithfulness we discarded random instantiations of the coefficients $\mathbf{a}$ if for two events of $\mathbf{Pa}_z$ that following the generative equations of Eqs.\,\ref{e1}-\ref{e2} should correspond to a different value of $p_z$, the difference in $p_z$ was smaller than $0.05$. This ensures that the generated distributions contain all and only the structural sufficient statistics present in the functional equations, and allowed us to evaluate the performance inferring the statistics by comparing the output of the IBSSI algorithm to the known underlying sufficient statistics present in each functional equation. First, we randomly generated $\mathrm{K} = 40$ sets of parameters $\mathbf{a}$ for each type of system. Second, we used $n \in \{4, 8, 16, 64\}$ to simulate configurations with a different signal-to-noise ratio for $\mathrm{Z}$, given that for the binomial distribution the ratio of the mean and the standard deviation is proportional to $\sqrt{n}$. In Eqs.\,\ref{e1a}, \ref{e1b}, and \ref{e2b} we fixed $p(\mathrm{V}_2=1) = 0.5$. We then simulated data for $3 \times 3$ combinations of $p(\mathrm{X}=1)$ and $p(\mathrm{V}_1=1)$ with values $\{ 0.3, 0.5, 0.7\}$, so that overall we generated $40 \times 4 \times 3 \times3 = 1440$ configurations. \subsubsection{Estimation of sufficient statistics with the Information Bottleneck algorithm} \label{ss421} We first study how the output $\hat{\theta}_{IB}$ of the IB method depends on its inputs $\mathbf{X}$, $\beta$, and $\max |\hat{\theta}_{IB}|$ (Figure \ref{f2}). For this purpose we examine how the cardinality $|\hat{\theta}_{IB}|$ depends on these factors, as well as how depends on them the ratio of configurations for which the criteria to assess the validity of an estimated $\hat{\theta}_{IB}$ (lines 16-18 in algorithm \ref{alg1}) are fulfilled. The overall performance of the IBSSI method, which combines outputs of the IB method across inputs parameters, will be studied subsequently. Each row in Figure \ref{f2} studies one type of system from Figure \ref{f02}. Each panel presents the results as a function of $\max |\hat{\theta}_{IB}|$ for three values of $\beta'$. Different columns show the results for $\mathbf{X} = \{ \mathrm{X}, \mathrm{V}_1 \}$ and $\mathbf{X} = \mathbf{Pa}_z$. A sample size $N = 20000$ was used for each the fitting and testing sets. In Figure \ref{f2}A, for the configurations from Eq.\,\ref{e1a}, the statistic $\theta = \mathrm{X}+\mathrm{V}_1$ can be identified with both $\mathbf{X} = \{ \mathrm{X}, \mathrm{V}_1 \}$ and $\mathbf{X} = \{ \mathrm{X}, \mathrm{V}_1 , \mathrm{V}_2\}$. Since $\mathrm{X} \in \{0, 1\}$ and $\mathrm{V}_1 \in \{0, 1\}$, then $\theta \in \{0, 1, 2 \}$ with cardinality $|\theta|=3$. Both $\mathrm{X} =0,\mathrm{V}_1 =1$ and $\mathrm{X} =1,\mathrm{V}_1 =0$ result in $\theta =1$, so that $\mathrm{X}$ is still uncertain after conditioning on $\theta$. With $\mathbf{X} = \{ \mathrm{X}, \mathrm{V}_1\}$, $|\hat{\theta}_{IB}|=|\theta|= 3$ is correctly identified for $\max |\hat{\theta}_{IB}|$ equal $3$ or $4$, when $\beta' = 15$. When using a too high $\beta'= 500$, the algorithm becomes too sensitive to differences in probability values due to the finite sample size, and in most cases $\tilde{\mathbf{X}} = \mathbf{X}$. With $\mathbf{X} = \{ \mathrm{X}, \mathrm{V}_1 , \mathrm{V}_2\}$, since $\mathrm{V}_2$ is not involved in any statistic, the IB algorithm should return $\theta_{IB} = \{ \theta, \mathrm{V}_2\}$, whose cardinality is $|\theta_{IB}| = |\theta| |\mathrm{V}_2|=3 * 2$. Again, the valid $\hat{\theta}_{IB}$ is retrieved if $\beta'$ is not too high. The selection ratio indicates the ratio of configurations for which the selection criteria of lines 16-18 of algorithm 1 are fulfilled. This ratio increases until $\max |\hat{\theta}_{IB}|$ is equal to $|\theta_{IB}|$ and drops for $\beta' = 500$ when $\max |\hat{\theta}_{IB}|> |\theta_{IB}|$, reflecting that the condition on $H(\mathrm{X}|\hat{\theta}_{IB})$ (line 16) is not fulfilled when $\tilde{\mathbf{X}} = \mathbf{X}$. For $\mathbf{X} = \{ \mathrm{X}, \mathrm{V}_1 , \mathrm{V}_2\}$ this drop only happens with $\max |\hat{\theta}_{IB}|= 8$ and not $\max |\hat{\theta}_{IB}|= 7$. In the latter case, even if the full statistic with cardinality $|\theta_{IB}| = |\theta| |\mathrm{V}_2|=6$ is not identified, still a valid statistic is selected, which identifies $\theta$ only for one of the two values of $\mathrm{V}_2$ and has $|\hat{\theta}_{IB}| = 7 < |\mathbf{X}|$. Figure \ref{f2}B, shows the results for the system of Eq.\,\ref{e1b}, with a statistic $\theta = \mathrm{X}+\mathrm{V}_1$ and an auxiliary statistic $\gamma = \mathrm{V}_1 + \mathrm{V}_2$. As mentioned in Section \ref{ss32}, the IB algorithm infers a single $\hat{\theta}_{IB}$ in the space of $\theta \otimes \gamma$. As before, $\theta \in \{0, 1, 2\}$, with $\theta =1$ for the events $\mathrm{X} =0,\mathrm{V}_1 =1$ or $\mathrm{X} =1,\mathrm{V}_1 =0$. However, now $I(\mathrm{X};\mathrm{Z}|\theta =1)>0$, because the two events differ in the value of $\mathrm{V}_1$, which also affects $\mathrm{Z}$ through $\gamma$. Only $I(\mathrm{X};\mathrm{Z}|\theta, \gamma)=0$. The underlying cardinality is $|\theta_{IB}|= |\theta \otimes \gamma|= 7$, with only $\mathrm{X}=0, \mathrm{V}_1 =1, \mathrm{V}_2 =0$ and $\mathrm{X}=1, \mathrm{V}_1 =0, \mathrm{V}_2 =1$ leading to the same value of $p_\mathrm{z}$. With an input $\mathbf{X} = \{ \mathrm{X}, \mathrm{V}_1\}$, the IB algorithm correctly indicates that there is no sufficient statistic, returning always a $\hat{\theta}_{IB}$ with cardinality $|\hat{\theta}_{IB}| = \max |\hat{\theta}_{IB}|$. The selection ratio is close to zero for all $\max |\hat{\theta}_{IB}|$. For $\max |\hat{\theta}_{IB}|<4$ the condition of line 18 is not fulfilled, that is, no statistic can be found containing all the information. For $\max |\hat{\theta}_{IB}|=4$ the algorithm returns $\tilde{\mathbf{X}} = \mathbf{X}$ and the condition of line 16 is not fulfilled. With $\mathbf{X} = \{ \mathrm{X}, \mathrm{V}_1, \mathrm{V}_2\}$, the cardinality correctly saturates at $|\hat{\theta}_{IB}|= 7$, except for a too high $\beta'$. The same behavior is observed for the configurations from Eq.\,\ref{e2a} (Figure \ref{f2}C). In this case, there is a single statistic $\theta = \mathrm{X}+\mathrm{V}_1$, but the path $\mathrm{X} \rightarrow \mathrm{Y} \rightarrow \mathrm{Z}$ requires to condition on $\mathrm{Y}$ to obtain the independence $\mathrm{Z} \perp \mathrm{X} | \theta, \mathrm{Y}$. For $\mathbf{X} = \{ \mathrm{X}, \mathrm{V}_1 \}$, with $\max |\hat{\theta}_{IB}|=4$ the average $|\hat{\theta}_{IB}|$ is below $4$ when using $\beta' = 15$, which indicates that this low $\beta'$ promotes in some cases some degree of compression despite the lack of a statistic. However, these false statistics are not accepted and the selection ratio remains close to zero, since the condition of line 18 in the algorithm is not fulfilled. For $\mathbf{X} = \{ \mathrm{X}, \mathrm{V}_1, \mathrm{Y} \}$, the statistic is correctly identified, with a saturation at $|\hat{\theta}_{IB}| = |\theta||\mathrm{Y}|= 3*2$, again if $\beta'$ is not too high. The fact that for this system a sufficient statistic is identified with $\mathbf{X} = \{ \mathrm{X}, \mathrm{V}_1, \mathrm{Y} \}$ and not with $\mathbf{X} = \{ \mathrm{X}, \mathrm{V}_1 \}$ is consistent with the requirements of the implementation of rule R.nc-ss (Section \ref{ss32}). In particular, given that $\mathrm{X} \perp \mathrm{Z}| \hat{\theta}_{IB}$ for $\mathbf{X} = \{ \mathrm{X}, \mathrm{V}_1, \mathrm{Y} \}$, the lack of a statistic for $\mathbf{X} = \{ \mathrm{X}, \mathrm{V}_1 \}$ corresponds to the requirement that using as input $\mathbf{X} \backslash \mathrm{Y}$ the output $\hat{\theta}'_{IB}$ leads to $\mathrm{X} \notperp \mathrm{Z}| \hat{\theta}'_{IB}$ or to $H(\mathrm{X}|\hat{\theta}'_{IB})=0$. Finally, Figure \ref{f2}D shows the results for the system with no sufficient statistics (Eq.\,\ref{e2b}). Correctly, the cardinality of $\hat{\theta}_{IB}$ does not saturate, independently of the input $\mathbf{X}$ used. For a certain percentage of configurations the selection criteria are fulfilled even in the lack of a sufficient set of statistics but, as we will now see, this does not directly lead to false positives. Indeed, so far we have examined the dependence of the IB output on $\mathbf{X}$, $\beta$, and $\max |\hat{\theta}_{IB}|$, but algorithm \ref{alg1} imposes additional constraints, in particular when combining results across $\max |\hat{\theta}_{IB}|$ values (line 4 and 11), which control the acceptance of invalid statistics. We will now evaluate the overall performance of the IBSSI method \subsubsection{Performance of the IBSSI method identifying sufficient sets of statistics} \label{ss422} The selection ratio examined above is a measure calculated from sampled data, which quantifies how many configurations fulfill the selection criteria, but cannot discriminate true from false selected sufficient statistics. To further evaluate performance, we used our knowledge of the form of the true underlying sufficient statistics in Eqs.\,\ref{e1}-\ref{e2}. For each type of system we pre-specified which forms of $\hat{\theta}_{IB}$ are consistent with the underlying statistics. Here consistency means that $\hat{\theta}_{IB}$ either contains the underlying sufficient statistics, or at least partially identifies them, in a way that the selection criteria are fulfilled and $\hat{\theta}_{IB}$ is valid to apply rules R.c-ss or R.nc-ss. For example, as mentioned above for the system of Eq.\,\ref{e1a} (Figure \ref{f2}A), when $\mathbf{X} = \{ \mathrm{X}, \mathrm{V}_1, \mathrm{V}_2 \}$, the full sufficient statistic has a cardinality $|\theta_{IB}| = |\theta| |\mathrm{V}_2|= 6$, but the IB algorithm may only identify $\theta = g(\mathrm{X}, \mathrm{V}_1)$ for one of the two values of $\mathrm{V}_2$, while for the other it does not compress $\{\mathrm{X}, \mathrm{V}_1\}$. In that case, although the sufficient statistic is not fully identified and $|\hat{\theta}_{IB}|=7$, the estimated statistic is still valid, since it would allow applying rule R.c-ss. The IBSSI method combines results across $\max |\hat{\theta}_{IB}|$ values following algorithm \ref{alg1} and further combines results across values of $\beta$ and selections of $\mathbf{X}$ as described in Section \ref{ss33}. We calculated the overall true positive (TP) rates and false positive (FP) rates across all configurations as follows: For each sample size, algorithm \ref{alg1} was applied with $\mathbf{X} = \{ \mathrm{X}, \mathrm{V}_1\}$ for a whole range of $\beta'$ values. For the cases in which a true underlying sufficient set of statistics exists, a configuration produced a false positive if for any $\beta'$ value a sufficient set of statistics was accepted as valid following the selection criteria, but was inconsistent with the true underlying one. When no underlying statistics exist, any accepted statistics were considered a false positive. A configuration produced a true positive if there was some $\beta'$ value for which a sufficient set of statistics was accepted as valid following the selection criteria and, for those accepted as valid, they all were consistent with true underlying statistics. As mentioned above, here by consistent we mean that $\hat{\theta}_{IB}$ either corresponds to the sufficient statistics, or identifies a compressed $\tilde{\mathbf{X}}$ that, although only partially identifying the structural sufficient statistics, still fulfills the selection criteria. For those configurations that using $\mathbf{X} = \{ \mathrm{X}, \mathrm{V}_1\}$ were not already accounted as false positives or true positives, we repeated the same procedure with the corresponding enlarged $\mathbf{X}$ \--with $\mathbf{X} = \{ \mathrm{X}, \mathrm{V}_1, \mathrm{V}_2\}$ for Eqs.\,\ref{e1} and \ref{e2b}, and $\mathbf{X} = \{ \mathrm{X}, \mathrm{V}_1, \mathrm{Y}\}$ for Eq.\,\ref{e2a}. Overall FP and TP rates were calculated from the total number of false and true positives over the two choices of $\mathbf{X}$. To examine the TP and FP rates we stratified the configurations by levels of information. For each type of system, independently of the input $\mathbf{X}$ used, the stratification was based on the normalized mutual information about $\mathrm{Z}$ carried by the minimal input $\mathbf{X}$ resulting in a sufficient set of statistics, or on the largest $\mathbf{X}$ in the case of Figure \ref{f2}D where no statistics exist. See the caption of Figure \ref{f3} for the average information values at each level for each system, and Appendix D.2 for details on the stratification procedure. Note however that the stratification in information levels is not part of the IBSSI method and we only use it to illustrate how information modulates performance. For the systems studied in this section the normalized information values are rather low (averages in the range $[0.03 - 0.28]$), which means that the performance of the IBSSI method is evaluated in demanding cases. See Appendix E.3 for examples covering a wider range of information levels, up to $0.55$. \begin{figure*} \begin{center} \scalebox{0.38}{\includegraphics*{Fig4IBd.pdf}} \end{center} \caption{Performance of the IBSSI method for the systems of Figure \ref{f02}. \textbf{A}) True positive (TP) rate identifying valid sufficient statistics in the systems from Eqs.\,\ref{e1a}, \ref{e1b}, and \ref{e2a}. \textbf{B}) False positive (FP) rate for those systems and the one of Eq.\,\ref{e2b}. Results are shown as a function of the sample size and configurations are grouped in levels of information about $\mathrm{Z}$ (see main text and Appendix D.2 for details on the stratification procedure). For systems 1 (Eq.\,\ref{e1a}), given $\theta = g(\mathrm{X}, \mathrm{V}_1)$, $I'(\mathrm{X} \mathrm{V}_1 ; \mathrm{Z}) \equiv I(\mathrm{X} \mathrm{V}_1; \mathrm{Z})/ H(\mathrm{Z})$ was used for binning. The average information at each level is: Low: $\langle I'(\mathrm{X} \mathrm{V}_1; \mathrm{Z}) \rangle = 0.03$. Medium: $\langle I'(\mathrm{X} \mathrm{V}_1; \mathrm{Z}) \rangle = 0.07$. High: $\langle I'(\mathrm{X} \mathrm{V}_1; \mathrm{Z}) \rangle = 0.14$. For systems 2 (Eq.\,\ref{e1b}), given $\theta = g(\mathrm{X}, \mathrm{V}_1)$ and $\gamma = g(\mathrm{V}_1, \mathrm{V}_2)$, $I'(\mathrm{X} \mathrm{V}_1 \mathrm{V}_2; \mathrm{Z}) \equiv I(\mathrm{X} \mathrm{V}_1 \mathrm{V}_2; \mathrm{Z})/ H(\mathrm{Z})$ was used for binning. Averages are: Low: $\langle I'(\mathrm{X} \mathrm{V}_1 \mathrm{V}_2; \mathrm{Z}) \rangle = 0.12$. Medium: $\langle I'(\mathrm{X} \mathrm{V}_1 \mathrm{V}_2; \mathrm{Z}) \rangle = 0.20$. High: $\langle I'(\mathrm{X} \mathrm{V}_1 \mathrm{V}_2; \mathrm{Z}) \rangle = 0.28$. For systems 3 (Eq.\,\ref{e2a}), $I'(\mathrm{X} \mathrm{V}_1 \mathrm{Y}; \mathrm{Z}) \equiv I(\mathrm{X} \mathrm{V}_1 \mathrm{Y}; \mathrm{Z})/ H(\mathrm{Z})$ was used, since conditioning on $\theta = g(\mathrm{X}, \mathrm{V}_1)$ and $\mathrm{Y}$ is required to render $\mathrm{X}$ and $\mathrm{Z}$ independent. Averages are: Low: $\langle I'(\mathrm{X} \mathrm{V}_1 \mathrm{Y}; \mathrm{Z}) \rangle = 0.08$. Medium: $\langle I'(\mathrm{X} \mathrm{V}_1 \mathrm{Y}; \mathrm{Z}) \rangle = 0.15$. High: $\langle I'(\mathrm{X} \mathrm{V}_1 \mathrm{Y}; \mathrm{Z}) \rangle = 0.25$. For systems 4 (Eq.\,\ref{e2b}), $I'(\mathrm{X} \mathrm{V}_1 \mathrm{V}_2; \mathrm{Z}) \equiv I(\mathrm{X} \mathrm{V}_1 \mathrm{V}_2; \mathrm{Z})/ H(\mathrm{Z})$ was used, since no sufficient statistics exist. Averages are: Low: $\langle I'(\mathrm{X} \mathrm{V}_1 \mathrm{V}_2; \mathrm{Z}) \rangle = 0.12$. Medium: $\langle I'(\mathrm{X} \mathrm{V}_1 \mathrm{V}_2; \mathrm{Z}) \rangle = 0.20$. High: $\langle I'(\mathrm{X} \mathrm{V}_1 \mathrm{V}_2; \mathrm{Z}) \rangle = 0.28$. The results are shown for two different sets of $\beta'$ values. Note the different scale of the y-axis for the TP and FP rates.} \label{f3} \end{figure*} Figure \ref{f3} shows true positive (TP) rates for the three types of systems containing sufficient statistics, and false positive (FP) rates for all systems. We present the results for two sets of $\beta'$ values, namely $\beta' \in \{ 25, 50, 75, 100\}$ and $\beta' \in \{ 50, 75, 100\}$. The TP rate increases with $N$, and for all types of systems when $N$ is high it is higher for the configurations with higher information. For low $N$, a flip between configurations with high and low information occurs for the systems of Eqs.\,\ref{e1b} and \ref{e2a}. This flip can be understood taking into account how the configurations have been generated, selecting $n \in \{4, 8, 16, 64\}$ for the binomial distribution $p(\mathrm{Z}| \mathbf{Pa}_z)$. The signal-to-noise ratio increases with $\sqrt{n}$, which means that configurations with higher $n$ also tend to have higher information. However, a higher $n$ also implies a poorer sampling of the distribution $p(\mathrm{Z}, \mathbf{X})$, for a given $N$. While a higher information is expected to facilitate the inference of the statistic, a poorer sampling is expected to hinder it (see Appendix E.5 for details). Furthermore, the TP rate increases faster with the set that includes $\beta'= 25$. This is because, with a small sample size, high $\beta'$ values enforce the preservation of differences in the probabilities related to sampling fluctuations and hence lead to selecting $\tilde{\mathbf{X}} = \mathbf{X}$. FP rates are generally low for all types of systems. For the systems of Eqs.\,\ref{e1} and \ref{e2a}, false positives refer to sufficient statistics that are accepted as valid which do not correspond to the underlying functional ones, while for the systems of Eq.\,\ref{e2b} any sufficient statistic accepted is a false positive. As expected, the increased TP rates when including the lower $\beta'= 25$ are accompanied by some (but small) increase in the FP rates. The information level also influences the FP rate. This suggests that imposing a lower bound on information levels to select sufficient statistics can be helpful to reduce false positives. This may be particularly important in cases in which the application of rules R.c-ss and R.nc-ss enables the posterior application of some standard rules of causal orientation, such that the effect of a false positive may propagate. As explained at the beginning of this section, we have focused on the evaluation of the IBSSI method instead of evaluating a full application of rules R.c-ss and R.nc-ss in order to isolate the performance identifying sufficient statistics from other factors that are not specific to rules R.c-ss and R.nc-ss but also affect their applicability. Since the IBSSI method allows the creation of a new conditional independence with the identified sufficient statistics, our results support its utility to implement the rules as described in Section \ref{ss32}. Overall, these examples show that the IB algorithm is able to identify sufficient statistics with good performance and without \emph{a priori} assumptions of which statistics exist. Besides the concrete performance values obtained, most importantly this analysis allowed us to discuss how the IBSSI procedure combines outputs from the IB method across a range of different parameters, and allowed us to characterize the factors that affect performance. The core requirement for the validity of a sufficient set of statistics is the fulfillment of the selection criteria in lines 16-18 of algorithm 1. Modifying the thresholds, especially $a_I$, can control the FP rate. The condition of line 15 checks the consistency of the statistics found across a range of $\max |\hat{\theta}_{IB}|$, and this range can also be widen to be more restrictive. See Appendix D.3 for a further discussion of possible adjustments of the IBSSI method. In Appendix E we provide further examples, with systems in which the set of statistics contains multiple statistics, in which the statistics have a different form, or the generative mechanism of $\mathrm{Z}$ is different. \subsection{Sufficient statistics in biologically-plausible Boolean regulatory rules} \label{ss43} We here focus on a concrete set of functional equations that have been shown \citep{Li06} to accurately model a biological network, namely the signal transduction network of the hormone abscisic acid in guard cells of plants. \cite{Li06} studied a dynamic model of the signaling process, with the temporal updating of the variables in the system governed by Boolean regulatory rules (Table 1 in \cite{Li06}). Data simulated from these rules has also been included in the workbench of the Causation and Prediction Challenge of \cite{Guyon08}, in which the objective was to reconstruct the causal structure of the underlying system \citep{Jenkins08}. Our aim here is not to address the reconstruction of the whole causal structure \--for which rules R.c-ss and R.nc-ss would need to be embedded in a concrete implementation of structure learning algorithm (see Appendix C)\--, but to examine how sufficient statistics present in the Boolean regulatory rules can be identified. We envisage a scenario in which a system governed by this type of Boolean rules is only partially observed, or there are unknown arguments of the rules, as it is often the case \citep{Geier07, Braga18}. For this purpose, we selected the Boolean rules from \cite{Li06} containing at least three arguments (Figure \ref{fB1}A) and simulated all combinations in which only two of the arguments are observable (see Appendix E.4 for further analysis of cases with three arguments observable). The setting studied corresponds to the causal structure of Figure \ref{fB1}B, where $\mathrm{X}$ and $\mathrm{V}_1$ denote the two observable arguments and $\mathrm{U}_1...\mathrm{U}_n$ the rest of arguments in each Boolean expression. All variables are binary, with values $0$ and $1$. We randomly generated $\mathrm{X}$ and the hidden variables with independent uniform distributions. We modeled the link $\mathrm{X} \rightarrow \mathrm{V}_1$ introducing a dependence $p(\mathrm{V}_1=1|\mathrm{x})= 0.4 + 0.2 \mathrm{x}$. We then generated $\mathrm{Z}$ following the Boolean rules. Using $\mathbf{X} = \{\mathrm{X}, \mathrm{V}_1\}$, we studied the inference of the existing sufficient statistics with the IB algorithm. \begin{figure*}[t] \begin{center} \scalebox{0.45}{\includegraphics*{FigBoolbivariate_b}} \end{center} \caption{Boolean regulatory rules containing sufficient statistics. \textbf{A}) Rules modeling the signal transduction network studied in \cite{Li06}. The identity of the original variables is not relevant for our analysis and is here omitted \--see caption of Figure S5 for the correspondence with Table 1 in \cite{Li06}. \textbf{B}) Causal structure corresponding to the setting in which we examine the identification of sufficient statistics. Variables $\mathrm{X}$ and $\mathrm{V}_1$ correspond to the only two observable arguments of a Boolean rule, and $\mathrm{U}_1...\mathrm{U}_n$ to the rest of arguments. \textbf{C}) Configurations corresponding to all combinations of pairs of observable variables from the rules in A). In each case we express the Boolean function in terms of the observable and hidden variables, we show the form of the sufficient statistic, when it exists, and we indicate whether the local selection criteria (see text) are fulfilled.} \label{fB1} \end{figure*} \begin{figure*}[t] \begin{center} \scalebox{0.6}{\includegraphics*{FigBoolbivariate2b}} \end{center} \caption{Performance of the IBSSI method identifying sufficient statistics in biologically-plausible Boolean regulatory rules. \textbf{A}) True positive (TP) rates and True negative (TN) rates, for the configurations of Figure \ref{fB1}C containing and not containing sufficient statistics, respectively. For the configurations with no sufficient statistic the TN rates are represented with a solid black line, and all overlap except for configuration 10 (dashed black line) for the lowest sample size. For the configurations with a sufficient statistic the legend numbers the lines in correspondence to Figure \ref{fB1}C. Configuration 10 was both analyzed for a setting producing a statistic or not. \textbf{B}) Normalised information between $\mathrm{Z}$ and the observable variables for each configuration. For the configurations with a sufficient statistic the TP rate is highly correlated with the normalised information.} \label{fB2} \end{figure*} Figure \ref{fB1}C details all combinations of pairs of observed variables obtained from the rules in Figure \ref{fB1}A. When it exists, we display the form of the sufficient statistic. Note that the sufficient statistics $\theta = \mathrm{X}\,\mathrm{AND}\,\mathrm{V}_1$ and $\theta = \mathrm{X}\,\mathrm{OR}\,\mathrm{V}_1$ could also be expressed as threshold-logic expressions $\mathrm{X} + \mathrm{V}_1 > 1$ and $\mathrm{X} + \mathrm{V}_1 > 0$, respectively, which constitute basic components of artificial neural networks \citep{Mcculloch43}. For configuration 10, a sufficient statistic exists only in the specific case of $p(\mathrm{U}_1)= p(\mathrm{U}_2)$, and we examine both the general and this specific case. Since in the rules $\mathrm{Z}$ is deterministically determined by its parents, we further strengthen the selection criteria of algorithm \ref{alg1} to ensure that, at least for some instantiation $\theta = \theta_0$ of the sufficient statistics embodied in the Boolean functions, neither $\mathrm{Z}$ nor $\mathrm{X}$ is fully determined. The necessity of these additional local criteria can be understood considering the concrete example of configuration $\sharp 2$ in Figure \ref{fB1}C. In this case the form of the sufficient statistic is $\theta = (1+\mathrm{X})\mathrm{V}_1$ and $\theta$ has three values: $\theta =0$ whenever $\mathrm{V}_1=0$ \--given the $\mathrm{AND}$ operation\--, and $\theta = 1,2$ when $\mathrm{V}_1=1$ and $\mathrm{X}= 0,1$, respectively. However, $\theta =2$ deterministically determines $\mathrm{X} = \mathrm{Z} = 1$, a value $\theta =0$ does not determine $\mathrm{X}$ but leads deterministically to $\mathrm{Z}=0$, while $\theta = 1$ leaves some uncertainty about $\mathrm{Z}$ given the hidden variables, but univocally determines $\mathrm{X}=0$. That is, the conditions of lines 16-17 in algorithm \ref{alg1} are fulfilled, but there is no $\theta = \theta_0$ for which simultaneously $H(\mathrm{Z}|\theta_0)>0$ and $H(\mathrm{X}|\theta_0)>0$. The additional local criteria demand the existence of such $\theta_0$, since otherwise it is not possible to evaluate the independence $\mathrm{X} \perp \mathrm{Z} |\theta_0 $ or other dependencies and independencies used in rules R.c-ss and R.nc-ss. From all configurations of Figure \ref{fB1}C, a valid sufficient statistic exists for 8 configurations. From the rest, only in 4 cases there is no sufficient statistic, while the validity of the sufficient statistic is rejected based on local criteria for other 7 configurations. While here following \cite{Li06} we study Boolean deterministic rules and limit the source of stochasticity to the hidden arguments of the rules, alternative models have been proposed, e.\,g.\,for gene regulatory networks, which combine Boolean expressions with explicit additional sources of stochasticity \citep{Shmulevich02, Ruczinski04, Dehghannasiri18}. The sufficient statistics discarded based on local criteria could be also exploited in the presence of such additional stochasticity. Figure \ref{fB2}A shows true positive (TP) rates for the configurations with a sufficient statistic, and true negative (TN) rates for the configurations without statistic, respectively. The rates were calculated over 100 independent simulations for each sample size. As seen from the TN rates, for these examples the IBSSI method does not produce false positives, except in few cases with the lowest sample size for configuration 10, for which indeed a sufficient statistic exists in a concrete setting, namely $p(\mathrm{U}_1)= p(\mathrm{U}_2)$. For the configurations containing a sufficient statistic, the TP rate increases with $N$ and is highly correlated with the normalised information $I(\mathrm{Z}; \mathrm{X} \mathrm{V}_1)/H(\mathrm{Z})$ (Figure \ref{fB2}B). \section{Selection Bias} \label{ss5} Standard algorithms of structure learning exploiting conditional independencies have also been extended to systems observed under selection bias \citep{Spirtes96}. When selection bias is present, dependencies between variables otherwise independent may appear because of a constraint introduced in the way a common descendant of those variables is sampled. For example, in Figure \ref{f4}A, $\mathrm{S}$ represents a variable directly related to the selection bias. With no selection bias $\mathrm{X} \perp \mathrm{Z}$, but if the sampling process depends on $\mathrm{S}$, a dependence is introduced according to $\mathrm{X} \notperp \mathrm{Z} | \mathrm{S}$. To introduce a bias it is not necessary that $\mathrm{S}$ takes the same value for all samples, it suffices that the sampled distribution $p^*(\mathrm{S})$ differs from the one determined by its parents, $p(\mathrm{S}| \mathrm{X}, \mathrm{Z}, \mathrm{V}_1)$. Note that here $\mathrm{S}$ is an actual variable of the system, observable or not, as opposed to additional \emph{selection variables} of the type $\mathrm{S}_\mathrm{V}$ defined in \cite{Spirtes96}, which are added to represent sampling properties of associated observable variables $\mathrm{V}$. If $\mathrm{S}$ is observable, a sufficient statistic like the one in Figure \ref{f4}A can be identified using the IB algorithm to determine $\theta$ such that $\mathrm{S} \perp \mathrm{X}| \theta$. Furthermore, $\theta$ can be identified even when $\mathrm{S}$ introduces selection bias and is not observable. This is because apart from $\mathrm{S} \perp \mathrm{X}| \theta$ the sufficient statistic also creates the independence $\mathrm{Z} \perp \mathrm{X}| \theta, \mathrm{S}$. In Figure \ref{f4} we have omitted for simplicity any variable $\mathrm{Y}$ as involved in rules R.c-ss and R.nc-ss, but it is clear that the presence of $\theta$ could be exploited to apply the rules. For a system containing the structure of Figure \ref{f4}A and $\mathrm{X} \rightarrow \mathrm{Y} \leftarrow \mathrm{Z}$, R.c-ss would be applicable, and for a system containing that structure and $\mathrm{X} \rightarrow \mathrm{Y} \rightarrow \mathrm{Z}$, R.nc-ss would be applicable, in that case with $\mathrm{Z} \perp \mathrm{X}| \theta, \mathrm{S}, \mathrm{Y}$. \begin{figure*}[t] \begin{center} \scalebox{0.55}{\includegraphics*{F3.pdf}} \end{center} \caption{Causal structures studied to assess the performance of the IBSSI method finding sufficient statistics in the presence of selection bias or dormant independencies. \textbf{A}) Causal structure in which the dependence between $\mathrm{X}, \mathrm{V}_1$ and $\mathrm{Z}$ is due to bias selecting $\mathrm{S}$, for which a sufficient statistic $\theta = g(\mathrm{X}, \mathrm{V}_1)$ exists. Variable $\mathrm{S}$ introduces a selection bias and is not necessarily observable. \textbf{B}) Causal structure in which the sufficient statistic $\theta = g(\mathrm{X}, \mathrm{V}_1)$ only results in a conditional independence between $\mathrm{X}$ and $\mathrm{Z}$ when the system is intervened with $do(\mathrm{V}_3)$ (dormant independence). In the unintervened system conditioning on $\mathrm{V}_3$ activates a dependence between $\mathrm{X}$ and $\mathrm{Z}$ through the hidden variable $\mathrm{U}$. The intervention $do(\mathrm{V}_3)$ eliminates all incoming arrows to $\mathrm{V}_3$ and creates the new independence $\mathrm{X} \perp \mathrm{Z} | \theta, do(\mathrm{V}_3)$. The identifiability of the intervention allows applying the IB algorithm to the intervened system. For simplicity, an additional variable $\mathrm{Y}$ is omitted, but in the presence of the causal links $\mathrm{X} \rightarrow \mathrm{Y} \leftarrow \mathrm{Z}$ the sufficient statistic would allow applying R.c-ss, and R.nc-ss could be applied in the presence of $\mathrm{X} \rightarrow \mathrm{Y} \rightarrow \mathrm{Z}$.} \label{f4} \end{figure*} To study examples of the identification of sufficient statistics in the presence of selection bias we generated a system with the causal structure of Figure \ref{f4}A. The variable $\mathrm{S}$ subjected to selection bias was generated with a binomial GLM, analogously to how we generated $\mathrm{Z}$ for the systems of Eqs.\,\ref{e1}-\ref{e2}. In particular, $\mathrm{S} \sim B(n,p_\mathrm{s})$, with $p_\mathrm{s} = 1/(1+\mathrm{exp}(-h(\mathbf{Pa}_s)))$, where $\mathbf{Pa}_s = \{ \mathrm{X}, \mathrm{V}_1, \mathrm{Z}\}$. The function $h(\mathbf{Pa}_s)$ was modeled as: \begin{equation} \begin{split} h &= a_0+ a_1 \mathrm{Z} + a_2(\mathrm{X}+\mathrm{V}_1) + a_3 (\mathrm{X}+\mathrm{V}_1)^2 + a_4(\mathrm{X}+\mathrm{V}_1)\mathrm{Z} + a_5(\mathrm{X}+\mathrm{V}_1)^2 \mathrm{Z}. \label{e3} \end{split} \end{equation} As in previous examples, we used $n \in \{4, 8, 16, 64\}$ to simulate configurations with different signal-to-noise ratio. Variables $\mathrm{X}$, $\mathrm{V}_1$, and $\mathrm{Z}$ are binary independent variables with values $0,1$, but the selection bias introduces a dependence between them. $\mathrm{S}$ is not observable, and a selection bias is introduced sampling only the observable variables when $\mathrm{S}$ is in the range $\max(\mathrm{S})/3 < \mathrm{S} < 2\max(\mathrm{S})/3$. We refer to this range as $\{\mathrm{S}_0\}$. We modeled $\mathrm{V}_2 \rightarrow \mathrm{Z}$ by $p(\mathrm{Z} = 1| \mathrm{V}_2 = \mathrm{v}_2) = 0.4 + 0.2 \mathrm{v}_2$. The selection bias creates a dependence between $\mathrm{Z}$ and $\mathrm{X}$, $\mathrm{V}_1$, which given the form of Eq.\,\ref{e3} results in a sufficient statistic $\theta = \mathrm{X}+\mathrm{V}_1$ for $\mathrm{X}$ with respect to $\mathrm{Z}$ (Fig.\,\ref{f4}A). In contrast to the sufficient statistics studied so far, here $\theta$ is not a functional sufficient statistic in the functional equation of $\mathrm{Z}$ or $\mathrm{X}$, but in the functional equation of $\mathrm{S}$, which is not observable. Both $\mathrm{X} =1,\mathrm{V}_1 =0$ and $\mathrm{X} =0,\mathrm{V}_1 =1$ result in $\theta =1$, and $\theta = \mathrm{X} + \mathrm{V}_1 \in \{0, 1, 2 \}$, with cardinality $|\theta|= 3$. Like for the previous examples, we randomly sampled the coefficients $\mathbf{a}$ to generate $1440$ configurations. Again, we ensured that the generated distributions were faithful to the corresponding graph $G^+_{\theta}$ so that knowledge of the underlying statistics could be used to evaluate the performance of the IBSSI method. First, to ensure the standard faithfulness condition between the distribution and the corresponding graph $G$, we required that the selection bias actually creates a dependence between $\mathrm{Z}$ and $\mathrm{X},\mathrm{V}_1$, imposing a lower bound of $I(\mathrm{Z}; \mathrm{X}, \mathrm{V}_1| \{\mathrm{S}_0\})/ H(\mathrm{Z}| \{\mathrm{S}_0\})\geq 0.05$. Second, because the sufficient statistic is to be inferred based on $\mathrm{Z} \perp \mathrm{X}| \theta, \{\mathrm{S}_0\}$ we required that for two events of $\{ \mathrm{X}, \mathrm{V}_1\}$ that following the generative equation of Eq.\,\ref{e3} correspond to a different value of $\theta = \mathrm{X} + \mathrm{V}_1 $, the difference in $p(\mathrm{Z}| \mathrm{X}, \mathrm{V}_1, \{\mathrm{S}_0\})$ was not smaller than $0.05$. Figure \ref{f6}A shows the overall TP and FP rates obtained with the IBSSI method. Again, a high TP rate is achievable with a low FP rate. Also here performance depends on the information levels, which were stratified by $I(\mathrm{Z}; \mathrm{X}, \mathrm{V}_1 | \{\mathrm{S}_0\})/ H(\mathrm{Z}| \{\mathrm{S}_0\})$. A smaller difference was found between selecting a range $\beta' \in \{ 25, 50, 75, 100\}$ or $\beta' \in \{ 50, 75, 100\}$. These results indicate that the identification of sufficient sets of statistics can be a powerful tool to counteract the impact of selection bias, allowing the recovery of a conditional independence between variables for which the selection bias introduced a dependence. \begin{figure*}[t] \begin{center} \scalebox{0.38}{\includegraphics*{Fig7IBd.pdf}} \end{center} \caption{Performance of the Information Bottleneck Sufficient Statistics Inference (IBSSI) method in the presence of selection bias (Eq.\,\ref{e3}) or dormant independencies (Eq.\,\ref{e4}). In both cases we show the true positive rates and false positive rates identifying valid sufficient statistics. Results are shown as a function of the sample size and for two ranges of $\beta'$ values. Configurations are grouped by information levels. \textbf{A}) Systems with selection bias. The selection bias limits observations to samples with $\mathrm{S}$ in the range $\{\mathrm{S}_0\}$ defined by $\max(\mathrm{S})/3 < \mathrm{S} < 2\max(\mathrm{S})/3$. Information levels are determined by $I'(\mathrm{X} \mathrm{V}_1; \mathrm{Z}| \{\mathrm{S}_0\}) \equiv I(\mathrm{X} \mathrm{V}_1; \mathrm{Z}| \{\mathrm{S}_0\})/ H(\mathrm{Z}| \{\mathrm{S}_0\})$, since $\theta = g(\mathrm{X}, \mathrm{V}_1)$. The average information at each level is: Low: $\langle I'(\mathrm{X} \mathrm{V}_1; \mathrm{Z}| \{\mathrm{S}_0\}) \rangle = 0.08$. Medium: $\langle I'(\mathrm{X} \mathrm{V}_1; \mathrm{Z}| \{\mathrm{S}_0\}) \rangle = 0.12$. High: $\langle I'(\mathrm{X} \mathrm{V}_1; \mathrm{Z}| \{\mathrm{S}_0\}) \rangle = 0.20$. \textbf{B}) Systems with dormant independencies. The intervention $do(\mathrm{V}_3)$ creates the new independence $\mathrm{X} \perp \mathrm{Z} | \theta, do(\mathrm{V}_3)$. Information levels are determined by $I'(\mathrm{X} \mathrm{V}_1; \mathrm{Z}| do(\mathrm{V}_3=1)) \equiv I(\mathrm{X} \mathrm{V}_1; \mathrm{Z}| do(\mathrm{V}_3=1 ))/ H(\mathrm{Z}| do(\mathrm{V}_3=1))$, since $\theta = g(\mathrm{X}, \mathrm{V}_1)$ and the system is intervened with $ do(\mathrm{V}_3= 1)$. The average information at each level is: Low: $\langle I'(\mathrm{X} \mathrm{V}_1; \mathrm{Z}| do(\mathrm{V}_3= 1)) \rangle = 0.08$. Medium: $\langle I'(\mathrm{X} \mathrm{V}_1; \mathrm{Z}| do(\mathrm{V}_3= 1)) \rangle = 0.13$. High: $\langle I'(\mathrm{X} \mathrm{V}_1; \mathrm{Z}| do(\mathrm{V}_3= 1)) \rangle = 0.18$.} \label{f6} \end{figure*} \section{Sufficient statistics in identifiable intervened systems} \label{ss6} So far we have examined examples considering that the whole causal structure of the system was unknown. In a more general setting, the causal structure may already be partially known, either because it can be partially inferred with the standard FCI algorithm, or thanks to side information, which can comprise interventional data \citep{Bareinboim16}. Similarly, when the aim is not to infer the causal structure but to identify a causal effect, it is most commonly assumed that the causal structure is known \citep{Tian02, Shpitser08c}, or concrete hypotheses about the causal structure are confronted. In these scenarios, finding sufficient statistics can also be useful either to further learn the causal structure or to identify causal effects. When parts of the causal structure are known it is possible to exploit also sufficient statistics that only lead to new conditional independencies when the system is intervened. An intervention of variable $\mathrm{V}_i$, denoted by $do(\mathrm{V}_i)$, corresponds to an external modification of the mechanisms of the system such that the functional equation of $\mathrm{V}_i$ is replaced by enforcing externally a certain value $\mathrm{V}_i = \mathrm{v}_i$ ($do(\mathrm{V}_i= \mathrm{v}_i )$). Under certain conditions on the form of the causal structure \citep{Tian02, Shpitser08c}, it is possible to calculate the distribution of the variables in the intervened system from the distribution in the observed system. Graphically, an intervention corresponds to removing the incoming arrows to the intervened variable from its parents. The removal of these arrows eliminates certain paths between variables, and this may lead to new conditional independencies only present in the intervened system \--known as \emph{dormant independencies} \citep{Shpitser08}. Consider the causal structure of Figure \ref{f4}B and assume that the structure is already known, except for the presence of the sufficient statistic $\theta$. That is, only the associated graph $G$, but not $G^+_{\theta}$, is known. This causal structure may be embedded in a larger system, with other parts of its structure yet to be inferred, such that identifying the sufficient statistic may help to further infer it. In the graph, $\mathrm{U}$ represents a variable whose presence is known, but which is not observable. Despite the presence of the functional statistic $\theta = g(\mathrm{X}, \mathrm{V}_1)$, it is not possible to find a set $\mathbf{S}$ such that $\mathrm{X} \perp \mathrm{Z} | \mathbf{S}, \theta$. This is because $\mathrm{X}$ and $\mathrm{Z}$ are dependent through the path $\mathrm{X} \rightarrow \mathrm{V}_3 \rightarrow \mathrm{Z}$, and conditioning on $\mathrm{V}_3$ to inactivate this path activates the path $\mathrm{X} \rightarrow \mathrm{V}_2 \leftarrow \mathrm{U} \rightarrow \mathrm{Z}$, which cannot be inactivated given that $\mathrm{U}$ is hidden. Alternatively, the path $\mathrm{X} \rightarrow \mathrm{V}_3 \rightarrow \mathrm{Z}$ can also be eliminated by intervening on $\mathrm{V}_3$, instead of conditioning. In the system resulting from the intervention $do(\mathrm{V}_3)$, the sufficient statistic can be identified from the independence $\mathrm{X} \perp \mathrm{Z} | \theta, do(\mathrm{V}_3)$ (Figure \ref{f4}B), and this can be exploited by the IB algorithm because the intervened system is identifiable, that is, the joint distribution of all other variables when intervening $\mathrm{V}_3$ can be calculated from the observational distribution. In more detail, the joint distribution of the observable variables in the intervened system can be identified as \citep{Pearl09} \small \begin{equation} \begin{split} &p(\mathrm{X}, \mathrm{V}_1, \mathrm{V}_2, \mathrm{Z}| do(\mathrm{V}_3 = \mathrm{v}_3)) = \sum_\mathrm{U} p(\mathrm{Z}| \mathrm{X}, \mathrm{V}_1, \mathrm{V}_3=\mathrm{v}_3, \mathrm{U}) p(\mathrm{V}_2| \mathrm{X}, \mathrm{U}) p(\mathrm{X}) p(\mathrm{U}) p(\mathrm{V}_1) = \\&\sum_\mathrm{U} p(\mathrm{Z}| \mathrm{X}, \mathrm{V}_1, \mathrm{V}_3=\mathrm{v}_3, \mathrm{U}) p(\mathrm{U} | \mathrm{X}, \mathrm{V}_2) p(\mathrm{X}, \mathrm{V}_2) p(\mathrm{V}_1) = p(\mathrm{Z}| \mathrm{X}, \mathrm{V}_1, \mathrm{V}_2, \mathrm{V}_3 = \mathrm{v}_3) p(\mathrm{X}, \mathrm{V}_2) p(\mathrm{V}_1), \label{e5} \end{split} \end{equation} \normalsize where the marginalization of the hidden variable $\mathrm{U}$ is possible because $\mathrm{Z} \perp \mathrm{V}_2 | \mathrm{X}, \mathrm{V}_1, \mathrm{V}_3, \mathrm{U}$ and $\mathrm{U} \perp \mathrm{V}_1 \mathrm{V}_3 | \mathrm{X}, \mathrm{V}_2$. There is no causal effect on $\mathrm{X}$, $\mathrm{V}_1$, and $\mathrm{V}_2$, so that $p(\mathrm{X}, \mathrm{V}_1, \mathrm{V}_2| do(\mathrm{V}_3 = \mathrm{v}_3 )$ is equal to $p(\mathrm{X}, \mathrm{V}_1, \mathrm{V}_2)$. The IB method can be applied to infer $\theta$, with the only difference that now the joint distribution of the intervened system in Eq.\,\ref{e5} is used as input. For a concrete example, $\mathrm{Z}$ was generated with a binomial GLM with $p_\mathrm{z} = 1/(1+\mathrm{exp}(-h(\mathbf{Pa}_z)))$, where $\mathbf{Pa}_z = \{ \mathrm{X}, \mathrm{V}_1, \mathrm{V}_3, \mathrm{U}\}$. The function $h(\mathbf{Pa}_z)$ was defined as: \begin{equation} \begin{split} h &= a_0+ a_1 \mathrm{U} + a_2(\mathrm{X}+\mathrm{V}_1) + a_3 (\mathrm{X}+\mathrm{V}_1)^2 + a_4(\mathrm{X}+\mathrm{V}_1)\mathrm{U} + a_5(\mathrm{X}+\mathrm{V}_1)^2 \mathrm{U}. \label{e4} \end{split} \end{equation} Because we model the intervened system with $do(\mathrm{V}_3 = \mathrm{v}_3)$ fixed, the dependence of $\mathrm{Z}$ on $\mathrm{V}_3$ is absorbed in the value of the coefficients. $\mathrm{X}$, $\mathrm{V}_1$, and $\mathrm{U}$ are independent binary variables. The links $\mathrm{X} \rightarrow \mathrm{V}_2 \leftarrow \mathrm{U}$ were modeled generating $\mathrm{V}_2$ from a binomial distribution with $n_{v_2} = 16$ and a mean parameter $p(\mathrm{V}_2 = 1| \mathrm{X}, \mathrm{U}) = 0.1 + 0.3 \mathrm{x} + 0.3 \mathrm{u}$. Variable $\mathrm{V}_3$ was generated from a binomial distribution with $n_{v_3} =1$ and parameter $p(\mathrm{V}_3 =1| \mathrm{X}, \mathrm{V}_2) = 1/(1+\mathrm{exp}(2 -1.5 \mathrm{v}_2/n_{v_2} - 2.5 \mathrm{x})$. We used the intervention $do(\mathrm{V}_3 = 1)$ to identify the sufficient statistic. We followed the same procedure of Section \ref{ss42} to generate $1440$ configurations. The signal-to-noise ratio was controlled with $n_z \in \{4, 8, 16, 64\}$. The probability $p(\mathrm{U} = 1)= 0.5$ was kept constant across configurations. To ensure faithfulness of the distribution to the corresponding graph $G$ when randomly sampling the coefficients $\mathbf{a}$, we required $I(\mathrm{X}, \mathrm{V}_1; \mathrm{Z}| do(\mathrm{V}_3=1))/ H(\mathrm{Z}|do(\mathrm{V}_3=1))\geq 0.05$ and $I(\mathrm{V}_2; \mathrm{Z}| do(\mathrm{V}_3=1))/ H(\mathrm{Z}|do(\mathrm{V}_3=1))\geq 0.05$. As before, we also required a minimum difference of $0.05$ for $p_\mathrm{z}$ according to Eq.\,\ref{e4} for different values of $\theta = \mathrm{X}+\mathrm{V}_1$. Figure \ref{f6}B shows the overall TP and FP rates. High performance is achieved with sufficiently high $N$ values, with a high TP and low FP rate. In this system, $\theta$ can only be identified with $\mathbf{X} = \{ \mathrm{X}, \mathrm{V}_1\}$, while the input $\mathbf{X} = \{ \mathrm{X}, \mathrm{V}_1, \mathrm{V}_2\}$ only can produce false positives, since the path $\mathrm{X} \rightarrow \mathrm{V}_2 \leftarrow \mathrm{U} \rightarrow \mathrm{Z}$ leads to $\mathrm{Z} \notperp \mathrm{X}| \theta, \mathrm{V}_2, do(\mathrm{V}_3)$. The low FP rates reflect that the IBSSI method detects this dependence when $\mathbf{X} = \{ \mathrm{X}, \mathrm{V}_1, \mathrm{V}_2\}$ is used, and the selection criteria of algorithm \ref{alg1}, in particular line 18, precludes from selecting an invalid statistic. In this case we found a weak dependence of the TP rates on the amount of information, but the FP rates were also lower for higher information levels. \section{Conclusions} We introduced a general framework that uses sufficient statistics to increase the inferential power of previous methods for structure learning that extract causal information from conditional independencies. While the standard formulation of these methods exploits conditional independencies directly verifiable from the probability distribution of the observable variables \citep{Spirtes00,Pearl09}, we argue that the structure in the generative mechanisms of observable variables often contains substructures acting as sufficient statistics, which create additional conditional independencies. We proposed to use the Information Bottleneck (IB) method \citep{Tishby99} to identify the sufficient statistics and introduced the Information Bottleneck Sufficient Statistics Inference (IBSSI) method to select sufficient sets of statistics useful for structure learning. We extended the standard rules of causal discovery from observational data to exploit the independencies associated with the inferred sufficient statistics and applied this approach to data, illustrating that the IBSSI method is able to identify sufficient statistics with a high true positive (TP) rate and low false negative (FN) rate. We validated the IBSSI method in simulated systems specifically designed to contain different types of functional equations and types of sufficient statistics. We equally validated the method with a benchmark model \citep{Jenkins08, Guyon08} composed of Boolean regulatory rules \--in whose structure we identified the presence of sufficient statistics\-- that has previously been shown to accurately model a biological signal transduction network \citep{Li06}. We characterized critical factors that determine the tradeoff between the TP and FN rates and introduced conditions to assess the consistency of the statistics. To exploit the sufficient statistics, in the main text for simplicity we focused on the two basic rules of causal orientation that allow inferring colliders and noncolliders from conditional independencies \citep{Verma93,Spirtes00}, since these rules underpin the complete set of rules that determines Markov equivalence classes of causal structures \citep{Zhang08c}. More broadly, the sufficient statistics can equally be applied to extend the complete set of rules, as we detail in Appendix C presenting an extension of the Causal Inference (CI) algorithm of \cite{Spirtes00} which integrates those and further new rules based on sufficient statistics together with the standard rules of causal orientation. Importantly, the new rules can interact synergistically with the standard rules, such that some information extracted from them iteratively allows the application of standard orientation rules not applicable otherwise. However, while the new rules can readily be integrated with the standard ones and the IBSSI method provides a procedure to infer sufficient sets of statistics, future work should further examine how to optimally combine the identification of sufficient statistics and their exploitation for structure learning. In particular, when probing the existence if sufficient statistics, especially in large systems, in a first step the partially oriented causal structure retrieved as the output of a standard algorithm such as the FCI \citep{Spirtes00} can help to determine which variables should be selected as potential arguments of the statistics. In subsequent iterative steps, new causal information extracted thanks to already identified statistics can inform the selection of new potential arguments of further statistics. In the main text, we focused on the identification of sufficient statistics nonparametrically with the IB method. Nonparametric approaches have the advantage of generality, but for specific domains in which the form of the generative mechanisms can properly be modeled, modeling approaches can be less data demanding and computationally intensive. To correctly infer a sufficient set of statistics, a model does not need to properly capture the full functional equation, but only to identify the (possibly much simpler) subcomponents containing the functional sufficient statistics. We discuss in Appendix F how modeling approaches can equally be applied to identify statistics. Indeed, the form of a fitted model may already indicate the presence of sufficient statistics, which can then be tested subsequently. Furthermore, since the identification of sufficient sets of statistics relies on characterizing substructures embodied in the functional equations, we expect this method to be particularly adaptable to an hybrid approach \citep{Ogarrio16, Jabbari17}, such that instead of recovering a single partially oriented graph, multiple causal structures are scored, quantifying the confidence in different inferred sufficient statistics. Similarly, sufficient statistics embodied in the functional equations are expected to constitute simpler and possibly more robust submodules preserved by a causal mechanism across domains, as opposed to the whole set of parameters of the functional equations. Accordingly, the sufficient statistics could also be used by complementary techniques for structure learning which exploit the invariance of generative models across domains \citep{Peters16,Ghassami17,Besserve18,Heinze18}. Furthermore, as we illustrated in Section \ref{ss6}, the identification of sufficient statistics can easily be combined with methods to calculate the effect of external interventions in the system \citep{Shpitser08c, Shpitser08}. Using information from new independencies associated with sufficient statistics can equally be useful to select optimal interventions designed to discriminate between Markov-equivalent causal structures \citep{Hauser14,Triantallou15,Kocaoglu17,Ghassami18, Agrawal2019}, or to determine interventional Markov equivalence classes \citep{Hauser12}. In this work we implemented the IB method with the original iterative procedure introduced by \cite{Tishby99}. However, more refined implementations of the IB method using deep networks \citep{Alemi17,Belghazi2018,Wieczorek18} promise to provide more efficient procedures to estimate sufficient sets of statistics also from high-dimensional data and for continuous variables. Deep learning approaches to infer generative models \citep{Kocaoglu18,Goudet18} can also be useful to characterize the subfunctions corresponding to sufficient statistics for high-dimensional data. A major challenge for the algorithms of structure learning based on conditional independencies is that of scalability to large systems \citep{Kalisch07,Raghu18,Ramsey19}. Large systems also represent a challenge for the application of the IBSSI method, in particular regarding the selection of which variables should be used as potential arguments of unknown underlying sufficient statistics. However, because the identification of sufficient statistics is especially conceived to exploit substructures within the functional equations that may depend on a substantially lower number of variables, we can expect that the method is particularly useful in large systems, for which conditional independencies between the observable variables involve a large number of conditioning variables. Such large complex causal structures comprise gene regulatory networks \citep{Maathuis10,Neto10,Banf17,Glymour19} or brain connectivity networks \citep{Chicharro14,Sanchez19,Reid19}. The identification of causally relevant low-dimensional sufficient statistics is also a main objective in systems neuroscience \citep{Cunningham14}, since understanding the neural code requires characterizing how information in the representation of sensory stimuli in neural population responses is transmitted across brain areas and transformed into a representation of behavioral decisions \citep{Chicharro14b,Panzeri17, Piasini17}. The IBSSI method promises to be particularly useful for this type of highly interconnected large systems with ubiquitous hidden variables, for which conditional independencies between the observable variables may be scarce. \acks{This work was supported by the BRAIN Initiative (Grants No. R01 NS108410, R01 NS109961 and No. U19 NS107464 to S.P.) and by the Fondation Bertarelli.} \newpage
{'timestamp': '2020-10-13T02:26:27', 'yymm': '2010', 'arxiv_id': '2010.05375', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05375'}
arxiv
\section{Introduction} The training stability of the StyleGAN architecture along with the availability of high quality pre-trained models \cite{pinkney_awesome_stylegan}, has made it possible for creatives and artists to produce high-quality generative models with access to only limited computing resources by using transfer learning. A model which has been generated by transfer learning, and the original "base model" have a close relationship \cite{fort2020deep} and it has been shown that linearly interpolating between the weights of two such generative models produces outputs which are approximately an interpolation of the two learned domains \cite{wang2018esrgan}. \footnote{Much experimentation on StyleGAN interpolation has been shared informally by the community on Twitter but there are no formal academic publications of these methods as far as the authors are aware.} Simply applying linear interpolation between all the parameters in the model does not make use of a highly important element of control in StyleGAN, namely that different resolution layers in the model are responsible for different features in the generated image \cite{karras2019stylebased} (e.g. low resolutions control head pose, high resolutions control lighting). By interpolating between parameters from different models, but doing this dependent on the resolution of the particular layer, we can select and blend features from the different generators as we desire. For example, taking the pose and head shape of ukiyo-e style portraits but preserving the photo-realistic rendering, or vice-versa, as shown in Figure \ref{fig:ukiyoe}. \section{Method} \label{method} \begin{figure} \centering \includegraphics[width=0.8\linewidth]{neurips-blending-fig} \caption{Schematic of the "layer swapping" interpolation scheme described in Section \ref{method}. Each block represents a resolution level in StyleGAN, the final interpolated model is composed of blocks taken from each of the input models depending on the resolution (not all blocks are shown for brevity).} \label{fig:diagram} \end{figure} \begin{enumerate} \item Start with a pre-trained model with weights $p_{base}$, the Base model. \item Train the model on a new dataset to create a model via transfer learning with weights $p_{transfer}$, the Transferred model. \item Combine the weights from both original and new Generators into a new set of weights $p_{interp}$. The function used to combine the weights between two models should be dependent on the resolution $r$ of the convolutional layers which are being combined. The choice of function used is arbitrary but here we use a simple binary choice between weights of each model which we term "layer swapping" (for more details see Appendix \ref{mathdetails}). \begin{align} p_{interp} &= (1-\alpha) p_{base} + \alpha p_{transfer} \\ \alpha &= \begin{cases} 1, \text{where } r<=r_{swap} \\ 0, \text{where } r>r_{swap}\end{cases} \end{align} where $r_{swap}$ is the resolution level at which the transition from one model to another occurs. \item The new weights $p_{interp}$ are then used to create the Interpolated model. \end{enumerate} \section{Results - Toonification} \begin{figure} \centering \includegraphics[width=\linewidth]{toonify} \caption{The interpolated model (a) produces images with the structural characteristics of a cartoon, but with photo-realistic rendering. When comparing the same latent vector input to the original FFHQ model (b) the identity appears largely preserved thus the interpolated model gives a "cartoonification" effect. The right most pair shows a result after encoding an image of Shinzo Abe.} \label{fig:toonify} \end{figure} We further demonstrate resolution dependent interpolation for the generation of photo-realistic faces exhibiting the structural characteristics of a cartoon character. We combine high resolution layers of an FFHQ model with the low resolution layers from a model transferred to animated character faces. This gives the appearance of realistic facial textures with the structural characteristics of a cartoon (e.g. large eyes, small chin). When given the same latent vector as input, the base and interpolated models generate faces with many of the same broad characteristics in terms of identity. We can then use the well established practice of encoding an arbitrary face into the base model \cite{karras2020analyzing}\cite{puzer_encoder} and use this latent vector as input to the interpolated model to give a "Toonified" version of the original image, see Figure \ref{fig:toonify}. \begin{ack} No external funding was received for this work. \end{ack} \small
{'timestamp': '2020-11-24T02:10:18', 'yymm': '2010', 'arxiv_id': '2010.05334', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05334'}
arxiv
\section{Appendices} \label{sec:appendix} \subsection{Data} \label{app:data} The complete set of \emph{normalized} classification labels for all three medication attributes and their meaning is shown in Table \ref{tab:class labels detailed}. Average statistics about the dataset are shown in Table \ref{tab:dataset description stats}. \begin{table}[!ht] \centering \begin{tabular}{@{}lllll@{}} \toprule & min & max & mean & $\sigma$ \\ \midrule \#utterances in \emph{text} & 3 & 20 & 7.8 & 2.3 \\ \#words in \emph{text} & 12 & 565 & 80.8 & 41.0 \\ \#words in \emph{freq} span & 1 & 21 & 4.4 & 2.6 \\ \#words in \emph{route} span & 1 & 9 & 1.5 & 1.0 \\ \#words in \emph{change} span & 1 & 34 & 6.8 & 4.9 \\ \bottomrule \end{tabular}% \caption{Statistics of extraction labels (\#words) and the corresponding \emph{text} } \label{tab:dataset description stats} \end{table} \begin{table*}[!ht] \centering \resizebox{\textwidth}{!}{% \begin{tabular}{@{}|l|l|l|l|@{}} \toprule Attribute & class & Meaning & class proportion \\ \midrule \emph{frequency} & \begin{tabular}[c]{@{}l@{}} Daily\\ Every morning\\ At Bedtime\\ Twice a day\\ Three times a day\\ Every six hours\\ Every week\\ Twice a week\\ Three times a week\\ Every month\\ Other\\ None\end{tabular} & \begin{tabular}[c]{@{}l@{}} Take the medication once a day (specific time not mentioned).\\ Take the medication once every morning.\\ At Bedtime\\ Twice a day\\ Three times a day\\ Every six hours\\ Every week\\ Twice a week\\ Three times a week\\ Every month\\ Other\\ None\end{tabular} & \begin{tabular}[c]{@{}l@{}} 8.0 \\ 0.9\\ 1.7\\ 6.5\\ 1.6\\ 0.2\\ 0.9\\ 0.2\\ 0.3\\ 0.3\\ 1.5\\ 77.9\end{tabular} \\\midrule \emph{route} & \begin{tabular}[c]{@{}l@{}}Pill\\ Injection\\ Topical cream\\ Nasal spray\\ Medicated patch\\ Ophthalmic solution\\ Inhaler\\ Oral solution\\ Other\\ None\end{tabular} & \begin{tabular}[c]{@{}l@{}}Pill\\ Injection\\ Topical cream\\ Nasal spray\\ Medicated patch\\ Ophthalmic solution\\ Inhaler\\ Oral solution\\ Other\\ None\end{tabular} & \begin{tabular}[c]{@{}l@{}}6.8\\ 3.5\\ 1.0\\ 0.5\\ 0.2\\ 0.2\\ 0.2\\ 0.1\\ 2.1\\ 85.5\end{tabular} \\\midrule \emph{change} & \begin{tabular}[c]{@{}l@{}}Take\\ Stop\\ Increase\\ Decrease\\ None\\ Other\end{tabular}& \begin{tabular}[c]{@{}l@{}}Take\\ Stop\\ Increase\\ Decrease\\ None\\ Other\end{tabular} & \begin{tabular}[c]{@{}l@{}}83.1\\ 6.5\\ 5.2\\ 2.0\\ 1.6\\ 1.4\end{tabular} \\ \bottomrule \end{tabular} } \caption{Complete set of normalized classification labels for all three medication attributes and their explanation} \label{tab:class labels detailed} \end{table*} \subsection{Hyperparameters} \label{app:hyperparams} We use AllenNLP \cite{allennlp} to implement our models and Weights\&Biases \cite{wandb} to manage our experiments. Following is the list of hyperparameters used in our experiments: \begin{enumerate} \item \textbf{Contextualized Token Embedder: } We use 1024-dimensional 24-layer \texttt{bert-large-cased} obtained as a pre-trained model from HuggingFace\footnote{\url{https://huggingface.co/bert-large-cased}}. We freeze the weights of the embedder in our training. The max sequence length is set to 256. \item \textbf{Speaker embedding: } 2-dimensional trainable embedding with vocabulary size of 4 as we only have 4 unique speakers in our dataset: doctor, patient, caregiver and nurse. \item \textbf{Softmax and Fusedmax: }The temperatures of softmax and fusedmax are set to a default value of 1. The sparsity weight of fusedmax is also set to its default value of 1 for all attributes. \item \textbf{TAScore: } The transformer used in TAScore is a 2-layer transformer encoder where each layer is implemented as in \citet{attention-is-all}. Both the hidden dimensions inside the transformer (self-attention and feedforward) are set to 32 and all the dropout probabilities are set to 0.2. The linear layer for the query has input and output dimensions of 1024 and 32, respectively. Due to the concatenation of speaker embedding, the linear layer for keys has input and output dimensions of 1026 and 32, respectively. The feedforward layer (which generates scalar scores for each token) on top of the transformer is 2-layered with relu activations and hidden sizes (16, 1). \item \textbf{Classifiers: } The final classifier for each attribute is a 2-layer feedforward network with hidden sizes (512, ``number of classes for the attribute'') and dropout probability of 0.2. \end{enumerate} \subsection{Examples: Projection Functions} \label{app:examples projection} Figures \ref{fig:examples softmax} and \ref{fig:examples fusedmax} show examples of outputs of projection functions softmax and fusedmax on random input scores. \begin{figure*} \centering \subfloat[Positive and negative scores]{\includegraphics[width = \textwidth]{images/softmax1.png}}\\ \subfloat[Positive scores only]{\includegraphics[width = \textwidth]{images/softmax2}}\\ \subfloat[More uniformly distributed positive scores]{\includegraphics[width = \textwidth]{images/softmax3.png}} \caption{Sample outputs (right column) of softmax function on random input scores (left column).} \label{fig:examples softmax} \end{figure*} \begin{figure*} \centering \subfloat[Positive and negative scores]{\includegraphics[width = \textwidth]{images/fusedmax1.png}}\\ \subfloat[Positive scores only]{\includegraphics[width = \textwidth]{images/fusedmax2}}\\ \subfloat[More uniformly distributed positive scores]{\includegraphics[width = \textwidth]{images/fusedmax3.png}} \caption{Sample outputs (right column) of fusedmax function on random input scores (left column).} \label{fig:examples fusedmax} \end{figure*} \subsection{Phrase based extraction baseline} \label{app:phrase based} We implement a phrase based extraction system to provide a baseline for the extraction task. A lexicon of relevant phrases is created for each class for each attribute as shown in Table \ref{tab:phrase based phrases}. We then look for string matches within these phrases and the text for the data-point. If there are matches then the longest match is considered as an extraction span for that attribute. \begin{table*}[] \centering \begin{tabular}{|l|l|l|} \hline Attribute & Class & Phrases \\ \hline \multirow{11}{*}{freq} & Every Morning & everyday in the morning \textbar{} every morning \textbar{} morning~ \\ \cline{2-3} & At Bedtime & \begin{tabular}[c]{@{}l@{}}everyday before sleeping \textbar{} everyday after dinner \textbar{}\\~every night \textbar{} after dinner \textbar{}\\~at bedtime \textbar{} before sleeping\end{tabular} \\ \cline{2-3} & Twice a day & \begin{tabular}[c]{@{}l@{}}twice a day \textbar{} 2 times a day \textbar{} two times a day \textbar{}\\~2 times per day \textbar{} two times per day\end{tabular} \\ \cline{2-3} & Three times a day & 3 times a day \textbar{} 3 times per day \textbar{} 3 times every day \\ \cline{2-3} & Every six hours & every 6 hours \textbar{} every six hours \\ \cline{2-3} & Every week & every week \textbar{} weekly \textbar{} once a week \\ \cline{2-3} & Twice a week & \begin{tabular}[c]{@{}l@{}}twice a week \textbar{} two times a week \textbar{}~\\2 times a week \textbar{} twice per week \textbar{} two times per week \textbar{}~\\2 times per week\end{tabular} \\ \cline{2-3} & Three times a week & 3 times a week \textbar{} 3 times per week \\ \cline{2-3} & Every month & every month \textbar{} monthly \textbar{} once a month \\ \cline{2-3} & Other & \\ \cline{2-3} & None & \\ \hline \multirow{9}{*}{route} & Pill & tablet \textbar{} pill \textbar{} capsule \textbar{} mg \\ \cline{2-3} & Injection & pen \textbar{} shot \textbar{} injector \textbar{} injection \textbar{} inject \\ \cline{2-3} & Topical cream & cream \textbar{} gel \textbar{} ointment \textbar{} lotion \\ \cline{2-3} & Nasal spray & spray \textbar{} nasal conversation transcript. \\ \cline{2-3} & Medicated patch & patch \\ \cline{2-3} & Ophthalmic solution & ophthalmic \textbar{} drops \textbar{} drop \\ \cline{2-3} & Oral solution & oral solution \\ \cline{2-3} & Other & \\ \cline{2-3} & None & \\ \hline \multirow{6}{*}{change} & Take & take \textbar{} start \textbar{} put you on \textbar{} continue \\ \cline{2-3} & Stop & stop \textbar{} off \\ \cline{2-3} & Increase & increase \\ \cline{2-3} & Decrease & reduce \textbar{} decrease \\ \cline{2-3} & Other & \\ \cline{2-3} & None & \\ \hline \end{tabular} \caption{Phrases used in the phrase based baseline. These are also the most frequently occurring phrases in the free-form annotations.} \label{tab:phrase based phrases} \end{table*} \section{Background} \label{sec:approach} There have been several successful attempts to use neural attention \cite{Bahdanau2015NeuralMT} to extract information from text in an unsupervised manner \cite{neural-attn-for-aspect-extraction, neural-relation-extraction, yu2019beyond}. Attention scores provide a good proxy for importance of a particular token in a model. However, when there are multiple layers of attention, or if the encoder is too complex and trainable, the model no longer provides a way to produce reliable and faithful importance scores \cite{attention-is-not-explanation}. We argue that, in order to bring in the faithfulness, we need to create an attention bottleneck in our classification + extraction model. The attention bottleneck is achieved by employing an attention function which generates a set of attention weights over the encoded input tokens. Attention bottleneck forces the classifier \emph{to only see} the portions of input that pass through it, thereby enabling us to trade the classification performance for extraction performance and getting span extraction with weak supervision from classification labels. In the rest of this section, we provide general background on neural attention and present its variants employed in this work. This is followed by the presentation of our complete model architecture in the subsequent sections. \subsection{Neural Attention} \label{sec:attention} Given a query $\mathbf{q} \in \mathbb{R}^m$ and keys $\mathbf{K} \in \mathbb{R}^{l\times n}$, the attention function $\alpha \colon \mathbb{R}^m \times \mathbb{R}^{l\times n} \to \Delta^l$ is composed of two functions: a scoring function $\mathcal{S} \colon \mathbb{R}^m \times \mathbb{R}^{l\times n} \to \mathbb{R}^l$ which produces unnormalized importance scores, and a projection function $\Pi \colon \mathbb{R}^l \to \Delta^l$ which normalizes these scores by projecting them to an $(l-1)$-dimensional probability simplex.\footnote{Throughout this work $l$ represents the sequence length dimension and $\Delta^l=\{\mathbf{x} \in \mathbb{R}^l ~|~ \mathbf{x}>0, \Vert \mathbf{x}\Vert_1 =1 \}$ represents a probability simplex.} \subsubsection{Scoring Function} \label{sec:scoring function} The purpose of the scoring function is to produce importance scores for each entry in the key $\mathbf{K}$ w.r.t the query $\mathbf{q}$ for the task at hand, which in our case is classification. We experiment with two scoring functions: additive and transformer-based. \smallskip \noindent\textbf{Additive: } This is same as the scoring function used in \citet{Bahdanau2015NeuralMT}, where the scores are produced as follows: \begin{align*} s_j = \mathbf{v}^{T} \tanh (\mathbf{W}_q~ \mathbf{q} + \mathbf{W}_k~ \mathbf{k}_j)~, \end{align*} \noindent where, $\mathbf{v} \in \mathbb{R}^m$, $\mathbf{W}_q \in \mathbb{R}^{m\times m}$ and $\mathbf{W}_k \in \mathbb{R}^{m \times n}$ are trainable weights. \smallskip \noindent\textbf{Transformer-based Attention Score (TAScore): } While the additive scoring function is simple and easy to train, it suffers from one major drawback in our setting: since we freeze the weights of our embedder and do not use multiple layers of trainable attention (Section \ref{sec:training}), the additive attention can struggle to resolve references -- finding the correct attribute when there are multiple entities of interest, especially when there are multiple distinct medications (Section \ref{sec:effect of scoring}). For this reason, we propose a novel multi-layer transformer-based attention scoring function (TAScore) which can perform this reference resolution while also preserving the \emph{attention bottleneck}. Figure \ref{fig:transformer scorer} shows the architecture of TAScore. The query and key vectors are projected to the same space using two separate linear layers while also adding sinusoidal positional embeddings to the key vectors. A special trainable separator vector is added between the query and key vectors and the entire sequence is passed through a multi-layer transformer \cite{attention-is-all}. Finally, scalar scores (one corresponding to each vector in the key) are produced from the outputs of the transformer by passing them through a feed-forward layer with dropout. \begin{figure} \centering \includegraphics[height=150pt]{images/transformer_scorer.pdf} \caption{Architecture of TAScore. $\mathbf{q}$ and $\mathbf{K}$ are input query and keys, respectively, and $\mathbf{s}$ are the output scores.} \label{fig:transformer scorer} \end{figure} \subsubsection{Projection Function} \label{sec:projection function} A projection function $\Pi \colon \mathbb{R}^l \to \Delta^l$ in the context of attention distribution, normalizes the real valued importance scores by projecting them to an $(l-1)$-dimensional probability simplex $\Delta^l$. \citet{fusedmax} provide a unified view of the projection function as follows: \vspace{-1.2mm} \begin{align*} \Pi_{\Omega}(\mathbf{s}) = \argmax_{\mathbf{a} \in \Delta^l}~ \mathbf{a}^{T} \mathbf{s} - \gamma \Omega(\mathbf{a})~. \end{align*} \noindent Here, $\mathbf{a}\in \Delta^l$, $\gamma$ is a hyperparameter and $\Omega$ is a regularization penalty \newlyadded{which allows us to introduce problem specific inductive bias into our attention distribution}. When $\Omega$ is strongly convex, we have a closed form solution to the projection operation as well as its gradient \cite{fusedmax, learning-with-fenchel}. \newlyadded{Since we use the attention distribution to perform extraction}, we experiment with the following instances of projection functions in this work. \smallskip \noindent\textbf{Softmax:}~~ $\Omega(\mathbf{a}) = \sum^l_{i=1} a_i \log a_i$\\ Using the negative entropy as the regularizer, results in the usual softmax projection operator $\Pi_{\Omega}(\mathbf{s}) = \frac{\exp({\mathbf{s}/\gamma})}{\sum^l_{i=1} \exp({s_i/\gamma})}~.$ \smallskip \noindent\textbf{Fusedmax:} $\Omega(\mathbf{a}) = \frac{1}{2}\Vert\mathbf{a}\Vert^2_2 + \sum^l_{i=1}\left| a_{i+1} - a_{i}\right|$\\ Using squared loss with fused-lasso penalty \cite{fusedmax}, results in a projection operator which produces sparse as well as contiguous attention weights\footnote{Some example outputs of softmax and fusedmax on random inputs are shown in Appendix \ref{app:examples projection}}. The fusedmax projection operator can be written as $ \Pi_{\Omega}(\mathbf{s}) = P_{\Delta^l}\left(P_{TV}(s)\right),~~\textrm{where} $ $$ P_{TV}(\mathbf{s}) = \argmin_{\mathbf{y}\in\mathbb{R}^l}\Vert\mathbf{y}-\mathbf{s}\Vert_2^2 + \sum_{d=1}^{l-1} |y_{d+1} - y_d| $$ is the proximal operator for 1d Total Variation Denoising problem, and $P_{\Delta^l}$ is the euclidean projection operator. Both these operators can be computed non-iteratively as described in \citet{Condat2013} and \citet{Duchi}, respectively. The gradient of Fusedmax operator can be efficiently computed as described in \citet{fusedmax}.\footnote{The pytorch implementation to compute fusedmax used in this work is available at \url{https://github.com/dhruvdcoder/sparse-structured-attention}.} \smallskip \noindent\textbf{Fusedmax*:} We observe that while softmax learns to focus on the right region of text, it tends to assign very low attention weights to some tokens of phrases resulting in multiple discontinuous spans per attribute, while Fusedmax on the other hand, almost always generates contiguous attention weights. However, Fusedmax makes more mistakes in identifying the overall region that contains the target span (Section \ref{sec:effect of projection}). In order to combine the advantages of softmax and Fusedmax, we first train a model using softmax as the projector and then swap the softmax with Fusedmax in the final few epochs. We call this approach Fusedmax*. \section{Conclusion and Future work} \label{sec:conclusion} We provide a framework to perform MR attribute extraction from medical conversations with weak supervision using noisy classification labels. This is done by creating an attention bottleneck in the classification model and performing extraction using the attention weights. After experimenting with several variants of attention scoring and projection functions, we show that the combination of our transformer-based attention scoring function (TAScore) combined with Fusedmax* achieves significantly higher extraction performance compared to the other attention variants and a phrase-based baseline. While our proposed method achieves good performance, there is still room for improvement, especially for text with multiple medications. Data augmentation by swapping or masking medication names is worth exploring. An alternate direction of future work involves improving the naturalness of extracted spans. Auxiliary supervision using a language modeling objective would be a promising approach for this. \section{Credits} This document has been adapted by Yulan He from the instructions for earlier ACL and NAACL proceedings, including those for ACL 2020 by Steven Bethard, Ryan Cotterrell and Rui Yan, ACL 2019 by Douwe Kiela and Ivan Vuli\'{c}, NAACL 2019 by Stephanie Lukin and Alla Roskovskaya, ACL 2018 by Shay Cohen, Kevin Gimpel, and Wei Lu, NAACL 2018 by Margaret Michell and Stephanie Lukin, 2017/2018 (NA)ACL bibtex suggestions from Jason Eisner, ACL 2017 by Dan Gildea and Min-Yen Kan, NAACL 2017 by Margaret Mitchell, ACL 2012 by Maggie Li and Michael White, ACL 2010 by Jing-Shing Chang and Philipp Koehn, ACL 2008 by Johanna D. Moore, Simone Teufel, James Allan, and Sadaoki Furui, ACL 2005 by Hwee Tou Ng and Kemal Oflazer, ACL 2002 by Eugene Charniak and Dekang Lin, and earlier ACL and EACL formats written by several people, including John Chen, Henry S. Thompson and Donald Walker. Additional elements were taken from the formatting instructions of the \emph{International Joint Conference on Artificial Intelligence} and the \emph{Conference on Computer Vision and Pattern Recognition}. \section{Introduction} The following instructions are directed to authors of papers submitted to EMNLP 2020 or accepted for publication in its proceedings. All authors are required to adhere to these specifications. Authors are required to provide a Portable Document Format (PDF) version of their papers. \textbf{The proceedings are designed for printing on A4 paper.} \section{Electronically-available resources} ACL provides this description and accompanying style files at \begin{quote} \url{https://2020.emnlp.org/downloads/emnlp2020-templates.zip} \end{quote} We strongly recommend the use of these style files, which have been appropriately tailored for the EMNLP 2020 proceedings. \paragraph{\LaTeX-specific details:} The templates include the \LaTeX2e{} source (\texttt{\small emnlp2020.tex}), the \LaTeX2e{} style file used to format it (\texttt{\small emnlp2020.sty}), an ACL bibliography style (\texttt{\small acl\_natbib.bst}), an example bibliography (\texttt{\small emnlp2020.bib}), and the bibliography for the ACL Anthology (\texttt{\small anthology.bib}). \section{Length of Submission} \label{sec:length} The conference accepts submissions of long papers and short papers. Long papers may consist of up to eight (8) pages of content plus unlimited pages for references. Upon acceptance, final versions of long papers will be given one additional page -- up to nine (9) pages of content plus unlimited pages for references -- so that reviewers' comments can be taken into account. Short papers may consist of up to four (4) pages of content, plus unlimited pages for references. Upon acceptance, short papers will be given five (5) pages in the proceedings and unlimited pages for references. For both long and short papers, all illustrations and tables that are part of the main text must be accommodated within these page limits, observing the formatting instructions given in the present document. Papers that do not conform to the specified length and formatting requirements are subject to be rejected without review. The conference encourages the submission of additional material that is relevant to the reviewers but not an integral part of the paper. There are two such types of material: appendices, which can be read, and non-readable supplementary materials, often data or code. Additional material must be submitted as separate files, and must adhere to the same anonymity guidelines as the main paper. The paper must be self-contained: it is optional for reviewers to look at the supplementary material. Papers should not refer, for further detail, to documents, code or data resources that are not available to the reviewers. Refer to Appendices~\ref{sec:appendix} and \ref{sec:supplemental} for further information. Workshop chairs may have different rules for allowed length and whether supplemental material is welcome. As always, the respective call for papers is the authoritative source. \section{Anonymity} As reviewing will be double-blind, papers submitted for review should not include any author information (such as names or affiliations). Furthermore, self-references that reveal the author's identity, \emph{e.g.}, \begin{quote} We previously showed \citep{Gusfield:97} \ldots \end{quote} should be avoided. Instead, use citations such as \begin{quote} \citet{Gusfield:97} previously showed\ldots \end{quote} Please do not use anonymous citations and do not include acknowledgements. \textbf{Papers that do not conform to these requirements may be rejected without review.} Any preliminary non-archival versions of submitted papers should be listed in the submission form but not in the review version of the paper. Reviewers are generally aware that authors may present preliminary versions of their work in other venues, but will not be provided the list of previous presentations from the submission form. Once a paper has been accepted to the conference, the camera-ready version of the paper should include the author's names and affiliations, and is allowed to use self-references. \paragraph{\LaTeX-specific details:} For an anonymized submission, ensure that {\small\verb|\aclfinalcopy|} at the top of this document is commented out, and that you have filled in the paper ID number (assigned during the submission process on softconf) where {\small\verb|***|} appears in the {\small\verb|\def\aclpaperid{***}|} definition at the top of this document. For a camera-ready submission, ensure that {\small\verb|\aclfinalcopy|} at the top of this document is not commented out. \section{Multiple Submission Policy} Papers that have been or will be submitted to other meetings or publications must indicate this at submission time in the START submission form, and must be withdrawn from the other venues if accepted by EMNLP 2020. Authors of papers accepted for presentation at EMNLP 2020 must notify the program chairs by the camera-ready deadline as to whether the paper will be presented. We will not accept for publication or presentation the papers that overlap significantly in content or results with papers that will be (or have been) published elsewhere. Authors submitting more than one paper to EMNLP 2020 must ensure that submissions do not overlap significantly ($>$25\%) with each other in content or results. \section{Formatting Instructions} Manuscripts must be in two-column format. Exceptions to the two-column format include the title, authors' names and complete addresses, which must be centered at the top of the first page, and any full-width figures or tables (see the guidelines in Section~\ref{ssec:title-authors}). \textbf{Type single-spaced.} Start all pages directly under the top margin. The manuscript should be printed single-sided and its length should not exceed the maximum page limit described in Section~\ref{sec:length}. Pages should be numbered in the version submitted for review, but \textbf{pages should not be numbered in the camera-ready version}. \paragraph{\LaTeX-specific details:} The style files will generate page numbers when {\small\verb|\aclfinalcopy|} is commented out, and remove them otherwise. \subsection{File Format} \label{sect:pdf} For the production of the electronic manuscript you must use Adobe's Portable Document Format (PDF). Please make sure that your PDF file includes all the necessary fonts (especially tree diagrams, symbols, and fonts with Asian characters). When you print or create the PDF file, there is usually an option in your printer setup to include none, all or just non-standard fonts. Please make sure that you select the option of including ALL the fonts. \textbf{Before sending it, test your PDF by printing it from a computer different from the one where it was created.} Moreover, some word processors may generate very large PDF files, where each page is rendered as an image. Such images may reproduce poorly. In this case, try alternative ways to obtain the PDF. One way on some systems is to install a driver for a postscript printer, send your document to the printer specifying ``Output to a file'', then convert the file to PDF. It is of utmost importance to specify the \textbf{A4 format} (21 cm x 29.7 cm) when formatting the paper. Print-outs of the PDF file on A4 paper should be identical to the hardcopy version. If you cannot meet the above requirements about the production of your electronic submission, please contact the publication chairs as soon as possible. \paragraph{\LaTeX-specific details:} PDF files are usually produced from \LaTeX{} using the \texttt{\small pdflatex} command. If your version of \LaTeX{} produces Postscript files, \texttt{\small ps2pdf} or \texttt{\small dvipdf} can convert these to PDF. To ensure A4 format in \LaTeX, use the command {\small\verb|\special{papersize=210mm,297mm}|} in the \LaTeX{} preamble (below the {\small\verb|\usepackage|} commands) and use \texttt{\small dvipdf} and/or \texttt{\small pdflatex}; or specify \texttt{\small -t a4} when working with \texttt{\small dvips}. \subsection{Layout} \label{ssec:layout} Format manuscripts two columns to a page, in the manner these instructions are formatted. The exact dimensions for a page on A4 paper are: \begin{itemize} \item Left and right margins: 2.5 cm \item Top margin: 2.5 cm \item Bottom margin: 2.5 cm \item Column width: 7.7 cm \item Column height: 24.7 cm \item Gap between columns: 0.6 cm \end{itemize} \noindent Papers should not be submitted on any other paper size. If you cannot meet the above requirements about the production of your electronic submission, please contact the publication chairs above as soon as possible. \subsection{Fonts} For reasons of uniformity, Adobe's \textbf{Times Roman} font should be used. If Times Roman is unavailable, you may use Times New Roman or \textbf{Computer Modern Roman}. Table~\ref{font-table} specifies what font sizes and styles must be used for each type of text in the manuscript. \begin{table} \centering \begin{tabular}{lrl} \hline \textbf{Type of Text} & \textbf{Font Size} & \textbf{Style} \\ \hline paper title & 15 pt & bold \\ author names & 12 pt & bold \\ author affiliation & 12 pt & \\ the word ``Abstract'' & 12 pt & bold \\ section titles & 12 pt & bold \\ subsection titles & 11 pt & bold \\ document text & 11 pt &\\ captions & 10 pt & \\ abstract text & 10 pt & \\ bibliography & 10 pt & \\ footnotes & 9 pt & \\ \hline \end{tabular} \caption{\label{font-table} Font guide. } \end{table} \paragraph{\LaTeX-specific details:} To use Times Roman in \LaTeX2e{}, put the following in the preamble: \begin{quote} \small \begin{verbatim} \usepackage{times} \usepackage{latexsym} \end{verbatim} \end{quote} \subsection{Ruler} A printed ruler (line numbers in the left and right margins of the article) should be presented in the version submitted for review, so that reviewers may comment on particular lines in the paper without circumlocution. The presence or absence of the ruler should not change the appearance of any other content on the page. The camera ready copy should not contain a ruler. \paragraph{Reviewers:} note that the ruler measurements may not align well with lines in the paper -- this turns out to be very difficult to do well when the paper contains many figures and equations, and, when done, looks ugly. In most cases one would expect that the approximate location will be adequate, although you can also use fractional references (\emph{e.g.}, this line ends at mark $295.5$). \paragraph{\LaTeX-specific details:} The style files will generate the ruler when {\small\verb|\aclfinalcopy|} is commented out, and remove it otherwise. \subsection{Title and Authors} \label{ssec:title-authors} Center the title, author's name(s) and affiliation(s) across both columns. Do not use footnotes for affiliations. Place the title centered at the top of the first page, in a 15-point bold font. Long titles should be typed on two lines without a blank line intervening. Put the title 2.5 cm from the top of the page, followed by a blank line, then the author's names(s), and the affiliation on the following line. Do not use only initials for given names (middle initials are allowed). Do not format surnames in all capitals (\emph{e.g.}, use ``Mitchell'' not ``MITCHELL''). Do not format title and section headings in all capitals except for proper names (such as ``BLEU'') that are conventionally in all capitals. The affiliation should contain the author's complete address, and if possible, an electronic mail address. The title, author names and addresses should be completely identical to those entered to the electronical paper submission website in order to maintain the consistency of author information among all publications of the conference. If they are different, the publication chairs may resolve the difference without consulting with you; so it is in your own interest to double-check that the information is consistent. Start the body of the first page 7.5 cm from the top of the page. \textbf{Even in the anonymous version of the paper, you should maintain space for names and addresses so that they will fit in the final (accepted) version.} \subsection{Abstract} Use two-column format when you begin the abstract. Type the abstract at the beginning of the first column. The width of the abstract text should be smaller than the width of the columns for the text in the body of the paper by 0.6 cm on each side. Center the word \textbf{Abstract} in a 12 point bold font above the body of the abstract. The abstract should be a concise summary of the general thesis and conclusions of the paper. It should be no longer than 200 words. The abstract text should be in 10 point font. \subsection{Text} Begin typing the main body of the text immediately after the abstract, observing the two-column format as shown in the present document. Indent 0.4 cm when starting a new paragraph. \subsection{Sections} Format section and subsection headings in the style shown on the present document. Use numbered sections (Arabic numerals) to facilitate cross references. Number subsections with the section number and the subsection number separated by a dot, in Arabic numerals. \subsection{Footnotes} Put footnotes at the bottom of the page and use 9 point font. They may be numbered or referred to by asterisks or other symbols.\footnote{This is how a footnote should appear.} Footnotes should be separated from the text by a line.\footnote{Note the line separating the footnotes from the text.} \subsection{Graphics} Place figures, tables, and photographs in the paper near where they are first discussed, rather than at the end, if possible. Wide illustrations may run across both columns. Color is allowed, but adhere to Section~\ref{ssec:accessibility}'s guidelines on accessibility. \paragraph{Captions:} Provide a caption for every illustration; number each one sequentially in the form: ``Figure 1. Caption of the Figure.'' ``Table 1. Caption of the Table.'' Type the captions of the figures and tables below the body, using 10 point text. Captions should be placed below illustrations. Captions that are one line are centered (see Table~\ref{font-table}). Captions longer than one line are left-aligned (see Table~\ref{tab:accents}). \begin{table} \centering \begin{tabular}{lc} \hline \textbf{Command} & \textbf{Output}\\ \hline \verb|{\"a}| & {\"a} \\ \verb|{\^e}| & {\^e} \\ \verb|{\`i}| & {\`i} \\ \verb|{\.I}| & {\.I} \\ \verb|{\o}| & {\o} \\ \verb|{\'u}| & {\'u} \\ \verb|{\aa}| & {\aa} \\\hline \end{tabular} \begin{tabular}{lc} \hline \textbf{Command} & \textbf{Output}\\ \hline \verb|{\c c}| & {\c c} \\ \verb|{\u g}| & {\u g} \\ \verb|{\l}| & {\l} \\ \verb|{\~n}| & {\~n} \\ \verb|{\H o}| & {\H o} \\ \verb|{\v r}| & {\v r} \\ \verb|{\ss}| & {\ss} \\ \hline \end{tabular} \caption{Example commands for accented characters, to be used in, \emph{e.g.}, \BibTeX\ names.}\label{tab:accents} \end{table} \paragraph{\LaTeX-specific details:} The style files are compatible with the caption and subcaption packages; do not add optional arguments. \textbf{Do not override the default caption sizes.} \subsection{Hyperlinks} Within-document and external hyperlinks are indicated with Dark Blue text, Color Hex \#000099. \subsection{Citations} Citations within the text appear in parentheses as~\citep{Gusfield:97} or, if the author's name appears in the text itself, as \citet{Gusfield:97}. Append lowercase letters to the year in cases of ambiguities. Treat double authors as in~\citep{Aho:72}, but write as in~\citep{Chandra:81} when more than two authors are involved. Collapse multiple citations as in~\citep{Gusfield:97,Aho:72}. Refrain from using full citations as sentence constituents. Instead of \begin{quote} ``\citep{Gusfield:97} showed that ...'' \end{quote} write \begin{quote} ``\citet{Gusfield:97} showed that ...'' \end{quote} \begin{table*} \centering \begin{tabular}{lll} \hline \textbf{Output} & \textbf{natbib command} & \textbf{Old ACL-style command}\\ \hline \citep{Gusfield:97} & \small\verb|\citep| & \small\verb|\cite| \\ \citealp{Gusfield:97} & \small\verb|\citealp| & no equivalent \\ \citet{Gusfield:97} & \small\verb|\citet| & \small\verb|\newcite| \\ \citeyearpar{Gusfield:97} & \small\verb|\citeyearpar| & \small\verb|\shortcite| \\ \hline \end{tabular} \caption{\label{citation-guide} Citation commands supported by the style file. The style is based on the natbib package and supports all natbib citation commands. It also supports commands defined in previous ACL style files for compatibility. } \end{table*} \paragraph{\LaTeX-specific details:} Table~\ref{citation-guide} shows the syntax supported by the style files. We encourage you to use the natbib styles. You can use the command {\small\verb|\citet|} (cite in text) to get ``author (year)'' citations as in \citet{Gusfield:97}. You can use the command {\small\verb|\citep|} (cite in parentheses) to get ``(author, year)'' citations as in \citep{Gusfield:97}. You can use the command {\small\verb|\citealp|} (alternative cite without parentheses) to get ``author year'' citations (which is useful for using citations within parentheses, as in \citealp{Gusfield:97}). \subsection{References} Gather the full set of references together under the heading \textbf{References}; place the section before any Appendices. Arrange the references alphabetically by first author, rather than by order of occurrence in the text. Provide as complete a citation as possible, using a consistent format, such as the one for \emph{Computational Linguistics\/} or the one in the \emph{Publication Manual of the American Psychological Association\/}~\citep{APA:83}. Use full names for authors, not just initials. Submissions should accurately reference prior and related work, including code and data. If a piece of prior work appeared in multiple venues, the version that appeared in a refereed, archival venue should be referenced. If multiple versions of a piece of prior work exist, the one used by the authors should be referenced. Authors should not rely on automated citation indices to provide accurate references for prior and related work. The following text cites various types of articles so that the references section of the present document will include them. \begin{itemize} \item Example article in journal: \citep{Ando2005}. \item Example article in proceedings, with location: \citep{borschinger-johnson-2011-particle}. \item Example article in proceedings, without location: \citep{andrew2007scalable}. \item Example arxiv paper: \citep{rasooli-tetrault-2015}. \end{itemize} \paragraph{\LaTeX-specific details:} The \LaTeX{} and Bib\TeX{} style files provided roughly follow the American Psychological Association format. If your own bib file is named \texttt{\small emnlp2020.bib}, then placing the following before any appendices in your \LaTeX{} file will generate the references section for you: \begin{quote}\small \verb|\bibliographystyle{acl_natbib}|\\ \verb| \section{Introduction} \label{sec:intro} \gdef\@thefnmark{}\@footnotetext{Proceedings of the Clinical Natural Language Processing Workshop, EMNLP, 2020.} Patients forget 40-80\% of the medical information provided by healthcare practitioners immediately \citep{doi:10.1080/03610739608254020} and misconstrue 48\% of what they think they remembered \citep{10.1093/rheumatology/18.1.18}, and this adversely affects patient adherence. Automatically extracting information from doctor-patient conversations can help patients correctly recall doctor’s instructions and improve compliance with the care plan \cite{tsulukidze2014providing}. On the other hand, clinicians spend up to 49.2\% of their overall time on EHR and desk work, and only 27.0\% of their total time on direct clinical face time with patients \citep{sinsky2016allocation}. Increased data management work is also correlated with increased doctor burnout \citep{kumar2016burnout}. Information extracted from medical conversations can also aid doctors in their documentation work \citep{rajkomar2019automatically,ben2020soap}, allow them to spend more face time with the patients, and build better relationships. \begin{figure}[!t] \begin{tcolorbox}[width=\columnwidth] \begin{singlespacing} {\setstretch{1.2} \begin{dialogue} \small \speak{DR} Limiting your alcohol consumption is important, so, and, um, so, you know, I would recommend \hmed{vitamin D\textsuperscript{1}} \hstartstop{to be taken\textsuperscript{1}}. Have you had \hmed{Fosamax\textsuperscript{2}} before? \speak{PT} I think my mum did. \speak{DR} Okay, \hmed{Fosamax\textsuperscript{2}}, \hstartstop{you take\textsuperscript{2}} \hfreq{one \hroute{pill\textsuperscript{2}} on Monday and one on Thursday\textsuperscript{2}}. \speak{DR} Do you use much caffine? \speak{PT} No, none. \speak{DR} Okay, \hstartstop{this is\textsuperscript{3}} \hmed{Actonel\textsuperscript{3}} and it's \hfreq{one \hroute{tablet\textsuperscript{3}} once a month\textsuperscript{3}}. \speak{DR} Do you get a one month or a three months supply in your prescriptions? \end{dialogue} } \end{singlespacing} \end{tcolorbox} \caption{An example excerpt from a doctor-patient conversation transcript. Here, there are three \hmed{medications} mentioned indicated by the superscript. The extracted attributes, \hstartstop{change}, \hroute{route} and \hfreq{frequency}, for each medications are also shown. } \label{fig:dialogue} \end{figure} In this work, we focus on extracting Medication Regimen (MR) information \cite{du2019learning, selvaraj2019medication} from the doctor-patient conversations. Specifically, we extract three attributes, i.e., \emph{frequency}, \emph{route}~and \emph{change}, corresponding to medications discussed in the conversation (Figure \ref{fig:dialogue}). Medication Regimen information can help doctors with medication orders cum renewals, medication reconciliation, verification of reconciliations for errors, and other medication-centered EHR documentation tasks. It can also improve patient engagement, transparency and better compliance with the care plan \cite{tsulukidze2014providing, grande2017digital}. MR attribute information present in a conversation can be obtained as spans in text (Figure \ref{fig:dialogue}) or can be categorized into classification labels (Table \ref{tab:dataset example}). While the classification labels are easy to obtain at scale in an automated manner -- for instance, by pairing conversations with billing codes or medication orders -- they can be noisy and can result in a prohibitively large number of classes. Classification labels go through normalization and disambiguation, often resulting in label names which are very different from the phrases used in the conversation. This process leads to a loss of granular information present in the text (see, for example, row 2 in Table \ref{tab:dataset example}). Span extraction, on the other hand, alleviates this issue as the outputs are actual spans in the conversation. However, span extraction annotations are relatively hard to come by and are time-consuming to annotate manually. Hence, in this work, we look at the task of MR attribute span extraction from doctor-patient conversation using weak supervision provided by the noisy classification labels. The main contributions of this work are as follows. We present a way of setting up an MR attribute extraction task from noisy classification data (Section \ref{sec:task and data}). We propose a weakly supervised model architecture which utilizes attention bottleneck inside a classification model to perform span extraction (Section \ref{sec:approach} \& \ref{sec:model}). In order to favor sparse and contiguous extractions, we experiment with two variants of attention projection functions (Section \ref{sec:projection function}), namely, softmax and Fusedmax \cite{fusedmax}. Further, we propose a novel transformer-based attention scoring function TAScore (Section \ref{sec:scoring function}). The combination of TAScore and Fusedmax achieves significant improvements in extraction performance over a phrase-based (22 LCSF1 points) and additive softmax attention (10 LCSF1 points) baselines. \section*{Acknowledgments} We thank University of Pittsburgh Medical Center (UPMC) and Abridge AI Inc. for providing access to the de-identified data corpus. \section{Background} \label{sec:approach} There have been several successful attempts to use neural attention \cite{Bahdanau2015NeuralMT} to extract information from text in an unsupervised manner \cite{neural-attn-for-aspect-extraction, neural-relation-extraction, yu2019beyond}. Attention scores provide a good proxy for importance of a particular token in a model. However, when there are multiple layers of attention, or if the encoder is too complex and trainable, the model no longer provides a way to produce reliable and faithful importance scores \cite{attention-is-not-explanation}. We argue that, in order to bring in the faithfulness, we need to create an attention bottleneck in our classification + extraction model. The attention bottleneck is achieved by employing an attention function which generates a set of attention weights over the encoded input tokens. Attention bottleneck forces the classifier \emph{to only see} the portions of input that pass through it, thereby enabling us to trade the classification performance for extraction performance and getting span extraction with weak supervision from classification labels. In the rest of this section, we provide general background on neural attention and present its variants employed in this work. This is followed by the presentation of our complete model architecture in the subsequent sections. \subsection{Neural Attention} \label{sec:attention} Given a query $\mathbf{q} \in \mathbb{R}^m$ and keys $\mathbf{K} \in \mathbb{R}^{l\times n}$, the attention function $\alpha \colon \mathbb{R}^m \times \mathbb{R}^{l\times n} \to \Delta^l$ is composed of two functions: a scoring function $\mathcal{S} \colon \mathbb{R}^m \times \mathbb{R}^{l\times n} \to \mathbb{R}^l$ which produces unnormalized importance scores, and a projection function $\Pi \colon \mathbb{R}^l \to \Delta^l$ which normalizes these scores by projecting them to an $(l-1)$-dimensional probability simplex.\footnote{Throughout this work $l$ represents the sequence length dimension and $\Delta^l=\{\mathbf{x} \in \mathbb{R}^l ~|~ \mathbf{x}>0, \Vert \mathbf{x}\Vert_1 =1 \}$ represents a probability simplex.} \subsubsection{Scoring Function} \label{sec:scoring function} The purpose of the scoring function is to produce importance scores for each entry in the key $\mathbf{K}$ w.r.t the query $\mathbf{q}$ for the task at hand, which in our case is classification. We experiment with two scoring functions: additive and transformer-based. \smallskip \noindent\textbf{Additive: } This is same as the scoring function used in \citet{Bahdanau2015NeuralMT}, where the scores are produced as follows: \begin{align*} s_j = \mathbf{v}^{T} \tanh (\mathbf{W}_q~ \mathbf{q} + \mathbf{W}_k~ \mathbf{k}_j)~, \end{align*} \noindent where, $\mathbf{v} \in \mathbb{R}^m$, $\mathbf{W}_q \in \mathbb{R}^{m\times m}$ and $\mathbf{W}_k \in \mathbb{R}^{m \times n}$ are trainable weights. \smallskip \noindent\textbf{Transformer-based Attention Score (TAScore): } While the additive scoring function is simple and easy to train, it suffers from one major drawback in our setting: since we freeze the weights of our embedder and do not use multiple layers of trainable attention (Section \ref{sec:training}), the additive attention can struggle to resolve references -- finding the correct attribute when there are multiple entities of interest, especially when there are multiple distinct medications (Section \ref{sec:effect of scoring}). For this reason, we propose a novel multi-layer transformer-based attention scoring function (TAScore) which can perform this reference resolution while also preserving the \emph{attention bottleneck}. Figure \ref{fig:transformer scorer} shows the architecture of TAScore. The query and key vectors are projected to the same space using two separate linear layers while also adding sinusoidal positional embeddings to the key vectors. A special trainable separator vector is added between the query and key vectors and the entire sequence is passed through a multi-layer transformer \cite{attention-is-all}. Finally, scalar scores (one corresponding to each vector in the key) are produced from the outputs of the transformer by passing them through a feed-forward layer with dropout. \begin{figure} \centering \includegraphics[height=150pt]{images/transformer_scorer.pdf} \caption{Architecture of TAScore. $\mathbf{q}$ and $\mathbf{K}$ are input query and keys, respectively, and $\mathbf{s}$ are the output scores.} \label{fig:transformer scorer} \end{figure} \subsubsection{Projection Function} \label{sec:projection function} A projection function $\Pi \colon \mathbb{R}^l \to \Delta^l$ in the context of attention distribution, normalizes the real valued importance scores by projecting them to an $(l-1)$-dimensional probability simplex $\Delta^l$. \citet{fusedmax} provide a unified view of the projection function as follows: \vspace{-1.2mm} \begin{align*} \Pi_{\Omega}(\mathbf{s}) = \argmax_{\mathbf{a} \in \Delta^l}~ \mathbf{a}^{T} \mathbf{s} - \gamma \Omega(\mathbf{a})~. \end{align*} \noindent Here, $\mathbf{a}\in \Delta^l$, $\gamma$ is a hyperparameter and $\Omega$ is a regularization penalty \newlyadded{which allows us to introduce problem specific inductive bias into our attention distribution}. When $\Omega$ is strongly convex, we have a closed form solution to the projection operation as well as its gradient \cite{fusedmax, learning-with-fenchel}. \newlyadded{Since we use the attention distribution to perform extraction}, we experiment with the following instances of projection functions in this work. \smallskip \noindent\textbf{Softmax:}~~ $\Omega(\mathbf{a}) = \sum^l_{i=1} a_i \log a_i$\\ Using the negative entropy as the regularizer, results in the usual softmax projection operator $\Pi_{\Omega}(\mathbf{s}) = \frac{\exp({\mathbf{s}/\gamma})}{\sum^l_{i=1} \exp({s_i/\gamma})}~.$ \smallskip \noindent\textbf{Fusedmax:} $\Omega(\mathbf{a}) = \frac{1}{2}\Vert\mathbf{a}\Vert^2_2 + \sum^l_{i=1}\left| a_{i+1} - a_{i}\right|$\\ Using squared loss with fused-lasso penalty \cite{fusedmax}, results in a projection operator which produces sparse as well as contiguous attention weights\footnote{Some example outputs of softmax and fusedmax on random inputs are shown in Appendix \ref{app:examples projection}}. The fusedmax projection operator can be written as $ \Pi_{\Omega}(\mathbf{s}) = P_{\Delta^l}\left(P_{TV}(s)\right),~~\textrm{where} $ $$ P_{TV}(\mathbf{s}) = \argmin_{\mathbf{y}\in\mathbb{R}^l}\Vert\mathbf{y}-\mathbf{s}\Vert_2^2 + \sum_{d=1}^{l-1} |y_{d+1} - y_d| $$ is the proximal operator for 1d Total Variation Denoising problem, and $P_{\Delta^l}$ is the euclidean projection operator. Both these operators can be computed non-iteratively as described in \citet{Condat2013} and \citet{Duchi}, respectively. The gradient of Fusedmax operator can be efficiently computed as described in \citet{fusedmax}.\footnote{The pytorch implementation to compute fusedmax used in this work is available at \url{https://github.com/dhruvdcoder/sparse-structured-attention}.} \smallskip \noindent\textbf{Fusedmax*:} We observe that while softmax learns to focus on the right region of text, it tends to assign very low attention weights to some tokens of phrases resulting in multiple discontinuous spans per attribute, while Fusedmax on the other hand, almost always generates contiguous attention weights. However, Fusedmax makes more mistakes in identifying the overall region that contains the target span (Section \ref{sec:effect of projection}). In order to combine the advantages of softmax and Fusedmax, we first train a model using softmax as the projector and then swap the softmax with Fusedmax in the final few epochs. We call this approach Fusedmax*. \section{Model} \label{sec:model} Our classification + extraction model uses MR attributes classification labels to extract MR attributes. The model can be divided into three phases: identify, classify and extract (Figure \ref{fig:model_overview}). The identify phases encodes the input text and medication name and uses the attention bottleneck to produce attention over the text. Classify phase computes the context vector using the attention from the identify phases and classifies the context vectors. Finally, the extract phase uses the attention from the identify phase to extract spans corresponding to MR attributes. \noindent\textbf{Notation}: Let the dataset $\mathcal{D}$ be $\{(\mathbf{x^{(1)}}, \mathbf{y^{(1)}}), \dots (\mathbf{x^{(N)}}, \mathbf{y^{(N)}}) \}$. Each $\mathbf{x}$ consists of a medication $m$ and conversation text $\mathbf{t}$, and each $\mathbf{y}$ consists of classification labels for \emph{frequency}, \emph{route}~and \emph{change}, i.e, $\mathbf{y} = (^fy, ^ry, ^cy)$, respectively. The number of classes for each attribute is denoted by $^{(\cdot)}n$. As seen from Table \ref{tab:class labels}, $^fn=12$, $^rn=10$ and $^cn=8$. The length of a text excerpt is denoted by $l$. The extracted span for attribute $k\in\{f,r,c\}$ is denoted by a binary vector $^{k}\mathbf{e}$ of length $l$, such that $^{k}e_j =1$, if $j^{\text{th}}$ token is in the extracted span for attribute $k$. \begin{figure}[] \centering \includegraphics[height=70mm,width=0.40\textwidth]{images/medication_attributes_extraction_v1_4.pdf} \caption{Complete model for weakly supervised MR attribute extraction.} \label{fig:model_overview} \end{figure} \subsection{Identify} \label{sec:model:identify} As shown in the Figure \ref{fig:model_overview}, the \emph{identify} phase finds the most relevant parts of the text w.r.t each of the three attributes. For this, we first encode the text as well as the given medication using a contextualized token embedder $\mathcal{E}$. In our case, this is 1024 dimensional BERT \cite{devlin-etal-2019-bert}\footnote{The pre-trained weight for BERT is from the HuggingFace library\cite{huggingface} }. Since BERT uses WordPiece representations \cite{wordpiece}, we average these wordpiece representations to form the word embeddings. In order to supply the speaker information, we concatenate a 2-dimensional fixed vocabulary speaker embedding to every token embedding in the text to obtain speaker-aware word representations. We then perform average pooling of the medication representations to get a single vector representation for the medication\footnote{Most medication names are single word, however a few medicines have names which are upto 4-5 words.}. Finally, with the given medication representation as the query and the speaker-aware token representations as the key, we use three separate attention functions (attention bottleneck), one for each attribute (no weight sharing), to produce three sets of normalized attention distributions $^f\mathbf{\hat{a}}$, $^r\mathbf{\hat{a}}$ and $^c\mathbf{\hat{a}}$ over the tokens of the text. The \emph{identify} phase can be succinctly described as follows: \begin{align*} ^k\mathbf{a} = {^k\alpha}(\mathcal{E}(m), \mathcal{E}(t))~,~~\text{where } k \in \{f, r, c\} \end{align*} Here, each $^k\mathbf{\hat{a}}$ is an element of the probability simplex $\Delta^l$ and is used to perform attribute extraction (Section \ref{sec:extract}). \subsection{Classify} \label{sec:model:classify} We obtain the attribute-wise context vectors~$^k\mathbf{c}$, as the weighted sum of the encoded tokens ($\mathbf{K}$ in Figure \ref{fig:model_overview}) where the weights are given by the attribute-wise attention distributions $^k\mathbf{a}$. To perform the classification for each attribute, the attribute-wise context vectors are used as input to feed-forward neural networks $\mathcal{F}_k$ (one per attribute), as shown below:\footnote{Complete set of hyperparameters used is given in Appendix \ref{app:hyperparams} \begin{align*} ^k\mathbf{p} &= \text{softmax}\left(\mathcal{F}_k(^k\mathbf{c})\right)\\ ^k\hat{y} &= \argmax_{j \in \{1,2,\dots, ^kn\}} {^kp_j}~,~~\text{where } k \in \{f, r, c\}. \end{align*} \subsection{Extract} \label{sec:extract} The spans are extracted from the attention distribution using a fixed extraction function $\mathcal{X}\colon \Delta^l \to \{0,1\}^l$, defined as: \begin{align*} ^k\hat{e}_j=\mathcal{X}_k(^k\mathbf{a})_j &= \begin{cases} 1 & \text{if } {^ka}_j > {^k\gamma} \\ 0 & \text{if } {^ka}_j \leq {^k\gamma}~, \end{cases} \end{align*} \noindent where $^k\gamma$ is the extraction threshold for attribute $k$. For softmax projection function, it is important to tune the attribute-wise extraction thresholds $\mathbf{\gamma}$. We tune these using extraction performance on the extraction validation set. For fusedmax projection function which produces spare weights, the thresholds need not be tuned, and hence are set to $0$. \subsection{Training} \label{sec:training} We train the model end-to-end using gradient descent, except the \emph{extract} module (Figure \ref{fig:model_overview}), which does not have any trainable weights, and the embedder $\mathcal{E}$. {Freezing the embedder is vital for the performance, since not doing so results in excessive dispersion of token information to other nearby tokens, resulting in poor extractions.} \smallskip The total loss for the training is divided into two parts as described below. \noindent\textbf{(1) Classification Loss $\mathcal{L}_c$: } In order to perform classification with highly class imbalanced data (see Table \ref{tab:class labels}), we use weighted cross-entropy: \begin{align*} \mathcal{L}_c &= \sum_{k \in \{ f, r, c\}} - ~{^kw_{^ky}}~ \log \left({^kp_{^ky}}\right)~, \end{align*} \noindent where the class weights ${^kw_{^ky}}$ are obtained by inverting each class' relative proportion. \smallskip \noindent\textbf{(2) Identification Loss $\mathcal{L}_i$: }If span labels $\mathbf{{e}}$ are present for some subset $\mathcal{A}$ of training examples, we first normalize these into ground truth attention probabilities $\mathbf{a}$: \begin{align*} ^ka_j &= \frac{^ke_j}{\sum^l_{j=1} {^ke_j}} ~~~\text{~~for~~} k \in \{f,r,c\} \end{align*} \noindent We then use KL-Divergence between the ground truth attention probabilities and the ones generated by the model ($\mathbf{\hat{a}}$) to compute identification loss $\mathcal{L}_i = \sum_{k \in \{ f, r, c\}} ~ \text{KL}\left(^k\mathbf{{a}} \Big\Vert {^k\mathbf{\hat{a}}}\right)$. Note that $\mathcal{L}_i$ is zero for data-points that do not have span labels. Using these two loss functions, the overall loss $\mathcal{L} = \mathcal{L}_c + \lambda \mathcal{L}_i$. \section{Medication Regimen (MR) using Weak Supervision} \label{sec:task and data} Medication Regimen (MR) consists of information about a prescribed medication akin to attributes of an entity. In this work, we specifically focus on \emph{frequency}, \emph{route}~of the medication and any \emph{change}~in the medication's \emph{dosage} or \emph{frequency}~ as shown in Figure \ref{fig:dialogue}. For example, given the conversation excerpt and the medication ``Fosamax'' as shown in Figure \ref{fig:dialogue}, the model needs to extract the spans ``one pill on Monday and one on Thursday'', ``pill'' and ``you take'' for attributes \emph{frequency}, \emph{route} ~and \emph{change}, respectively. The major challenge, however, is to perform the attribute span extraction using noisy classification labels with very few or no span-level labels. The rest of this section describes the dataset used for this task. \begin{table}[] \centering \resizebox{\columnwidth}{!}{% {\small \begin{tabular}{|l|l|} \toprule Attribute & Normalized Classes \\ \midrule \emph{frequency} & \begin{tabular}[c]{@{}l@{}}Daily \textbar{} Every morning \textbar{} At Bedtime \textbar{}\\Twice a day \textbar{} Three times a day \textbar{} Every six hours \textbar{}\\Every week \textbar{} Twice a week \textbar{} Three times a week \textbar{}\\Every month \textbar{} Other \textbar{} None \end{tabular} \\ \midrule \emph{route} & \begin{tabular}[c]{@{}l@{}}Pill \textbar{} Injection \textbar{} Topical cream \textbar{} Nasal spray \textbar{}\\Medicated patch \textbar{} Ophthalmic solution \textbar{} Inhaler \textbar{}\\Oral solution \textbar{} Other \textbar{} None \end{tabular} \\ \midrule \emph{change} & Take \textbar{} Stop \textbar{} Increase \textbar{} Decrease \textbar{} None \textbar{} Other \\ \bottomrule \end{tabular} } } \caption{The normalized labels in the classification data.} \label{tab:class labels} \end{table} \begin{table*}[] \centering \resizebox{\textwidth}{!}{% \begin{tabular}{@{}lcccc@{}} \toprule \multirow{2}{*}{\emph{text}} & \multirow{2}{*}{\emph{medication}} &\multicolumn{3}{c}{Classification labels} \\ \cmidrule(l){3-5} & & \multicolumn{1}{l}{\emph{frequency}} & \emph{route} & \emph{change} \\ \midrule \begin{tabular}[c]{@{}l@{}}{\small$\dots$ I would recommend vitamin D to be taken.}\\[-2mm] {\small Have you had Fosamax before?$\dots$}\end{tabular} & { vitamin D} & { none} & \multicolumn{1}{c}{{ none} } & take \\\midrule \begin{tabular}[c]{@{}l@{}}{\small$\dots$ I think my mum did. Okay, Fosamax, you take one pill on Monday}\\[-2mm] {\small and one on Thursday. Do you have much caffine? No, none$\dots$}\end{tabular} & Fosamax & Twice a week & \multicolumn{1}{c}{pill} & take \\\midrule \begin{tabular}[c]{@{}l@{}}{\small Do you have much caffine? No, none. Okay, this is Actonel and it's,}\\[-2mm] {\small one tablet once a month.$\dots$} \end{tabular} & Actonel & Once a month & \multicolumn{1}{c}{pill} & take \\ \bottomrule \end{tabular} } \caption{Classification examples resulting from the conversation shown in Figure \ref{fig:dialogue}.} \label{tab:dataset example} \end{table*} \subsection{Data} The data used in this paper comes from a collection of human transcriptions of 63000 fully-consented and de-identified doctor-patient conversations. A total of 57000 conversations were randomly selected to construct the training (and dev) conversation pool and the remaining 6000 conversations were reserved as the test pool. \smallskip \noindent\textbf{The classification dataset: }All the conversations are annotated with MR tags by expert human annotators. Each set of MR tags consists of the \emph{medication} name and its corresponding attributes \emph{frequency}, \emph{route}~ and \emph{change}, which are normalized free-form instructions in natural language phrases corresponding to each of the three attributes (see Table \ref{tab:phrase based phrases} in \ref{app:phrase based}). Each set of MR tags is grounded to a contiguous window of utterances' \emph{text},\footnote{The \emph{text} includes both the spoken words and the speaker information.} around a medication mention as evidence for that set. Hence, each set of grounded MR tags can be written as $<$\emph{medication}, \emph{text}, \emph{frequency}, \emph{route}, \emph{change}$>$, where the last three entries correspond to the three MR attributes. The free-form instructions for each attribute in the MR tags are normalized and categorized into manageable number of classification labels to avoid long tail and overlapping classes. This process results in classes shown in Table \ref{tab:class labels}.\footnote{The detailed explanation for each of the classes can be found in Table \ref{tab:class labels detailed} in Appendix \ref{app:data}.} As an illustration, this annotation process when applied to the conversation piece shown in Figure \ref{fig:dialogue} would result in the three data points shown in Table \ref{tab:dataset example}. Using this procedure on both the training and test conversation pools, we obtain 45,059 training, 11,212 validation and 5,458 test classification data points.\footnote{The dataset statistics are given in Appendix \ref{app:data}.} \smallskip \noindent\textbf{The extraction dataset: } Since the goal is to extract spans related to MR attributes, we would ideally need a dataset with span annotations to perform this task in a fully supervised manner. However, span annotation is laborious and expensive. Hence, we re-purpose the classification dataset (along with its classification labels) to perform the task of span extraction using weak supervision. We also manually annotate a small fraction of the train, validation and test sets (150, 150 and 500 data-points respectively) for attribute spans to see the effect of supplying a small number of strongly supervised instances on the performance of the model. In order to have a good representation of all the classes in the test set, we increase the sampling weight of data-points which have rare classes. Hence, our test set is relatively more difficult compared to a random sample of 500 data-points. All the results are reported on our test set of 500 difficult data-points annotated for attribute spans. For annotating attribute spans, the annotators were given instructions to mark spans which provide minimally sufficient and natural evidence for the already annotated attribute class as described below. \smallskip \noindent\textbf{Sufficiency:} Given only the annotated span for a particular attribute, one should be able to predict the correct classification label. This aims to encourage the attribute spans to cover all distinguishing information for that attribute. \noindent\textbf{Minimality: }Peripheral words which can be replaced with other words without changing the attribute's classification label should not be included in the extracted span. This aims to discourage marking entire utterances as attribute spans. \noindent\textbf{Naturalness: }The marked span(s) if presented to a human should sound like complete English phrases (if it has multiple tokens) or a meaningful word if it has only a single token. In essence, this means that the extractions should not drop stop words from within phrases. \newlyadded{This requirement aims to reduce the cognitive load on the human who uses the model's extraction output.} \subsection{Challenges} \label{sec:challenges} Using medical conversations for information extraction is more challenging compared to written doctor notes because the spontaneity of conversation gives rise to a variety of speech patterns with disfluencies and interruptions. Moreover, the vocabulary can range from colloquial to medical jargon. In addition, we also have noise in our classification dataset with its main source being annotators' use of information outside the grounded \emph{text} window to produce the free-form tags. This happens in two ways. First, when the free-form MR instructions are written using evidence that was discussed elsewhere in the conversation but is not present in the grounded \emph{text} window. Second, when the annotator uses their domain knowledge instead of using just the information in the grounded \emph{text} window -- for instance, when the \emph{route} of a \emph{medication} is not explicitly mentioned, the annotator might use the \emph{medication}`s common \emph{route} in their free-form instructions. Using manual analysis of the 800 data-points across the train, dev and test sets, we find that 22\% of \emph{frequency}, 36\% of \emph{route}~and 15\% of \emph{change}~ classification labels, have this noise. In this work, our approach to extraction depends on the size of the auxiliary task's (classification) dataset to overcome above mentioned challenges. \section{Conclusion and Future work} \label{sec:conclusion} We provide a framework to perform MR attribute extraction from medical conversations with weak supervision using noisy classification labels. This is done by creating an attention bottleneck in the classification model and performing extraction using the attention weights. After experimenting with several variants of attention scoring and projection functions, we show that the combination of our transformer-based attention scoring function (TAScore) combined with Fusedmax* achieves significantly higher extraction performance compared to the other attention variants and a phrase-based baseline. While our proposed method achieves good performance, there is still room for improvement, especially for text with multiple medications. Data augmentation by swapping or masking medication names is worth exploring. An alternate direction of future work involves improving the naturalness of extracted spans. Auxiliary supervision using a language modeling objective would be a promising approach for this. \section*{Acknowledgments} We thank University of Pittsburgh Medical Center (UPMC) and Abridge AI Inc. for providing access to the de-identified data corpus. \section{Credits} This document has been adapted by Yulan He from the instructions for earlier ACL and NAACL proceedings, including those for ACL 2020 by Steven Bethard, Ryan Cotterrell and Rui Yan, ACL 2019 by Douwe Kiela and Ivan Vuli\'{c}, NAACL 2019 by Stephanie Lukin and Alla Roskovskaya, ACL 2018 by Shay Cohen, Kevin Gimpel, and Wei Lu, NAACL 2018 by Margaret Michell and Stephanie Lukin, 2017/2018 (NA)ACL bibtex suggestions from Jason Eisner, ACL 2017 by Dan Gildea and Min-Yen Kan, NAACL 2017 by Margaret Mitchell, ACL 2012 by Maggie Li and Michael White, ACL 2010 by Jing-Shing Chang and Philipp Koehn, ACL 2008 by Johanna D. Moore, Simone Teufel, James Allan, and Sadaoki Furui, ACL 2005 by Hwee Tou Ng and Kemal Oflazer, ACL 2002 by Eugene Charniak and Dekang Lin, and earlier ACL and EACL formats written by several people, including John Chen, Henry S. Thompson and Donald Walker. Additional elements were taken from the formatting instructions of the \emph{International Joint Conference on Artificial Intelligence} and the \emph{Conference on Computer Vision and Pattern Recognition}. \section{Introduction} The following instructions are directed to authors of papers submitted to EMNLP 2020 or accepted for publication in its proceedings. All authors are required to adhere to these specifications. Authors are required to provide a Portable Document Format (PDF) version of their papers. \textbf{The proceedings are designed for printing on A4 paper.} \section{Electronically-available resources} ACL provides this description and accompanying style files at \begin{quote} \url{https://2020.emnlp.org/downloads/emnlp2020-templates.zip} \end{quote} We strongly recommend the use of these style files, which have been appropriately tailored for the EMNLP 2020 proceedings. \paragraph{\LaTeX-specific details:} The templates include the \LaTeX2e{} source (\texttt{\small emnlp2020.tex}), the \LaTeX2e{} style file used to format it (\texttt{\small emnlp2020.sty}), an ACL bibliography style (\texttt{\small acl\_natbib.bst}), an example bibliography (\texttt{\small emnlp2020.bib}), and the bibliography for the ACL Anthology (\texttt{\small anthology.bib}). \section{Length of Submission} \label{sec:length} The conference accepts submissions of long papers and short papers. Long papers may consist of up to eight (8) pages of content plus unlimited pages for references. Upon acceptance, final versions of long papers will be given one additional page -- up to nine (9) pages of content plus unlimited pages for references -- so that reviewers' comments can be taken into account. Short papers may consist of up to four (4) pages of content, plus unlimited pages for references. Upon acceptance, short papers will be given five (5) pages in the proceedings and unlimited pages for references. For both long and short papers, all illustrations and tables that are part of the main text must be accommodated within these page limits, observing the formatting instructions given in the present document. Papers that do not conform to the specified length and formatting requirements are subject to be rejected without review. The conference encourages the submission of additional material that is relevant to the reviewers but not an integral part of the paper. There are two such types of material: appendices, which can be read, and non-readable supplementary materials, often data or code. Additional material must be submitted as separate files, and must adhere to the same anonymity guidelines as the main paper. The paper must be self-contained: it is optional for reviewers to look at the supplementary material. Papers should not refer, for further detail, to documents, code or data resources that are not available to the reviewers. Refer to Appendices~\ref{sec:appendix} and \ref{sec:supplemental} for further information. Workshop chairs may have different rules for allowed length and whether supplemental material is welcome. As always, the respective call for papers is the authoritative source. \section{Anonymity} As reviewing will be double-blind, papers submitted for review should not include any author information (such as names or affiliations). Furthermore, self-references that reveal the author's identity, \emph{e.g.}, \begin{quote} We previously showed \citep{Gusfield:97} \ldots \end{quote} should be avoided. Instead, use citations such as \begin{quote} \citet{Gusfield:97} previously showed\ldots \end{quote} Please do not use anonymous citations and do not include acknowledgements. \textbf{Papers that do not conform to these requirements may be rejected without review.} Any preliminary non-archival versions of submitted papers should be listed in the submission form but not in the review version of the paper. Reviewers are generally aware that authors may present preliminary versions of their work in other venues, but will not be provided the list of previous presentations from the submission form. Once a paper has been accepted to the conference, the camera-ready version of the paper should include the author's names and affiliations, and is allowed to use self-references. \paragraph{\LaTeX-specific details:} For an anonymized submission, ensure that {\small\verb|\aclfinalcopy|} at the top of this document is commented out, and that you have filled in the paper ID number (assigned during the submission process on softconf) where {\small\verb|***|} appears in the {\small\verb|\def\aclpaperid{***}|} definition at the top of this document. For a camera-ready submission, ensure that {\small\verb|\aclfinalcopy|} at the top of this document is not commented out. \section{Multiple Submission Policy} Papers that have been or will be submitted to other meetings or publications must indicate this at submission time in the START submission form, and must be withdrawn from the other venues if accepted by EMNLP 2020. Authors of papers accepted for presentation at EMNLP 2020 must notify the program chairs by the camera-ready deadline as to whether the paper will be presented. We will not accept for publication or presentation the papers that overlap significantly in content or results with papers that will be (or have been) published elsewhere. Authors submitting more than one paper to EMNLP 2020 must ensure that submissions do not overlap significantly ($>$25\%) with each other in content or results. \section{Formatting Instructions} Manuscripts must be in two-column format. Exceptions to the two-column format include the title, authors' names and complete addresses, which must be centered at the top of the first page, and any full-width figures or tables (see the guidelines in Section~\ref{ssec:title-authors}). \textbf{Type single-spaced.} Start all pages directly under the top margin. The manuscript should be printed single-sided and its length should not exceed the maximum page limit described in Section~\ref{sec:length}. Pages should be numbered in the version submitted for review, but \textbf{pages should not be numbered in the camera-ready version}. \paragraph{\LaTeX-specific details:} The style files will generate page numbers when {\small\verb|\aclfinalcopy|} is commented out, and remove them otherwise. \subsection{File Format} \label{sect:pdf} For the production of the electronic manuscript you must use Adobe's Portable Document Format (PDF). Please make sure that your PDF file includes all the necessary fonts (especially tree diagrams, symbols, and fonts with Asian characters). When you print or create the PDF file, there is usually an option in your printer setup to include none, all or just non-standard fonts. Please make sure that you select the option of including ALL the fonts. \textbf{Before sending it, test your PDF by printing it from a computer different from the one where it was created.} Moreover, some word processors may generate very large PDF files, where each page is rendered as an image. Such images may reproduce poorly. In this case, try alternative ways to obtain the PDF. One way on some systems is to install a driver for a postscript printer, send your document to the printer specifying ``Output to a file'', then convert the file to PDF. It is of utmost importance to specify the \textbf{A4 format} (21 cm x 29.7 cm) when formatting the paper. Print-outs of the PDF file on A4 paper should be identical to the hardcopy version. If you cannot meet the above requirements about the production of your electronic submission, please contact the publication chairs as soon as possible. \paragraph{\LaTeX-specific details:} PDF files are usually produced from \LaTeX{} using the \texttt{\small pdflatex} command. If your version of \LaTeX{} produces Postscript files, \texttt{\small ps2pdf} or \texttt{\small dvipdf} can convert these to PDF. To ensure A4 format in \LaTeX, use the command {\small\verb|\special{papersize=210mm,297mm}|} in the \LaTeX{} preamble (below the {\small\verb|\usepackage|} commands) and use \texttt{\small dvipdf} and/or \texttt{\small pdflatex}; or specify \texttt{\small -t a4} when working with \texttt{\small dvips}. \subsection{Layout} \label{ssec:layout} Format manuscripts two columns to a page, in the manner these instructions are formatted. The exact dimensions for a page on A4 paper are: \begin{itemize} \item Left and right margins: 2.5 cm \item Top margin: 2.5 cm \item Bottom margin: 2.5 cm \item Column width: 7.7 cm \item Column height: 24.7 cm \item Gap between columns: 0.6 cm \end{itemize} \noindent Papers should not be submitted on any other paper size. If you cannot meet the above requirements about the production of your electronic submission, please contact the publication chairs above as soon as possible. \subsection{Fonts} For reasons of uniformity, Adobe's \textbf{Times Roman} font should be used. If Times Roman is unavailable, you may use Times New Roman or \textbf{Computer Modern Roman}. Table~\ref{font-table} specifies what font sizes and styles must be used for each type of text in the manuscript. \begin{table} \centering \begin{tabular}{lrl} \hline \textbf{Type of Text} & \textbf{Font Size} & \textbf{Style} \\ \hline paper title & 15 pt & bold \\ author names & 12 pt & bold \\ author affiliation & 12 pt & \\ the word ``Abstract'' & 12 pt & bold \\ section titles & 12 pt & bold \\ subsection titles & 11 pt & bold \\ document text & 11 pt &\\ captions & 10 pt & \\ abstract text & 10 pt & \\ bibliography & 10 pt & \\ footnotes & 9 pt & \\ \hline \end{tabular} \caption{\label{font-table} Font guide. } \end{table} \paragraph{\LaTeX-specific details:} To use Times Roman in \LaTeX2e{}, put the following in the preamble: \begin{quote} \small \begin{verbatim} \usepackage{times} \usepackage{latexsym} \end{verbatim} \end{quote} \subsection{Ruler} A printed ruler (line numbers in the left and right margins of the article) should be presented in the version submitted for review, so that reviewers may comment on particular lines in the paper without circumlocution. The presence or absence of the ruler should not change the appearance of any other content on the page. The camera ready copy should not contain a ruler. \paragraph{Reviewers:} note that the ruler measurements may not align well with lines in the paper -- this turns out to be very difficult to do well when the paper contains many figures and equations, and, when done, looks ugly. In most cases one would expect that the approximate location will be adequate, although you can also use fractional references (\emph{e.g.}, this line ends at mark $295.5$). \paragraph{\LaTeX-specific details:} The style files will generate the ruler when {\small\verb|\aclfinalcopy|} is commented out, and remove it otherwise. \subsection{Title and Authors} \label{ssec:title-authors} Center the title, author's name(s) and affiliation(s) across both columns. Do not use footnotes for affiliations. Place the title centered at the top of the first page, in a 15-point bold font. Long titles should be typed on two lines without a blank line intervening. Put the title 2.5 cm from the top of the page, followed by a blank line, then the author's names(s), and the affiliation on the following line. Do not use only initials for given names (middle initials are allowed). Do not format surnames in all capitals (\emph{e.g.}, use ``Mitchell'' not ``MITCHELL''). Do not format title and section headings in all capitals except for proper names (such as ``BLEU'') that are conventionally in all capitals. The affiliation should contain the author's complete address, and if possible, an electronic mail address. The title, author names and addresses should be completely identical to those entered to the electronical paper submission website in order to maintain the consistency of author information among all publications of the conference. If they are different, the publication chairs may resolve the difference without consulting with you; so it is in your own interest to double-check that the information is consistent. Start the body of the first page 7.5 cm from the top of the page. \textbf{Even in the anonymous version of the paper, you should maintain space for names and addresses so that they will fit in the final (accepted) version.} \subsection{Abstract} Use two-column format when you begin the abstract. Type the abstract at the beginning of the first column. The width of the abstract text should be smaller than the width of the columns for the text in the body of the paper by 0.6 cm on each side. Center the word \textbf{Abstract} in a 12 point bold font above the body of the abstract. The abstract should be a concise summary of the general thesis and conclusions of the paper. It should be no longer than 200 words. The abstract text should be in 10 point font. \subsection{Text} Begin typing the main body of the text immediately after the abstract, observing the two-column format as shown in the present document. Indent 0.4 cm when starting a new paragraph. \subsection{Sections} Format section and subsection headings in the style shown on the present document. Use numbered sections (Arabic numerals) to facilitate cross references. Number subsections with the section number and the subsection number separated by a dot, in Arabic numerals. \subsection{Footnotes} Put footnotes at the bottom of the page and use 9 point font. They may be numbered or referred to by asterisks or other symbols.\footnote{This is how a footnote should appear.} Footnotes should be separated from the text by a line.\footnote{Note the line separating the footnotes from the text.} \subsection{Graphics} Place figures, tables, and photographs in the paper near where they are first discussed, rather than at the end, if possible. Wide illustrations may run across both columns. Color is allowed, but adhere to Section~\ref{ssec:accessibility}'s guidelines on accessibility. \paragraph{Captions:} Provide a caption for every illustration; number each one sequentially in the form: ``Figure 1. Caption of the Figure.'' ``Table 1. Caption of the Table.'' Type the captions of the figures and tables below the body, using 10 point text. Captions should be placed below illustrations. Captions that are one line are centered (see Table~\ref{font-table}). Captions longer than one line are left-aligned (see Table~\ref{tab:accents}). \begin{table} \centering \begin{tabular}{lc} \hline \textbf{Command} & \textbf{Output}\\ \hline \verb|{\"a}| & {\"a} \\ \verb|{\^e}| & {\^e} \\ \verb|{\`i}| & {\`i} \\ \verb|{\.I}| & {\.I} \\ \verb|{\o}| & {\o} \\ \verb|{\'u}| & {\'u} \\ \verb|{\aa}| & {\aa} \\\hline \end{tabular} \begin{tabular}{lc} \hline \textbf{Command} & \textbf{Output}\\ \hline \verb|{\c c}| & {\c c} \\ \verb|{\u g}| & {\u g} \\ \verb|{\l}| & {\l} \\ \verb|{\~n}| & {\~n} \\ \verb|{\H o}| & {\H o} \\ \verb|{\v r}| & {\v r} \\ \verb|{\ss}| & {\ss} \\ \hline \end{tabular} \caption{Example commands for accented characters, to be used in, \emph{e.g.}, \BibTeX\ names.}\label{tab:accents} \end{table} \paragraph{\LaTeX-specific details:} The style files are compatible with the caption and subcaption packages; do not add optional arguments. \textbf{Do not override the default caption sizes.} \subsection{Hyperlinks} Within-document and external hyperlinks are indicated with Dark Blue text, Color Hex \#000099. \subsection{Citations} Citations within the text appear in parentheses as~\citep{Gusfield:97} or, if the author's name appears in the text itself, as \citet{Gusfield:97}. Append lowercase letters to the year in cases of ambiguities. Treat double authors as in~\citep{Aho:72}, but write as in~\citep{Chandra:81} when more than two authors are involved. Collapse multiple citations as in~\citep{Gusfield:97,Aho:72}. Refrain from using full citations as sentence constituents. Instead of \begin{quote} ``\citep{Gusfield:97} showed that ...'' \end{quote} write \begin{quote} ``\citet{Gusfield:97} showed that ...'' \end{quote} \begin{table*} \centering \begin{tabular}{lll} \hline \textbf{Output} & \textbf{natbib command} & \textbf{Old ACL-style command}\\ \hline \citep{Gusfield:97} & \small\verb|\citep| & \small\verb|\cite| \\ \citealp{Gusfield:97} & \small\verb|\citealp| & no equivalent \\ \citet{Gusfield:97} & \small\verb|\citet| & \small\verb|\newcite| \\ \citeyearpar{Gusfield:97} & \small\verb|\citeyearpar| & \small\verb|\shortcite| \\ \hline \end{tabular} \caption{\label{citation-guide} Citation commands supported by the style file. The style is based on the natbib package and supports all natbib citation commands. It also supports commands defined in previous ACL style files for compatibility. } \end{table*} \paragraph{\LaTeX-specific details:} Table~\ref{citation-guide} shows the syntax supported by the style files. We encourage you to use the natbib styles. You can use the command {\small\verb|\citet|} (cite in text) to get ``author (year)'' citations as in \citet{Gusfield:97}. You can use the command {\small\verb|\citep|} (cite in parentheses) to get ``(author, year)'' citations as in \citep{Gusfield:97}. You can use the command {\small\verb|\citealp|} (alternative cite without parentheses) to get ``author year'' citations (which is useful for using citations within parentheses, as in \citealp{Gusfield:97}). \subsection{References} Gather the full set of references together under the heading \textbf{References}; place the section before any Appendices. Arrange the references alphabetically by first author, rather than by order of occurrence in the text. Provide as complete a citation as possible, using a consistent format, such as the one for \emph{Computational Linguistics\/} or the one in the \emph{Publication Manual of the American Psychological Association\/}~\citep{APA:83}. Use full names for authors, not just initials. Submissions should accurately reference prior and related work, including code and data. If a piece of prior work appeared in multiple venues, the version that appeared in a refereed, archival venue should be referenced. If multiple versions of a piece of prior work exist, the one used by the authors should be referenced. Authors should not rely on automated citation indices to provide accurate references for prior and related work. The following text cites various types of articles so that the references section of the present document will include them. \begin{itemize} \item Example article in journal: \citep{Ando2005}. \item Example article in proceedings, with location: \citep{borschinger-johnson-2011-particle}. \item Example article in proceedings, without location: \citep{andrew2007scalable}. \item Example arxiv paper: \citep{rasooli-tetrault-2015}. \end{itemize} \paragraph{\LaTeX-specific details:} The \LaTeX{} and Bib\TeX{} style files provided roughly follow the American Psychological Association format. If your own bib file is named \texttt{\small emnlp2020.bib}, then placing the following before any appendices in your \LaTeX{} file will generate the references section for you: \begin{quote}\small \verb|\bibliographystyle{acl_natbib}|\\ \verb| \section{Metrics} \label{sec:metrics} \noindent\textbf{Token-wise F1 (TF1)}: Each token in text is either part of the extracted span (positive class) for an attribute or not (negative class). Token-wise F1 score is the F1 score of the positive class obtained by considering all the tokens in the dataset as separate binary classification data points. TF1 is calculated separately for each attribute. \smallskip \noindent\textbf{Longest Common Substring F1 (LCSF1):} LCSF1 measures if the extracted spans, along with being part of the gold spans, are contiguous or not. Longest Common Substring (LCS) is the longest overlapping contiguous span of tokens between the predicted and gold spans. LCSF1 is defined as the harmonic mean of LCS-Recall and LCS-Precision which are defined per extraction as: \vspace{-3mm} {\small \begin{align*} \text{LCS-Recall} &= \frac{\text{\#tokens in LCS}}{\text{\#tokens in gold span}}\\ \text{LCS-Precision} &= \frac{\text{\#tokens in LCS}}{\text{\#tokens in predicted span}} \end{align*} }% \section{Results and Analysis} \label{sec: results and analysis} \label{sec:results} Table \ref{tab:all results} shows the results obtained by various combinations of attention scoring and projection functions on the task of MR attribute extraction in terms of the metrics defined in Section \ref{sec:metrics}. It also shows the classification F1 score to emphasize how the attention bottleneck affects classification performance. The first row shows how a simple phrase based extraction system would perform on the task.\footnote{The details about the phrase based baseline are presented in Appendix \ref{app:phrase based}} \subsection{Effect of Span labels} In order to see if having a small number of extraction training data-points (containing explicit span labels) helps the extraction performance, we annotate 150 (see Section \ref{sec:task and data} for how we sampled the datapoints) of the training data-points with span labels. As seen from Table \ref{tab:all results}, even a small number of examples with span labels ($\approx 0.3 \%$) help a lot with the extraction performance for all models. We think this trend might continue if we add more training span labels. We leave the finding of the right balance between annotation effort and extraction performance as a future direction to explore. \subsection{Effect of classification labels} In order to quantify the effect of performing the auxiliary task of classification along with the main task of extraction, we train the proposed model in three different settings. (1) The \textit{Classification Only} uses the complete dataset (\texttildelow45k) but only with the classification labels. (2) The \textit{Extraction Only} setting only uses the 150 training examples that have span labels. (3) Finally, the \textit{Classification+Extraction} setting uses the 45k examples with classification labels along with the 150 examples with the span labels to train the model. Table \ref{tab:effect joint model} (rows 2, 3 and 4) shows the effect of having classification labels and performing extraction and classification jointly using the proposed model. The model structure and the volume of the classification data (\texttildelow45k examples) makes the auxiliary task of classification extremely helpful for the main task of extraction, even with the presence of label noise. It is worth noting that the classification performance of the proposed method is also improved by explicit supervision to the extraction portion of the model (row 2 vs 4, Table \ref{tab:effect joint model}). In order to set a reference for classification performance, we train strong classification only models, one for each attribute, using pretrained BERT. These \textit{BERT Classifiers}, are implemented as described in \citet{devlin-etal-2019-bert} with input consisting of the text and medication name separated by a [SEP] token (row 1). Based on the improvements achieved in the classification performance using span annotations, we believe that having more span labels can further close the gap between the classification performance of the proposed model and the BERT Classifiers. However, this work focuses on extraction performance, hence improving the classification performance is left to future work. \subsection{Effect of projection function} \label{sec:effect of projection} While softmax with post-hoc threshold tuning achieves consistently higher TF1 compared to fusedmax (which does not require threshold tuning), the later achieves better LCSF1. We observe that while the attention function using softmax projection focuses on the correct portion of the text, it drops intermediate words, resulting in multiple discontinuous spans. Fusedmax on the other hand almost always produces contiguous spans. Figure \ref{fig:extraction examples} further illustrates this point using a test example. The training trick which we call fusedmax* swaps the softmax projection function with fusedmax during the final few epochs to combine the strengths of both softmax and fusedmax. This achieves high LCSF1 as well as TF1. \begin{figure}[h!] \centering \subfloat[BERT+TAScore+Fusedmax*]{\includegraphics[width = \columnwidth]{images/bert-transformer-fusedmax-from-softmax.png}}\\[-1mm] \subfloat[BERT+TAScore+Softmax]{\includegraphics[width = \columnwidth]{images/bert-transformer-softmax.png}} \vspace{-1mm} \caption{Difference in extracted spans for MR attributes with models that uses Fusedmax* and Softmax, for the medication Actonel. Blue: \emph{change}, green: \emph{route}~and yellow: \emph{frequency}. Refer Figure \ref{fig:dialogue} for ground-truth annotations.} \label{fig:extraction examples} \end{figure} \subsection{Effect of scoring function} \label{sec:effect of scoring} Table \ref{tab:effect of scorer} shows the percent change in the extraction F1 if we use TAScore instead of additive scoring (everything else being the same). As seen, there is a significant improvement irrespective of the projection function being used. \begin{table}[h!] \centering \resizebox{\columnwidth}{!}{% \begin{tabular}{@{}l|lll|lll@{}} \toprule \multirow{2}{*}{\begin{tabular}[c]{@{}l@{}}Scorer\end{tabular}} & \multicolumn{3}{l|}{TF1 ($\Delta$\%)} & \multicolumn{3}{l}{LCSF1 ($\Delta$\%)} \\ \cmidrule(l){2-7} & \begin{tabular}[c]{@{}l@{}}MM\\ (77.3)\end{tabular} & \begin{tabular}[c]{@{}l@{}}SM\\ (22.7)\end{tabular} & \begin{tabular}[c]{@{}l@{}}All\\ (100)\end{tabular} & \begin{tabular}[c]{@{}l@{}}MM\\ (77.3)\end{tabular} & \begin{tabular}[c]{@{}l@{}}SM\\ (22.7)\end{tabular} & \begin{tabular}[c]{@{}l@{}}All\\ (100)\end{tabular} \\ \midrule softmax & +11.1 & +10.6 & +10.6 & +6.5 & +6.6 & +6.3 \\ fusedmax & +12.1 & +8.3 & +11.5 & +16.4 & +15.5 & +13.9 \\ fusedmax* & +5.4 & +1.9 & +4.7 & +9.25 & +1.1 & +7.9 \\ \bottomrule \end{tabular}% } \caption{MR extraction improvement (\%) brought by TAScore over additive scorer in the full test set (All=100\%), and test subset with single medication (SM=22.7\%) and multiple medications (MM=77.3\%) in the \emph{text}.} \label{tab:effect of scorer} \end{table} The need for TAScore stems from the difficulty of the additive scoring function to resolve references between spans when there are multiple medications present. In order to measure the efficacy of TAScore for this problem, we divide the test set into two subsets: data-points which have multiple distinct medications in their text (MM) and data-points that have single medication only. As seen from the first two columns for both the metrics in Table \ref{tab:effect of scorer}, using TAScore instead of additive results in more improvement in the MM-subset compared to the SM-subset, showing that using transformer scorer does help with resolving references when multiple medications are present in the text. Figure \ref{fig:LCSF1 distribution} shows the distribution of Avg. LCSF1 (average across all three attributes). It can be seen that there are a significant number of datapoints in the MM subset which get LCSF1 of zero, showing that even when the transformer scorer achieves improvement on MM subset, it gets quite a lot of these data-points completely wrong. This shows that the there is still room for improvement. \begin{figure} \centering \includegraphics[width=.9\columnwidth]{images/LCSF1_distribution.png} \caption{Distribution of the Avg. LCSF1 for the best performing model (BERT+TAScore+Fusedmax*). A significant number ($\approx10\%$) of datapoints with multiple medication in their \emph{text} get LCSF1 of zero (1st bar).} \label{fig:LCSF1 distribution} \end{figure} \subsection{Discussion} In summary, our analysis reveals that Fusedmax/Fusedmax* favors contiguous extraction spans which is a necessity for our task. Irrespective of the projection function used, the proposed scoring function TAScore improves the extraction performance when compared to the popular additive scoring function. The proposed model architecture is able to establish a synergy between the classification and span extraction tasks where one improves the performance of the other. Overall, the proposed combination of TAScore and Fusedmax* achieves a 22 LCSF1 points improvement over the phrase-based baseline and 10 LCSF1 points improvement over the naive additive and softmax combination. \section{Related Work} \label{sec:related work} Existing literature directly related to our work can be bucketed into two categories -- related methods and related tasks. \smallskip \noindent\textbf{Methods: }The recent work on generating rationales/explanations for deep neural network based classification models \cite{Lei2016, Bastings2020, Paranjape2020} is closely related to ours in terms of the methods used. Most of these works use binary latent variables to perform extraction as an intermediate step before classification. Our work is closely related to \cite{Jain2020,zhong2019finegrained}, who use attention scores to generate rationales for classification models. These works, however, focus on generating \emph{faithful} and \emph{plausible} explanation for classification as opposed to extracting the spans for attributes of an entity, which is the focus of our work. Moreover, our method can be generalized to any number of attributes while all these methods would require a separate model for each attribute. \smallskip \noindent\textbf{Tasks: }Understanding doctor-patient conversations is starting to receive attention recently \cite{rajkomar2019automatically, ben2020soap}. \citet{selvaraj2019medication} performs MR extraction by framing the problem as a generative question answering task. This approach is not efficient at inference time -- it requires one forward pass for each attribute. Moreover, unlike a span extraction model, the generative model might produce hallucinated facts. \citet{du2019learning} obtain MR attributes as spans in text; however, they use a fully supervised approach which requires a large dataset with span-level labels. \section{Introduction} \label{sec:intro} \gdef\@thefnmark{}\@footnotetext{Proceedings of the Clinical Natural Language Processing Workshop, EMNLP, 2020.} Patients forget 40-80\% of the medical information provided by healthcare practitioners immediately \citep{doi:10.1080/03610739608254020} and misconstrue 48\% of what they think they remembered \citep{10.1093/rheumatology/18.1.18}, and this adversely affects patient adherence. Automatically extracting information from doctor-patient conversations can help patients correctly recall doctor’s instructions and improve compliance with the care plan \cite{tsulukidze2014providing}. On the other hand, clinicians spend up to 49.2\% of their overall time on EHR and desk work, and only 27.0\% of their total time on direct clinical face time with patients \citep{sinsky2016allocation}. Increased data management work is also correlated with increased doctor burnout \citep{kumar2016burnout}. Information extracted from medical conversations can also aid doctors in their documentation work \citep{rajkomar2019automatically,ben2020soap}, allow them to spend more face time with the patients, and build better relationships. \begin{figure}[!t] \begin{tcolorbox}[width=\columnwidth] \begin{singlespacing} {\setstretch{1.2} \begin{dialogue} \small \speak{DR} Limiting your alcohol consumption is important, so, and, um, so, you know, I would recommend \hmed{vitamin D\textsuperscript{1}} \hstartstop{to be taken\textsuperscript{1}}. Have you had \hmed{Fosamax\textsuperscript{2}} before? \speak{PT} I think my mum did. \speak{DR} Okay, \hmed{Fosamax\textsuperscript{2}}, \hstartstop{you take\textsuperscript{2}} \hfreq{one \hroute{pill\textsuperscript{2}} on Monday and one on Thursday\textsuperscript{2}}. \speak{DR} Do you use much caffine? \speak{PT} No, none. \speak{DR} Okay, \hstartstop{this is\textsuperscript{3}} \hmed{Actonel\textsuperscript{3}} and it's \hfreq{one \hroute{tablet\textsuperscript{3}} once a month\textsuperscript{3}}. \speak{DR} Do you get a one month or a three months supply in your prescriptions? \end{dialogue} } \end{singlespacing} \end{tcolorbox} \caption{An example excerpt from a doctor-patient conversation transcript. Here, there are three \hmed{medications} mentioned indicated by the superscript. The extracted attributes, \hstartstop{change}, \hroute{route} and \hfreq{frequency}, for each medications are also shown. } \label{fig:dialogue} \end{figure} In this work, we focus on extracting Medication Regimen (MR) information \cite{du2019learning, selvaraj2019medication} from the doctor-patient conversations. Specifically, we extract three attributes, i.e., \emph{frequency}, \emph{route}~and \emph{change}, corresponding to medications discussed in the conversation (Figure \ref{fig:dialogue}). Medication Regimen information can help doctors with medication orders cum renewals, medication reconciliation, verification of reconciliations for errors, and other medication-centered EHR documentation tasks. It can also improve patient engagement, transparency and better compliance with the care plan \cite{tsulukidze2014providing, grande2017digital}. MR attribute information present in a conversation can be obtained as spans in text (Figure \ref{fig:dialogue}) or can be categorized into classification labels (Table \ref{tab:dataset example}). While the classification labels are easy to obtain at scale in an automated manner -- for instance, by pairing conversations with billing codes or medication orders -- they can be noisy and can result in a prohibitively large number of classes. Classification labels go through normalization and disambiguation, often resulting in label names which are very different from the phrases used in the conversation. This process leads to a loss of granular information present in the text (see, for example, row 2 in Table \ref{tab:dataset example}). Span extraction, on the other hand, alleviates this issue as the outputs are actual spans in the conversation. However, span extraction annotations are relatively hard to come by and are time-consuming to annotate manually. Hence, in this work, we look at the task of MR attribute span extraction from doctor-patient conversation using weak supervision provided by the noisy classification labels. The main contributions of this work are as follows. We present a way of setting up an MR attribute extraction task from noisy classification data (Section \ref{sec:task and data}). We propose a weakly supervised model architecture which utilizes attention bottleneck inside a classification model to perform span extraction (Section \ref{sec:approach} \& \ref{sec:model}). In order to favor sparse and contiguous extractions, we experiment with two variants of attention projection functions (Section \ref{sec:projection function}), namely, softmax and Fusedmax \cite{fusedmax}. Further, we propose a novel transformer-based attention scoring function TAScore (Section \ref{sec:scoring function}). The combination of TAScore and Fusedmax achieves significant improvements in extraction performance over a phrase-based (22 LCSF1 points) and additive softmax attention (10 LCSF1 points) baselines. \section{While Writing} \todo{Add into} \sout{Some text} \points{ \begin{enumerate} \item Point1 \item Pont2 \end{enumerate} } Normal text \section{Appendices} \label{sec:appendix} \subsection{Data} \label{app:data} The complete set of \emph{normalized} classification labels for all three medication attributes and their meaning is shown in Table \ref{tab:class labels detailed}. Average statistics about the dataset are shown in Table \ref{tab:dataset description stats}. \begin{table}[!ht] \centering \begin{tabular}{@{}lllll@{}} \toprule & min & max & mean & $\sigma$ \\ \midrule \#utterances in \emph{text} & 3 & 20 & 7.8 & 2.3 \\ \#words in \emph{text} & 12 & 565 & 80.8 & 41.0 \\ \#words in \emph{freq} span & 1 & 21 & 4.4 & 2.6 \\ \#words in \emph{route} span & 1 & 9 & 1.5 & 1.0 \\ \#words in \emph{change} span & 1 & 34 & 6.8 & 4.9 \\ \bottomrule \end{tabular}% \caption{Statistics of extraction labels (\#words) and the corresponding \emph{text} } \label{tab:dataset description stats} \end{table} \begin{table*}[!ht] \centering \resizebox{\textwidth}{!}{% \begin{tabular}{@{}|l|l|l|l|@{}} \toprule Attribute & class & Meaning & class proportion \\ \midrule \emph{frequency} & \begin{tabular}[c]{@{}l@{}} Daily\\ Every morning\\ At Bedtime\\ Twice a day\\ Three times a day\\ Every six hours\\ Every week\\ Twice a week\\ Three times a week\\ Every month\\ Other\\ None\end{tabular} & \begin{tabular}[c]{@{}l@{}} Take the medication once a day (specific time not mentioned).\\ Take the medication once every morning.\\ At Bedtime\\ Twice a day\\ Three times a day\\ Every six hours\\ Every week\\ Twice a week\\ Three times a week\\ Every month\\ Other\\ None\end{tabular} & \begin{tabular}[c]{@{}l@{}} 8.0 \\ 0.9\\ 1.7\\ 6.5\\ 1.6\\ 0.2\\ 0.9\\ 0.2\\ 0.3\\ 0.3\\ 1.5\\ 77.9\end{tabular} \\\midrule \emph{route} & \begin{tabular}[c]{@{}l@{}}Pill\\ Injection\\ Topical cream\\ Nasal spray\\ Medicated patch\\ Ophthalmic solution\\ Inhaler\\ Oral solution\\ Other\\ None\end{tabular} & \begin{tabular}[c]{@{}l@{}}Pill\\ Injection\\ Topical cream\\ Nasal spray\\ Medicated patch\\ Ophthalmic solution\\ Inhaler\\ Oral solution\\ Other\\ None\end{tabular} & \begin{tabular}[c]{@{}l@{}}6.8\\ 3.5\\ 1.0\\ 0.5\\ 0.2\\ 0.2\\ 0.2\\ 0.1\\ 2.1\\ 85.5\end{tabular} \\\midrule \emph{change} & \begin{tabular}[c]{@{}l@{}}Take\\ Stop\\ Increase\\ Decrease\\ None\\ Other\end{tabular}& \begin{tabular}[c]{@{}l@{}}Take\\ Stop\\ Increase\\ Decrease\\ None\\ Other\end{tabular} & \begin{tabular}[c]{@{}l@{}}83.1\\ 6.5\\ 5.2\\ 2.0\\ 1.6\\ 1.4\end{tabular} \\ \bottomrule \end{tabular} } \caption{Complete set of normalized classification labels for all three medication attributes and their explanation} \label{tab:class labels detailed} \end{table*} \subsection{Hyperparameters} \label{app:hyperparams} We use AllenNLP \cite{allennlp} to implement our models and Weights\&Biases \cite{wandb} to manage our experiments. Following is the list of hyperparameters used in our experiments: \begin{enumerate} \item \textbf{Contextualized Token Embedder: } We use 1024-dimensional 24-layer \texttt{bert-large-cased} obtained as a pre-trained model from HuggingFace\footnote{\url{https://huggingface.co/bert-large-cased}}. We freeze the weights of the embedder in our training. The max sequence length is set to 256. \item \textbf{Speaker embedding: } 2-dimensional trainable embedding with vocabulary size of 4 as we only have 4 unique speakers in our dataset: doctor, patient, caregiver and nurse. \item \textbf{Softmax and Fusedmax: }The temperatures of softmax and fusedmax are set to a default value of 1. The sparsity weight of fusedmax is also set to its default value of 1 for all attributes. \item \textbf{TAScore: } The transformer used in TAScore is a 2-layer transformer encoder where each layer is implemented as in \citet{attention-is-all}. Both the hidden dimensions inside the transformer (self-attention and feedforward) are set to 32 and all the dropout probabilities are set to 0.2. The linear layer for the query has input and output dimensions of 1024 and 32, respectively. Due to the concatenation of speaker embedding, the linear layer for keys has input and output dimensions of 1026 and 32, respectively. The feedforward layer (which generates scalar scores for each token) on top of the transformer is 2-layered with relu activations and hidden sizes (16, 1). \item \textbf{Classifiers: } The final classifier for each attribute is a 2-layer feedforward network with hidden sizes (512, ``number of classes for the attribute'') and dropout probability of 0.2. \end{enumerate} \subsection{Examples: Projection Functions} \label{app:examples projection} Figures \ref{fig:examples softmax} and \ref{fig:examples fusedmax} show examples of outputs of projection functions softmax and fusedmax on random input scores. \begin{figure*} \centering \subfloat[Positive and negative scores]{\includegraphics[width = \textwidth]{images/softmax1.png}}\\ \subfloat[Positive scores only]{\includegraphics[width = \textwidth]{images/softmax2}}\\ \subfloat[More uniformly distributed positive scores]{\includegraphics[width = \textwidth]{images/softmax3.png}} \caption{Sample outputs (right column) of softmax function on random input scores (left column).} \label{fig:examples softmax} \end{figure*} \begin{figure*} \centering \subfloat[Positive and negative scores]{\includegraphics[width = \textwidth]{images/fusedmax1.png}}\\ \subfloat[Positive scores only]{\includegraphics[width = \textwidth]{images/fusedmax2}}\\ \subfloat[More uniformly distributed positive scores]{\includegraphics[width = \textwidth]{images/fusedmax3.png}} \caption{Sample outputs (right column) of fusedmax function on random input scores (left column).} \label{fig:examples fusedmax} \end{figure*} \subsection{Phrase based extraction baseline} \label{app:phrase based} We implement a phrase based extraction system to provide a baseline for the extraction task. A lexicon of relevant phrases is created for each class for each attribute as shown in Table \ref{tab:phrase based phrases}. We then look for string matches within these phrases and the text for the data-point. If there are matches then the longest match is considered as an extraction span for that attribute. \begin{table*}[] \centering \begin{tabular}{|l|l|l|} \hline Attribute & Class & Phrases \\ \hline \multirow{11}{*}{freq} & Every Morning & everyday in the morning \textbar{} every morning \textbar{} morning~ \\ \cline{2-3} & At Bedtime & \begin{tabular}[c]{@{}l@{}}everyday before sleeping \textbar{} everyday after dinner \textbar{}\\~every night \textbar{} after dinner \textbar{}\\~at bedtime \textbar{} before sleeping\end{tabular} \\ \cline{2-3} & Twice a day & \begin{tabular}[c]{@{}l@{}}twice a day \textbar{} 2 times a day \textbar{} two times a day \textbar{}\\~2 times per day \textbar{} two times per day\end{tabular} \\ \cline{2-3} & Three times a day & 3 times a day \textbar{} 3 times per day \textbar{} 3 times every day \\ \cline{2-3} & Every six hours & every 6 hours \textbar{} every six hours \\ \cline{2-3} & Every week & every week \textbar{} weekly \textbar{} once a week \\ \cline{2-3} & Twice a week & \begin{tabular}[c]{@{}l@{}}twice a week \textbar{} two times a week \textbar{}~\\2 times a week \textbar{} twice per week \textbar{} two times per week \textbar{}~\\2 times per week\end{tabular} \\ \cline{2-3} & Three times a week & 3 times a week \textbar{} 3 times per week \\ \cline{2-3} & Every month & every month \textbar{} monthly \textbar{} once a month \\ \cline{2-3} & Other & \\ \cline{2-3} & None & \\ \hline \multirow{9}{*}{route} & Pill & tablet \textbar{} pill \textbar{} capsule \textbar{} mg \\ \cline{2-3} & Injection & pen \textbar{} shot \textbar{} injector \textbar{} injection \textbar{} inject \\ \cline{2-3} & Topical cream & cream \textbar{} gel \textbar{} ointment \textbar{} lotion \\ \cline{2-3} & Nasal spray & spray \textbar{} nasal conversation transcript. \\ \cline{2-3} & Medicated patch & patch \\ \cline{2-3} & Ophthalmic solution & ophthalmic \textbar{} drops \textbar{} drop \\ \cline{2-3} & Oral solution & oral solution \\ \cline{2-3} & Other & \\ \cline{2-3} & None & \\ \hline \multirow{6}{*}{change} & Take & take \textbar{} start \textbar{} put you on \textbar{} continue \\ \cline{2-3} & Stop & stop \textbar{} off \\ \cline{2-3} & Increase & increase \\ \cline{2-3} & Decrease & reduce \textbar{} decrease \\ \cline{2-3} & Other & \\ \cline{2-3} & None & \\ \hline \end{tabular} \caption{Phrases used in the phrase based baseline. These are also the most frequently occurring phrases in the free-form annotations.} \label{tab:phrase based phrases} \end{table*} \section{Model} \label{sec:model} Our classification + extraction model uses MR attributes classification labels to extract MR attributes. The model can be divided into three phases: identify, classify and extract (Figure \ref{fig:model_overview}). The identify phases encodes the input text and medication name and uses the attention bottleneck to produce attention over the text. Classify phase computes the context vector using the attention from the identify phases and classifies the context vectors. Finally, the extract phase uses the attention from the identify phase to extract spans corresponding to MR attributes. \noindent\textbf{Notation}: Let the dataset $\mathcal{D}$ be $\{(\mathbf{x^{(1)}}, \mathbf{y^{(1)}}), \dots (\mathbf{x^{(N)}}, \mathbf{y^{(N)}}) \}$. Each $\mathbf{x}$ consists of a medication $m$ and conversation text $\mathbf{t}$, and each $\mathbf{y}$ consists of classification labels for \emph{frequency}, \emph{route}~and \emph{change}, i.e, $\mathbf{y} = (^fy, ^ry, ^cy)$, respectively. The number of classes for each attribute is denoted by $^{(\cdot)}n$. As seen from Table \ref{tab:class labels}, $^fn=12$, $^rn=10$ and $^cn=8$. The length of a text excerpt is denoted by $l$. The extracted span for attribute $k\in\{f,r,c\}$ is denoted by a binary vector $^{k}\mathbf{e}$ of length $l$, such that $^{k}e_j =1$, if $j^{\text{th}}$ token is in the extracted span for attribute $k$. \begin{figure}[] \centering \includegraphics[height=70mm,width=0.40\textwidth]{images/medication_attributes_extraction_v1_4.pdf} \caption{Complete model for weakly supervised MR attribute extraction.} \label{fig:model_overview} \end{figure} \subsection{Identify} \label{sec:model:identify} As shown in the Figure \ref{fig:model_overview}, the \emph{identify} phase finds the most relevant parts of the text w.r.t each of the three attributes. For this, we first encode the text as well as the given medication using a contextualized token embedder $\mathcal{E}$. In our case, this is 1024 dimensional BERT \cite{devlin-etal-2019-bert}\footnote{The pre-trained weight for BERT is from the HuggingFace library\cite{huggingface} }. Since BERT uses WordPiece representations \cite{wordpiece}, we average these wordpiece representations to form the word embeddings. In order to supply the speaker information, we concatenate a 2-dimensional fixed vocabulary speaker embedding to every token embedding in the text to obtain speaker-aware word representations. We then perform average pooling of the medication representations to get a single vector representation for the medication\footnote{Most medication names are single word, however a few medicines have names which are upto 4-5 words.}. Finally, with the given medication representation as the query and the speaker-aware token representations as the key, we use three separate attention functions (attention bottleneck), one for each attribute (no weight sharing), to produce three sets of normalized attention distributions $^f\mathbf{\hat{a}}$, $^r\mathbf{\hat{a}}$ and $^c\mathbf{\hat{a}}$ over the tokens of the text. The \emph{identify} phase can be succinctly described as follows: \begin{align*} ^k\mathbf{a} = {^k\alpha}(\mathcal{E}(m), \mathcal{E}(t))~,~~\text{where } k \in \{f, r, c\} \end{align*} Here, each $^k\mathbf{\hat{a}}$ is an element of the probability simplex $\Delta^l$ and is used to perform attribute extraction (Section \ref{sec:extract}). \subsection{Classify} \label{sec:model:classify} We obtain the attribute-wise context vectors~$^k\mathbf{c}$, as the weighted sum of the encoded tokens ($\mathbf{K}$ in Figure \ref{fig:model_overview}) where the weights are given by the attribute-wise attention distributions $^k\mathbf{a}$. To perform the classification for each attribute, the attribute-wise context vectors are used as input to feed-forward neural networks $\mathcal{F}_k$ (one per attribute), as shown below:\footnote{Complete set of hyperparameters used is given in Appendix \ref{app:hyperparams} \begin{align*} ^k\mathbf{p} &= \text{softmax}\left(\mathcal{F}_k(^k\mathbf{c})\right)\\ ^k\hat{y} &= \argmax_{j \in \{1,2,\dots, ^kn\}} {^kp_j}~,~~\text{where } k \in \{f, r, c\}. \end{align*} \subsection{Extract} \label{sec:extract} The spans are extracted from the attention distribution using a fixed extraction function $\mathcal{X}\colon \Delta^l \to \{0,1\}^l$, defined as: \begin{align*} ^k\hat{e}_j=\mathcal{X}_k(^k\mathbf{a})_j &= \begin{cases} 1 & \text{if } {^ka}_j > {^k\gamma} \\ 0 & \text{if } {^ka}_j \leq {^k\gamma}~, \end{cases} \end{align*} \noindent where $^k\gamma$ is the extraction threshold for attribute $k$. For softmax projection function, it is important to tune the attribute-wise extraction thresholds $\mathbf{\gamma}$. We tune these using extraction performance on the extraction validation set. For fusedmax projection function which produces spare weights, the thresholds need not be tuned, and hence are set to $0$. \subsection{Training} \label{sec:training} We train the model end-to-end using gradient descent, except the \emph{extract} module (Figure \ref{fig:model_overview}), which does not have any trainable weights, and the embedder $\mathcal{E}$. {Freezing the embedder is vital for the performance, since not doing so results in excessive dispersion of token information to other nearby tokens, resulting in poor extractions.} \smallskip The total loss for the training is divided into two parts as described below. \noindent\textbf{(1) Classification Loss $\mathcal{L}_c$: } In order to perform classification with highly class imbalanced data (see Table \ref{tab:class labels}), we use weighted cross-entropy: \begin{align*} \mathcal{L}_c &= \sum_{k \in \{ f, r, c\}} - ~{^kw_{^ky}}~ \log \left({^kp_{^ky}}\right)~, \end{align*} \noindent where the class weights ${^kw_{^ky}}$ are obtained by inverting each class' relative proportion. \smallskip \noindent\textbf{(2) Identification Loss $\mathcal{L}_i$: }If span labels $\mathbf{{e}}$ are present for some subset $\mathcal{A}$ of training examples, we first normalize these into ground truth attention probabilities $\mathbf{a}$: \begin{align*} ^ka_j &= \frac{^ke_j}{\sum^l_{j=1} {^ke_j}} ~~~\text{~~for~~} k \in \{f,r,c\} \end{align*} \noindent We then use KL-Divergence between the ground truth attention probabilities and the ones generated by the model ($\mathbf{\hat{a}}$) to compute identification loss $\mathcal{L}_i = \sum_{k \in \{ f, r, c\}} ~ \text{KL}\left(^k\mathbf{{a}} \Big\Vert {^k\mathbf{\hat{a}}}\right)$. Note that $\mathcal{L}_i$ is zero for data-points that do not have span labels. Using these two loss functions, the overall loss $\mathcal{L} = \mathcal{L}_c + \lambda \mathcal{L}_i$. \section{Related Work} \label{sec:related work} Existing literature directly related to our work can be bucketed into two categories -- related methods and related tasks. \smallskip \noindent\textbf{Methods: }The recent work on generating rationales/explanations for deep neural network based classification models \cite{Lei2016, Bastings2020, Paranjape2020} is closely related to ours in terms of the methods used. Most of these works use binary latent variables to perform extraction as an intermediate step before classification. Our work is closely related to \cite{Jain2020,zhong2019finegrained}, who use attention scores to generate rationales for classification models. These works, however, focus on generating \emph{faithful} and \emph{plausible} explanation for classification as opposed to extracting the spans for attributes of an entity, which is the focus of our work. Moreover, our method can be generalized to any number of attributes while all these methods would require a separate model for each attribute. \smallskip \noindent\textbf{Tasks: }Understanding doctor-patient conversations is starting to receive attention recently \cite{rajkomar2019automatically, ben2020soap}. \citet{selvaraj2019medication} performs MR extraction by framing the problem as a generative question answering task. This approach is not efficient at inference time -- it requires one forward pass for each attribute. Moreover, unlike a span extraction model, the generative model might produce hallucinated facts. \citet{du2019learning} obtain MR attributes as spans in text; however, they use a fully supervised approach which requires a large dataset with span-level labels. \section{Metrics} \label{sec:metrics} \noindent\textbf{Token-wise F1 (TF1)}: Each token in text is either part of the extracted span (positive class) for an attribute or not (negative class). Token-wise F1 score is the F1 score of the positive class obtained by considering all the tokens in the dataset as separate binary classification data points. TF1 is calculated separately for each attribute. \smallskip \noindent\textbf{Longest Common Substring F1 (LCSF1):} LCSF1 measures if the extracted spans, along with being part of the gold spans, are contiguous or not. Longest Common Substring (LCS) is the longest overlapping contiguous span of tokens between the predicted and gold spans. LCSF1 is defined as the harmonic mean of LCS-Recall and LCS-Precision which are defined per extraction as: \vspace{-3mm} {\small \begin{align*} \text{LCS-Recall} &= \frac{\text{\#tokens in LCS}}{\text{\#tokens in gold span}}\\ \text{LCS-Precision} &= \frac{\text{\#tokens in LCS}}{\text{\#tokens in predicted span}} \end{align*} }% \section{Results and Analysis} \label{sec: results and analysis} \label{sec:results} Table \ref{tab:all results} shows the results obtained by various combinations of attention scoring and projection functions on the task of MR attribute extraction in terms of the metrics defined in Section \ref{sec:metrics}. It also shows the classification F1 score to emphasize how the attention bottleneck affects classification performance. The first row shows how a simple phrase based extraction system would perform on the task.\footnote{The details about the phrase based baseline are presented in Appendix \ref{app:phrase based}} \subsection{Effect of Span labels} In order to see if having a small number of extraction training data-points (containing explicit span labels) helps the extraction performance, we annotate 150 (see Section \ref{sec:task and data} for how we sampled the datapoints) of the training data-points with span labels. As seen from Table \ref{tab:all results}, even a small number of examples with span labels ($\approx 0.3 \%$) help a lot with the extraction performance for all models. We think this trend might continue if we add more training span labels. We leave the finding of the right balance between annotation effort and extraction performance as a future direction to explore. \subsection{Effect of classification labels} In order to quantify the effect of performing the auxiliary task of classification along with the main task of extraction, we train the proposed model in three different settings. (1) The \textit{Classification Only} uses the complete dataset (\texttildelow45k) but only with the classification labels. (2) The \textit{Extraction Only} setting only uses the 150 training examples that have span labels. (3) Finally, the \textit{Classification+Extraction} setting uses the 45k examples with classification labels along with the 150 examples with the span labels to train the model. Table \ref{tab:effect joint model} (rows 2, 3 and 4) shows the effect of having classification labels and performing extraction and classification jointly using the proposed model. The model structure and the volume of the classification data (\texttildelow45k examples) makes the auxiliary task of classification extremely helpful for the main task of extraction, even with the presence of label noise. It is worth noting that the classification performance of the proposed method is also improved by explicit supervision to the extraction portion of the model (row 2 vs 4, Table \ref{tab:effect joint model}). In order to set a reference for classification performance, we train strong classification only models, one for each attribute, using pretrained BERT. These \textit{BERT Classifiers}, are implemented as described in \citet{devlin-etal-2019-bert} with input consisting of the text and medication name separated by a [SEP] token (row 1). Based on the improvements achieved in the classification performance using span annotations, we believe that having more span labels can further close the gap between the classification performance of the proposed model and the BERT Classifiers. However, this work focuses on extraction performance, hence improving the classification performance is left to future work. \subsection{Effect of projection function} \label{sec:effect of projection} While softmax with post-hoc threshold tuning achieves consistently higher TF1 compared to fusedmax (which does not require threshold tuning), the later achieves better LCSF1. We observe that while the attention function using softmax projection focuses on the correct portion of the text, it drops intermediate words, resulting in multiple discontinuous spans. Fusedmax on the other hand almost always produces contiguous spans. Figure \ref{fig:extraction examples} further illustrates this point using a test example. The training trick which we call fusedmax* swaps the softmax projection function with fusedmax during the final few epochs to combine the strengths of both softmax and fusedmax. This achieves high LCSF1 as well as TF1. \begin{figure}[h!] \centering \subfloat[BERT+TAScore+Fusedmax*]{\includegraphics[width = \columnwidth]{images/bert-transformer-fusedmax-from-softmax.png}}\\[-1mm] \subfloat[BERT+TAScore+Softmax]{\includegraphics[width = \columnwidth]{images/bert-transformer-softmax.png}} \vspace{-1mm} \caption{Difference in extracted spans for MR attributes with models that uses Fusedmax* and Softmax, for the medication Actonel. Blue: \emph{change}, green: \emph{route}~and yellow: \emph{frequency}. Refer Figure \ref{fig:dialogue} for ground-truth annotations.} \label{fig:extraction examples} \end{figure} \subsection{Effect of scoring function} \label{sec:effect of scoring} Table \ref{tab:effect of scorer} shows the percent change in the extraction F1 if we use TAScore instead of additive scoring (everything else being the same). As seen, there is a significant improvement irrespective of the projection function being used. \begin{table}[h!] \centering \resizebox{\columnwidth}{!}{% \begin{tabular}{@{}l|lll|lll@{}} \toprule \multirow{2}{*}{\begin{tabular}[c]{@{}l@{}}Scorer\end{tabular}} & \multicolumn{3}{l|}{TF1 ($\Delta$\%)} & \multicolumn{3}{l}{LCSF1 ($\Delta$\%)} \\ \cmidrule(l){2-7} & \begin{tabular}[c]{@{}l@{}}MM\\ (77.3)\end{tabular} & \begin{tabular}[c]{@{}l@{}}SM\\ (22.7)\end{tabular} & \begin{tabular}[c]{@{}l@{}}All\\ (100)\end{tabular} & \begin{tabular}[c]{@{}l@{}}MM\\ (77.3)\end{tabular} & \begin{tabular}[c]{@{}l@{}}SM\\ (22.7)\end{tabular} & \begin{tabular}[c]{@{}l@{}}All\\ (100)\end{tabular} \\ \midrule softmax & +11.1 & +10.6 & +10.6 & +6.5 & +6.6 & +6.3 \\ fusedmax & +12.1 & +8.3 & +11.5 & +16.4 & +15.5 & +13.9 \\ fusedmax* & +5.4 & +1.9 & +4.7 & +9.25 & +1.1 & +7.9 \\ \bottomrule \end{tabular}% } \caption{MR extraction improvement (\%) brought by TAScore over additive scorer in the full test set (All=100\%), and test subset with single medication (SM=22.7\%) and multiple medications (MM=77.3\%) in the \emph{text}.} \label{tab:effect of scorer} \end{table} The need for TAScore stems from the difficulty of the additive scoring function to resolve references between spans when there are multiple medications present. In order to measure the efficacy of TAScore for this problem, we divide the test set into two subsets: data-points which have multiple distinct medications in their text (MM) and data-points that have single medication only. As seen from the first two columns for both the metrics in Table \ref{tab:effect of scorer}, using TAScore instead of additive results in more improvement in the MM-subset compared to the SM-subset, showing that using transformer scorer does help with resolving references when multiple medications are present in the text. Figure \ref{fig:LCSF1 distribution} shows the distribution of Avg. LCSF1 (average across all three attributes). It can be seen that there are a significant number of datapoints in the MM subset which get LCSF1 of zero, showing that even when the transformer scorer achieves improvement on MM subset, it gets quite a lot of these data-points completely wrong. This shows that the there is still room for improvement. \begin{figure} \centering \includegraphics[width=.9\columnwidth]{images/LCSF1_distribution.png} \caption{Distribution of the Avg. LCSF1 for the best performing model (BERT+TAScore+Fusedmax*). A significant number ($\approx10\%$) of datapoints with multiple medication in their \emph{text} get LCSF1 of zero (1st bar).} \label{fig:LCSF1 distribution} \end{figure} \subsection{Discussion} In summary, our analysis reveals that Fusedmax/Fusedmax* favors contiguous extraction spans which is a necessity for our task. Irrespective of the projection function used, the proposed scoring function TAScore improves the extraction performance when compared to the popular additive scoring function. The proposed model architecture is able to establish a synergy between the classification and span extraction tasks where one improves the performance of the other. Overall, the proposed combination of TAScore and Fusedmax* achieves a 22 LCSF1 points improvement over the phrase-based baseline and 10 LCSF1 points improvement over the naive additive and softmax combination. \section{Medication Regimen (MR) using Weak Supervision} \label{sec:task and data} Medication Regimen (MR) consists of information about a prescribed medication akin to attributes of an entity. In this work, we specifically focus on \emph{frequency}, \emph{route}~of the medication and any \emph{change}~in the medication's \emph{dosage} or \emph{frequency}~ as shown in Figure \ref{fig:dialogue}. For example, given the conversation excerpt and the medication ``Fosamax'' as shown in Figure \ref{fig:dialogue}, the model needs to extract the spans ``one pill on Monday and one on Thursday'', ``pill'' and ``you take'' for attributes \emph{frequency}, \emph{route} ~and \emph{change}, respectively. The major challenge, however, is to perform the attribute span extraction using noisy classification labels with very few or no span-level labels. The rest of this section describes the dataset used for this task. \begin{table}[] \centering \resizebox{\columnwidth}{!}{% {\small \begin{tabular}{|l|l|} \toprule Attribute & Normalized Classes \\ \midrule \emph{frequency} & \begin{tabular}[c]{@{}l@{}}Daily \textbar{} Every morning \textbar{} At Bedtime \textbar{}\\Twice a day \textbar{} Three times a day \textbar{} Every six hours \textbar{}\\Every week \textbar{} Twice a week \textbar{} Three times a week \textbar{}\\Every month \textbar{} Other \textbar{} None \end{tabular} \\ \midrule \emph{route} & \begin{tabular}[c]{@{}l@{}}Pill \textbar{} Injection \textbar{} Topical cream \textbar{} Nasal spray \textbar{}\\Medicated patch \textbar{} Ophthalmic solution \textbar{} Inhaler \textbar{}\\Oral solution \textbar{} Other \textbar{} None \end{tabular} \\ \midrule \emph{change} & Take \textbar{} Stop \textbar{} Increase \textbar{} Decrease \textbar{} None \textbar{} Other \\ \bottomrule \end{tabular} } } \caption{The normalized labels in the classification data.} \label{tab:class labels} \end{table} \begin{table*}[] \centering \resizebox{\textwidth}{!}{% \begin{tabular}{@{}lcccc@{}} \toprule \multirow{2}{*}{\emph{text}} & \multirow{2}{*}{\emph{medication}} &\multicolumn{3}{c}{Classification labels} \\ \cmidrule(l){3-5} & & \multicolumn{1}{l}{\emph{frequency}} & \emph{route} & \emph{change} \\ \midrule \begin{tabular}[c]{@{}l@{}}{\small$\dots$ I would recommend vitamin D to be taken.}\\[-2mm] {\small Have you had Fosamax before?$\dots$}\end{tabular} & { vitamin D} & { none} & \multicolumn{1}{c}{{ none} } & take \\\midrule \begin{tabular}[c]{@{}l@{}}{\small$\dots$ I think my mum did. Okay, Fosamax, you take one pill on Monday}\\[-2mm] {\small and one on Thursday. Do you have much caffine? No, none$\dots$}\end{tabular} & Fosamax & Twice a week & \multicolumn{1}{c}{pill} & take \\\midrule \begin{tabular}[c]{@{}l@{}}{\small Do you have much caffine? No, none. Okay, this is Actonel and it's,}\\[-2mm] {\small one tablet once a month.$\dots$} \end{tabular} & Actonel & Once a month & \multicolumn{1}{c}{pill} & take \\ \bottomrule \end{tabular} } \caption{Classification examples resulting from the conversation shown in Figure \ref{fig:dialogue}.} \label{tab:dataset example} \end{table*} \subsection{Data} The data used in this paper comes from a collection of human transcriptions of 63000 fully-consented and de-identified doctor-patient conversations. A total of 57000 conversations were randomly selected to construct the training (and dev) conversation pool and the remaining 6000 conversations were reserved as the test pool. \smallskip \noindent\textbf{The classification dataset: }All the conversations are annotated with MR tags by expert human annotators. Each set of MR tags consists of the \emph{medication} name and its corresponding attributes \emph{frequency}, \emph{route}~ and \emph{change}, which are normalized free-form instructions in natural language phrases corresponding to each of the three attributes (see Table \ref{tab:phrase based phrases} in \ref{app:phrase based}). Each set of MR tags is grounded to a contiguous window of utterances' \emph{text},\footnote{The \emph{text} includes both the spoken words and the speaker information.} around a medication mention as evidence for that set. Hence, each set of grounded MR tags can be written as $<$\emph{medication}, \emph{text}, \emph{frequency}, \emph{route}, \emph{change}$>$, where the last three entries correspond to the three MR attributes. The free-form instructions for each attribute in the MR tags are normalized and categorized into manageable number of classification labels to avoid long tail and overlapping classes. This process results in classes shown in Table \ref{tab:class labels}.\footnote{The detailed explanation for each of the classes can be found in Table \ref{tab:class labels detailed} in Appendix \ref{app:data}.} As an illustration, this annotation process when applied to the conversation piece shown in Figure \ref{fig:dialogue} would result in the three data points shown in Table \ref{tab:dataset example}. Using this procedure on both the training and test conversation pools, we obtain 45,059 training, 11,212 validation and 5,458 test classification data points.\footnote{The dataset statistics are given in Appendix \ref{app:data}.} \smallskip \noindent\textbf{The extraction dataset: } Since the goal is to extract spans related to MR attributes, we would ideally need a dataset with span annotations to perform this task in a fully supervised manner. However, span annotation is laborious and expensive. Hence, we re-purpose the classification dataset (along with its classification labels) to perform the task of span extraction using weak supervision. We also manually annotate a small fraction of the train, validation and test sets (150, 150 and 500 data-points respectively) for attribute spans to see the effect of supplying a small number of strongly supervised instances on the performance of the model. In order to have a good representation of all the classes in the test set, we increase the sampling weight of data-points which have rare classes. Hence, our test set is relatively more difficult compared to a random sample of 500 data-points. All the results are reported on our test set of 500 difficult data-points annotated for attribute spans. For annotating attribute spans, the annotators were given instructions to mark spans which provide minimally sufficient and natural evidence for the already annotated attribute class as described below. \smallskip \noindent\textbf{Sufficiency:} Given only the annotated span for a particular attribute, one should be able to predict the correct classification label. This aims to encourage the attribute spans to cover all distinguishing information for that attribute. \noindent\textbf{Minimality: }Peripheral words which can be replaced with other words without changing the attribute's classification label should not be included in the extracted span. This aims to discourage marking entire utterances as attribute spans. \noindent\textbf{Naturalness: }The marked span(s) if presented to a human should sound like complete English phrases (if it has multiple tokens) or a meaningful word if it has only a single token. In essence, this means that the extractions should not drop stop words from within phrases. \newlyadded{This requirement aims to reduce the cognitive load on the human who uses the model's extraction output.} \subsection{Challenges} \label{sec:challenges} Using medical conversations for information extraction is more challenging compared to written doctor notes because the spontaneity of conversation gives rise to a variety of speech patterns with disfluencies and interruptions. Moreover, the vocabulary can range from colloquial to medical jargon. In addition, we also have noise in our classification dataset with its main source being annotators' use of information outside the grounded \emph{text} window to produce the free-form tags. This happens in two ways. First, when the free-form MR instructions are written using evidence that was discussed elsewhere in the conversation but is not present in the grounded \emph{text} window. Second, when the annotator uses their domain knowledge instead of using just the information in the grounded \emph{text} window -- for instance, when the \emph{route} of a \emph{medication} is not explicitly mentioned, the annotator might use the \emph{medication}`s common \emph{route} in their free-form instructions. Using manual analysis of the 800 data-points across the train, dev and test sets, we find that 22\% of \emph{frequency}, 36\% of \emph{route}~and 15\% of \emph{change}~ classification labels, have this noise. In this work, our approach to extraction depends on the size of the auxiliary task's (classification) dataset to overcome above mentioned challenges. \section{While Writing} \todo{Add into} \sout{Some text} \points{ \begin{enumerate} \item Point1 \item Pont2 \end{enumerate} } Normal text
{'timestamp': '2020-10-13T02:24:42', 'yymm': '2010', 'arxiv_id': '2010.05317', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05317'}
arxiv
\section{\label{sec-introduction}Introduction} DTW \cite{sakoe_dynamic_1978} is one of the most important similarity measure in time series analysis, extensively used in clustering~\cite{luczak_hierarchical_2016}, classification~\cite{wang_experimental_2013}, and similarity search~\cite{rakthanmanon_searching_2012}. Classification with one nearest neighbour under DTW (``NN1-DTW'') was a widely used benchmark for a long time, and while state of the art classifiers are now significantly more accurate, some of them actually embed a NN1-DTW classifier as a component~\cite{lines_time_2015,lines_time_2018,lucas_proximity_2019,shifaz_ts-chief_2020}. A naive DTW implementation has space and time complexities both undesirably quadratic. How to take care of the former is well known~\cite{mueen_extracting_2016} (and we do so in this article, cf~section~\ref{sec-background}), while taking care of the later is more challenging. The common ``early abandoning'' strategy first tries to avoid DTW computations, and then tries to early abandon them. But it can only speed up scenarios where an upper bound is available (e.g.~NN1~search), and not DTW itself. DTW has been sped up through vectorization~\cite{xiao_parallelizing_2013,mueen_extracting_2016} or approximation~\cite{salvador_toward_2007}% \footnote{Using constraint bands or approximation generally leads to different results than with ``exact DTW'', and thus cannot be considered as being faster versions of DTW.}, and more recently by PrunedDTW~\cite{silva_speeding_2016}, an algorithm developed for scenarios where early abandoning isn't applicable (e.g.~when all pairwise distances are required). It was later applied to similarity search in the UCR USP Suite~\cite{silva_speeding_2018}, fitted with \emph{some} early abandon capabilities used in conjunction with lower bounding. However, the core of the algorithm was not revisited. In this article, we present ``EAPrunedDTW'', our version of PrunedDTW specifically designed to efficiently and effectively early abandon. We incorporated our algorithm in the UCR Suite and reproduced the experiments from~\cite{silva_speeding_2018}, showing a significant speed improvement over previous implementations based on DTW and PrunedDTW. Moreover, we show that using lower bounds, even if useful, becomes dispensable. This is especially relevant for other distances sharing the same structure as DTW (see~\cite{marteau_time_2009}) for which no efficient and tight lower bounds exist. The next section introduces DTW and related work. We then present our algorithm in two parts, sections~\ref{sec-presentation-1} and~\ref{sec-presentation-2}. Experiments follow in section~\ref{sec-experimentations}, and we conclude in section~\ref{sec-conclusion}. \section{\label{sec-background}Background and related work} Given two times series $S$ and $T$ of respective length $l_S$ and $l_T$, and a $\cost$ function (usually the squared Euclidean distance) over data points themselves denoted by application (e.g.~$S(i)$), the distance $\DTW^{S,T}$ between $S$ and $T$ is defined by: \begin{figure}[H] \setlength{\abovedisplayskip}{0pt} \setlength{\belowdisplayskip}{0pt} \begin{alignat}{2} & \hspace{-3em} \DTW^{S,T} && = \DTW^{S,T}(l_S, l_T) \\ & \hspace{-3em} \DTW^{S,T}(0,0) && = 0 \label{eq:DTW:border1}\\ & \hspace{-3em} \DTW^{S,T}(i,0) && = +\infty \label{eq:DTW:border2}\\ & \hspace{-3em} \DTW^{S,T}(0,j) && = +\infty \label{eq:DTW:border3}\\ & \hspace{-3em} \DTW^{S,T}(i,j) && = \cost(S(i), T(j)) + \min\left\{ \begin{array}{l} \DTW^{S,T}(i-1, j) \\ \DTW^{S,T}(i, j-1) \\ \DTW^{S,T}(i-1, j-1) \end{array} \right.\label{eq:DTW:main} \end{alignat} \caption{\label{eq:DTW}Equations defining $\DTW^{S,T}$} \end{figure} We define by \mbox{$M_{\cost}^{S,T}(i,j) = \cost(S(i), S(j))$} the cost matrix of $S$ and $T$. A warping path in $M_{\cost}^{S,T}$ is a continuous and monotonous path connecting $(1,1)$ to $(l_S, l_T)$. The value $\DTW^{S,T}$ is the cost of the optimal (cheapest) warping path\footnote{There may be several optimal paths with the same cost.}, which also represents the cost of the optimal non linear alignment between $S$ and $T$. Such an alignment is illustrated by Figure~\ref{fig:DTW:Alignments} for \mbox{$S = (3, 1, 4, 4, 1, 1)$} and \mbox{$T = (1, 3, 2, 1, 2, 2)$}. The constraints on the path lead to the extremities (at $(1,1)$ and $l_S, l_T)$ being aligned and no alignments crossing each other (monotonicity). Let $S(1\dots{i})$ be the prefix of $S$ of length~$i$. We defined the DTW matrix of the series $S$ and $T$ by \mbox{$M_{\DTW}^{S,T}(i,j) = \DTW^{S(1\dots{i}),T(1\dots{j})}$}. Figure~\ref{fig:DTW:Matrix} shows the matrix and optimal warping path for $S$ and $T$ (this and subsequent figures are colored from intense green for the minimum value 0, through to intense red for the maximum value 22). We are only interested in the DTW matrix's last cell at $(l_S, l_T)$, i.e.~the value of $\DTW^{S,T}$. This cell can be computed without keeping the full matrix in memory. Equation~\ref{eq:DTW:main} tells us that a cell's value only depends on its ``top'', ``top left diagonal'', and ``left'' neighbours. In a line by line, left to right scan, the two firsts are obtained from the previous line, while the later is the previously computed cell. Hence, we only need to keep the current and previous line in memory, limiting the space complexity to $O(l)$ as described by Algorithm~\ref{alg:DTW}. Commenting Algorithm~\ref{alg:DTW}. Memory allocation is limited by matching the line dimension with the shortest series. Both arrays, representing the previous and current lines of the matrix, have an extra cell for the vertical border ($j=0$) and are initialized to $\infty$. The horizontal border ($i=0$) is initially represented by the $\curr$ array, which is swapped for the $\prev$ array prior to any computation (line~\ref{alg:dtw:swap}). This is why we initialize the border cell $(0,0)$ in the extra cell of the $\curr$ array (line~\ref{alg:dtw:init0}). This cell has to be set back to $\infty$ after the first iteration. We repeatedly do so (line~\ref{alg:dtw:inf}), which is avoidable by computing the first line before the loop. However, our goal is to introduce a structure we will build upon: a form of this assignment is required later. \begin{figure}[t] \centering \subfloat[\label{fig:DTW:Matrix} DTW matrix with warping path for $S$ and $T$. We have $\DTW^{S,T}=M_{\DTW}^{S,T}(6,6)=9$. ] \includegraphics[trim=0 35 0 0, clip,width=0.45\textwidth]{figures/DTWMatrix.pdf} }% \hspace{\fill} \subfloat[\label{fig:DTW:Alignments} DTW alignements for $S$ and $T$ with their costs. Their sum is $\DTW^{S,T}=9$.]{% \includegraphics[width=0.45\textwidth]{figures/DTWAlignments.pdf} } \caption{\label{fig:DTW} DTW matrix $M_{\DTW}^{S,T}$ with warping path and alignments for \mbox{$S = (3, 1, 4, 4, 1, 1)$} and \mbox{$T = (1, 3, 2, 1, 2, 2)$}. A warping path's cell $(i,j)$ means that $S(i)$ is aligned with $T(j)$. } \end{figure} \begin{algorithm2e}[t] \small \SetAlgoLined \LinesNumbered \DontPrintSemicolon \SetKwData{c}{c} \SetKwFunction{cost}{cost} \KwIn{the time series $S$ and $T$} \KwResult{$\DTW^{S,T}$} \co $\leftarrow$ shortest series between $S$ and $T$\; \li $\leftarrow$ longest series between $S$ and $T$\; (\prev, \curr) $\leftarrow$ arrays of length $l_{\co}+1$ filled with $\infty$\; $\curr{0} \leftarrow 0 $\; \label{alg:dtw:init0} \For{$i \leftarrow 1$ \KwTo $l_{\li}$}{ \swap{\prev, \curr}\; \label{alg:dtw:swap} \curr{0} $\leftarrow \infty$\; \label{alg:dtw:inf} \For{$j \leftarrow 1$ \KwTo $l_{\co}$}{ $\c \leftarrow \cost{\li{i}, \co{j}} $\; $\curr{j} \leftarrow \c + \kwmin{\curr{j-1}, \prev{j}, \prev{j-1}}$\; } } \Return{\curr{$l_{\co}$}}\; \caption{\label{alg:DTW}$O(n)$ space complexity $\DTW^{S,T}$.} \end{algorithm2e} \subsection{The Warping Window} DTW is commonly parametrized by a warping window $w$ constraining the warping path to deviate by at most $w$ cells from the diagonal~\cite{sakoe_dynamic_1978}. A window of 0 is equivalent to the $\cost$ function being applied to the successive elements of the two series (e.g. the squared Euclidean distance), while a window of $\min(l_{S},l_T)$ is equivalent to DTW. The experiments section~\ref{sec-experimentations} require a warping window, but for clarity's sake we present our algorithms for DTW only. \subsection{Early Abandoning} Early abandoning is commonly used to speed up scenarios requiring nearest neighbour search, like NN1 classification or similarity search. In those scenarios, we test a query $S$ against several candidates $T_1, T_2, \dots T_m$. After computing $v_1 = \DTW^{S,T_1}$, we have a first upper bound $\ub=v_1$ on the DTW cost between $S$ and its actual nearest neighbour, i.e. the nearest neighbour will have a cost lower than or equal to $\ub$. We tighten $\ub$ every time we find a better candidate. It follows that we can early abandon the computation of $\DTW^{S,T_k}$ as soon as we can determine that $v_k$ will \emph{strictly} exceed $\ub$. This strictness condition prevents from early abandoning ties. To implement DTW with early abandon it is enough to get the the minimum value of each $\curr$ line, and stop if it is strictly greater then $\ub$. The UCR Suite also exploits the Keogh lower bound to further tighten $\ub$ \cite{rakthanmanon_searching_2012}. Another form of early abandoning is lower bounding: The idea is to cheaply compute a lower bound $\lb(S, T_k)\leq\DTW^{S,T_k}$ and to skip any further computation if $\lb(S, T_k)>\ub$. Several lower bounds have been developed, and developing them is still an active field of research. The most commonly used lower bounds are LB\_Kim and LB\_Keogh~\cite{mueen_extracting_2016}. \subsection{PrunedDTW} Early abandoning requires an upper bound on the best candidates. PrunedDTW~\cite{silva_speeding_2016} was designed for scenarios where no such upper bound exists, e.g. when all pairwise distances are required. In those cases, we can only speed-up DTW itself. PrunedDTW determines that some cells from the DTW matrix cannot be part of the optimal warping path and skips their computation. To do so, it relies on a pruning threshold which is an upper bound on the current alignment's cost (and not on the cost of the alignment with the best candidates). This threshold can only depend on the series being aligned. PrunedDTW uses the squared Euclidean distance, which corresponds to the diagonal in the DTW matrix\footnote{The cost of any valid alignment is an upper bound. Either the alignment is the optimal one, or the optimal one will have a lower cost.}, which may be quite loose. The next logical step was to use PrunedDTW in scenarios with upper bounds on best candidates as they are usually tighter. The UCR Suite has been modified to use PrunedDTW, giving birth to the UCR USP Suite \cite{silva_speeding_2018}. However, PrunedDTW inherits features from its origins as a pruning algorithm, and fails to fully exploit the possibilities of early abandoning. In the current work we seek to exploit those opportunities to the full. \subsection{Overheads and Run-Time Speed} The computation of DTW relies of two nested ``tight'' loops: the inner body is small but repeated many times. Early abandoning and pruning techniques modify those loops with extra checking and bookkeeping, adding a bit of ``overhead'' per iteration. The expectation is that the time saved by those techniques outweigh their overhead. It follows that for the same gain, the algorithm with the smallest overhead will be the most efficient. By carefully decomposing our algorithm in several stages, we seek to minimize these overheads while maximising pruning. Comparing the run-time speed of different algorithms seems simple: run the candidates several times under the same conditions and compare the fastest (i.e. less noisy) results. There is not much to discuss if the differences are substantial (regardless of the direction), and clearly due to algorithmic changes. However, we are not comparing algorithms, but implementations of those algorithms. A ``fast'' implementation of a ``slow'' algorithm may be the best performer until we reach large enough data. To combat this problem we embed our DTW algorithm in the UCR Suite and make minimal modifications to the code. \section{\label{sec-presentation-1}Pruning and Early Abandoning from the left} In the previous section, we show how to compute $\DTW^{S,T}$ line by line. Now, we show how to prune the computation ``from the left''. As we scan a line, we look at discarding as many as possible of the leftmost cells of the DTW matrix. We do so by extending the ``left border'' up to the leftmost cell of the current line that could potentially be part of an optimal warping path. The Figures~\ref{fig:DTW:EAMatrix:UB9} and \ref{fig:DTW:EAMatrix:UB6} present the pruning and early abandoning scenarios for the same $S$ and $T$ as before, using upper bounds of $\ub=9$ and $\ub=6$. As $\DTW^{S,T}=9$, no early abandoning occurs in the first case, but it does in the second. \begin{figure}[!t] \centering \subfloat[][\label{fig:DTW:EAMatrix:UB9}DTW Matrix for $S$ and $T$ with $\ub=9$. The arrows represent the dependencies of the cell $(4,1)$.]{% \includegraphics[trim=0 35 0 0, clip, width=0.45\textwidth]{figures/UB9_DTWEAMatrix.pdf} }% \hspace{\fill} \subfloat[][\label{fig:DTW:EAMatrix:UB6}DTW Matrix for $S$ and $T$ with $\ub=6$. Early abandon occurs at the end of the fifth line.]{% \includegraphics[trim=0 35 0 0, clip, width=0.45\textwidth]{figures/UB6_DTWEAMatrix.pdf} } \caption{\label{fig:DTW:EAMatrix}Representation of $M_{\DTW}^{S,T}$ ``from the left'' pruning for \mbox{$S = (3, 1, 4, 4, 1, 1)$} and \mbox{$T = (1, 3, 2, 1, 2, 2)$} with two different upper bounds. } \end{figure} \begin{algorithm2e}[!t] \small \SetAlgoLined \LinesNumbered \DontPrintSemicolon \SetKwData{c}{c} \SetKwFunction{cost}{cost} \KwIn{the time series $S$ and $T$, an upper bound $\ub$} \KwResult{$\DTW^{S,T}$} \co $\leftarrow$ shortest series between $S$ and $T$\; \li $\leftarrow$ longest series between $S$ and $T$\; (\prev, \curr) $\leftarrow$ arrays of length $l_{\co}+1$ filled with $\infty$\; $\curr{0} \leftarrow 0 $\; $\nextstart \leftarrow 1$\; \label{alg:DTWEA:init_ns} \For{$i \leftarrow 1$ \KwTo $l_{\li}$}{ \swap{\prev, \curr}\; $j \leftarrow \nextstart$\; $\curr{j-1} \leftarrow \infty$\; \label{alg:DTW:inf} \While{$j=\nextstart \wedge j \leq l_{\co}$}{ \label{alg:DTWEA:cond1} $\c \leftarrow \cost{\li{i}, \co{j}} $\; $\curr{j} \leftarrow \c + \kwmin{\prev{j}, \prev{j-1}}$\; \label{alg:DTWEA:min} \lIf{$\curr{j}>\ub$}{$\nextstart \leftarrow \nextstart+1$} $j\leftarrow j+1$\; } \lIf{$j>l_{co}$}{\Return{$\infty$}} \label{alg:DTWEA:ea} \While{$j \leq l_{\co}$}{ $\c \leftarrow \cost{\li{i}, \co{j}} $\; $\curr{j} \leftarrow \c + \kwmin{\curr{j-1}, \prev{j}, \prev{j-1}}$\; $j\leftarrow j+1$\; } } \Return{\curr{$l_{\co}$}}\; \caption{\label{alg:DTWEA}Pruning from the left.} \end{algorithm2e} Looking at Figure~\ref{fig:DTW:EAMatrix}, the grey cells are never computed (border or pruned cells), and the white cells with red edges represent ``discard points''. Given a line and an upper bound $\ub$, discard points represent a continuous sequence of cells greater than $\ub$, starting at the left border. By monotonicity, all columns below discard points are guaranteed to be greater than $\ub$. It follows that those columns can be skipped for the rest of the computation, and we do so by starting the next line after the current line's last discard point% \footnote{This explain why the Algorithm~\ref{alg:DTWEA} uses the ``\nextstart'' variable rather than a ``discard point'' one}. Ignoring the top border for now (we will take care of it in the next section), you can easily check that all the dependencies of the grey cells are either another grey cell, or a discard point. Note that $(1,0)$ is a discard point while $(2,0)$ is pruned. In this regard, the first discard point and pruned column naturally match the left border. Looking at the discard point at $(3,1)$ in Figure~\ref{fig:DTW:EAMatrix:UB9} with $\ub=9$, we see that all the dependencies (black arrows) of $(4,1)$ are greater than $\ub$, and the same goes until $(6,1)$. It follows that we can start the following lines on the second columns, at $(3,2)$, effectively skipping the cells below $(3,1)$ and intuitively extending the border by one cell to the right. Note that the continuity condition, that all cells to the left of a discard point must also exceed $\ub$, is paramount. Without it, the cell at $(3,4)$ with value $14>9$ would be marked as a discard point and wrongfully prevent the optimal warping path from being computed. Now looking at Figure~\ref{fig:DTW:EAMatrix:UB6} with $\ub=6$, we see that the discard points reach the end of the fifth line, leading to early abandoning. Under this strategy, early abandoning is the natural consequence of extending the border over the full length of a line. This is a very effective way of early abandoning, requiring liitle bookkeeping. In contrast, PrunedDTW~\cite{silva_speeding_2018} maintains the minimum across a row and abandons when that minimum exceeds $\ub$. Algorithm~\ref{alg:DTWEA} shows how this works, in two stages. Lines now start at index \nextstart instead of index 1. The first line still starts at $1$, so we initialize \nextstart to $1$, and then update it by $j+1$ after encountering a discard point at $(i, j)$. The first stage, represented by the first inner loop, computes successive discard points on the same line. The condition on line~\ref{alg:DTWEA:cond1} enforces our continuity requirement: if \nextstart did not increase, the previous cell is not a discard point, and so neither is the current cell. Also, while in this loop, we know that a cell's left neighbour is greater then \ub and thus can be left out when looking for the smallest dependency (see line~\ref{alg:DTWEA:min}). In that regard, line~\ref{alg:DTW:inf} seems unnecessary -- it isn't as it also represents an assignment to the top left diagonal at the next iteration. We then have to check how we exited the first inner loop. If we reached the end of the line, we early abandon (line~\ref{alg:DTWEA:ea}), else we go into the second stage of the algorithm, embodied by the second inner loop, which is a normal DTW computation. \section{\label{sec-presentation-2}Early Abandoned PrunedDTW} In the previous section, we intuitively extended the left border to the right, leading to early abandoning when it reaches the end of the line. Unfortunately, we cannot do the same thing for the top border. This is because our strategy implicitly relies on the computation order (line by line) by moving forward where we start a line (updating $\nextstart$). In a line by line scan ``moving where a column starts'' does not make sense. However, we can move backward where we end a line pruning cells up to its actual end. As before, we ensure that all pruned cells would be greater than an upper bound $\ub$ by ensuring that their dependencies are greater than $\ub$. Adding this ``pruning from the right'' to the algorithm~\ref{alg:DTWEA} gives us the full EAPrunedDTW algorithm. Figures~\ref{fig:DTW:EAPrunedMatrix:UB9} and~\ref{fig:DTW:EAPrunedMatrix:UB6} present the EAPrunedDTW scenarios for $S$ and $T$, with $\ub=9$ and $\ub=6$. The blue cell shows an early abandoning position, and the black cells with red border are ``pruning points''. In a line, a pruning point starts a continuous sequence of cells greater than $\ub$ until the actual end of the line. In this regard, we have another natural match, now between the first pruning point at $(0,1)$ and the top border, as for all cells after $(0, 1)$ we indeed have $\infty>\ub$. Examining Figure~\ref{fig:DTW:EAPrunedMatrix:UB6} with $\ub=6$, the cell $(2,2)=8>\ub$ is not a pruning point as it is followed by cells below $\ub$. Notice that we can prune after the pruning points at $(1, 4)$ and $(4,3)$, but not after $(3,3)$. This is because a pruning point at $(i, j)$ carries information for the next line: it tells us that a cell at $(i+1, j'>j)$ can only depend on its left neighbour, its top and top left neighbours being greater than $\ub$. It follows that all cells following a cell $(i+1, j')>\ub$ will be greater than $\ub$. This allow us to both create a pruning point at $(i+1, j')$ and to prune the rest of the line. This explains why we prune after $(4,3)$ but not after $(3,3)$: the former can be pruned thanks to the latter! Moreover, cells after $(3,3)$ must be computed in order to check the continuity requirement, allowing $(3,3)$ to be a pruning point. Notice how, contrary to the discard points that extend the left border once and for all, pruning points create a ``right border'' that can go back and forth. Given a pruning point at $(i, j)$, we discussed what happens to the cells at $(i+1, j'>j)$. We now discuss the case of the cell immediately below, at $(i+1, j)$. This point is of particular interest as it is where our left and right borders can ``collide''. Either it depends on both its left and top left neighbours (e.g.~$(2,4)$), or only on its top left neighbour if it follows a discard point (e.g.~$(5,3)$ and $(1,1)$). In the latter case, we early abandon if the cell is greater than $\ub$ (e.g. the blue cell at $(5,3)$) as this would put $\nextstart$ in a pruned area, creating a ``border collision''. Note that PrunedDTW does prune ``from the left'' and ``from the right'', but does not take the border collision into account, early abandoning by checking the minimum value of the line. This allows EAPrunedDTW to abandon earlier than PrunedDTW. \begin{figure}[!t] \centering \subfloat[][\label{fig:DTW:EAPrunedMatrix:UB9}DTW Matrix for $S$ and $T$ with $\ub=9$]{% \includegraphics[trim=0 35 0 0, clip, width=0.45\textwidth]{figures/UB9_DTWEAPrunedMatrix.pdf} }% \hspace{\fill} \subfloat[][\label{fig:DTW:EAPrunedMatrix:UB6}DTW Matrix for $S$ and $T$ with $\ub=6$. The arrows show the dependencies actually evaluated]{% \includegraphics[trim=0 35 0 0, clip, width=0.45\textwidth]{figures/UB6_DTWEAPrunedMatrix.pdf} } \caption{\label{fig:DTWEAPruned}Illustration of EAPrunedDTW. The blue cell represents the point of early abandoning, white cells represent discard points, and dark gray cells represent pruning points. } \end{figure} \begin{algorithm2e}[!t] \small \SetAlgoLined \LinesNumbered \DontPrintSemicolon \SetKwData{c}{c} \SetKwFunction{cost}{cost} \KwIn{the time series $S$ and $T$, an upper bound $\ub$} \KwResult{$\DTW^{S,T}$} \co $\leftarrow$ shortest series between $S$ and $T$\; \li $\leftarrow$ longest series between $S$ and $T$\; (\prev, \curr) $\leftarrow$ arrays of length $l_{\co}+1$ filled with $\infty$\; $\curr{0} \leftarrow 0 $\; $\nextstart \leftarrow 1$\; $\prevpruningpoint \leftarrow 1$\; \label{alg:EAPrunedDTW:initpp} $\pruningpoint \leftarrow 0$\; \For{$i \leftarrow 1$ \KwTo $l_{\li}$}{ \swap{\prev, \curr}\; $j \leftarrow \nextstart$\; $\curr{j-1} \leftarrow \infty$\; \While{$j=\nextstart \wedge j < \prevpruningpoint$}{ $\c \leftarrow \cost{\li{i}, \co{j}} $\; $\curr{j} \leftarrow \c + \kwmin{\prev{j}, \prev{j-1}}$\; \label{alg:EAPrunedDTW:2m} \lIf{$\curr{j}\leq\ub$}{$\pruningpoint \leftarrow j+1$}\lElse{$\nextstart \leftarrow \nextstart+1$} $j\leftarrow j+1$\; } \While{$j < \prevpruningpoint$}{ $\c \leftarrow \cost{\li{i}, \co{j}} $\; $\curr{j} \leftarrow \c + \kwmin{\curr{j-1}, \prev{j}, \prev{j-1}}$\; \lIf{$\curr{j}\leq\ub$}{$\pruningpoint \leftarrow j+1$} $j\leftarrow j+1$\; } \If(\tcp*[h]{At \prevpruningpoint}){$j\leq{}l_{\co}$}{ \label{alg:EAPrunedDTW:pp} $\c \leftarrow \cost{\li{i}, \co{j}} $\; \If{$j=\nextstart$}{ \label{alg:EAPrunedDTW:testtp} $\curr{j} \leftarrow \c + \prev{j-1}$\; \lIf{$\curr{j}\leq\ub$}{$\pruningpoint \leftarrow j+1$}\lElse{\Return{$\infty$}} } \Else{ $\curr{j} \leftarrow \c + \kwmin{\curr{j-1}, \prev{j-1}}$\; \lIf{$\curr{j}\leq\ub$}{$\pruningpoint \leftarrow j+1$} } $j \leftarrow j+1$\; } \uElseIf{$j=\nextstart$}{\Return{$\infty$}} \label{alg:EAPrunedDTW:ea} \While{$j = \pruningpoint \wedge j \leq l_{\co}$}{ \label{alg:EAPrunedDTW:postpp} $\curr{j} \leftarrow \c + \curr{j-1}$\; \label{alg:EAPrunedDTW:1m} \lIf{$\curr{j}\leq\ub$}{$\pruningpoint \leftarrow j+1$} $j \leftarrow j+1$\; } $\prevpruningpoint \leftarrow \pruningpoint$\; } \lIf{$\prevpruningpoint > l_{\co}$}{ \Return{\curr{$l_{\co}$}} } \lElse{\Return{$\infty$}} \caption{\label{alg:EAPrunedDTW}Early Abandoning PrunedDTW.} \end{algorithm2e} EAPrunedDTW is described in algorithm~\ref{alg:EAPrunedDTW}, in four stages, building upon algorithm~\ref{alg:DTWEA}. We introduce two new variables. The first one, \prevpruningpoint, represents the pruning point of the previous line and is initialized to 1 (for the first pruning point at $(0,1)$, line~\ref{alg:EAPrunedDTW:initpp}). The second one, \pruningpoint, represents the pruning point being computed in the current line, and is initialized to 0. This concurs with our update strategy: we assume that a cell is a pruning point unless proven otherwise. In other words, if the current cell is less than $\ub$, we assume that the next one is a pruning point. Either it is, and \pruningpoint being left untouched will end up correctly set, or it is not and \pruningpoint will be updated again. The first two stages, embodied by the first two inner loops, are similar to the ones in Algorithm\ref{alg:DTWEA}. However, the loops now update \pruningpoint, only go up to \prevpruningpoint, and we early abandon in the third stage. The third stage corresponds to the column of the previous pruning point (line~\ref{alg:EAPrunedDTW:pp}). If we are still within bounds, we check if the previous cell is a discard point ($\nextstart=j$ at line~\ref{alg:EAPrunedDTW:testtp} tests if we reached this position while advancing $\nextstart$, i.e.~while encountering discard point), we only look at the diagonal, early abandoning if the computed value is greater than $\ub$. Else, we compute the DTW value based on the left and diagonal. In both cases we update \pruningpoint. If we are not within bound, we reached the end of the line. If we did so with the first loop (again tested with $\nextstart=j$), we are in the same early abandoning situation as in Algorithm~\ref{alg:DTWEA}, and we early abandon (line~\ref{alg:EAPrunedDTW:ea}). We finally reach the fourth stage, after the column \prevpruningpoint (line~\ref{alg:EAPrunedDTW:postpp}). The only possible dependency is now on the left, and we can skip the rest of the line as soon as we encounter a value greater than $\ub$. We do this by checking \pruningpoint against $j$, ensuring that it is being updated. The final check before returning ensures that we computed the last cell of the line in the last iteration, as we may have stopped the computation in the last stage. Decomposing the algorithm in several stages is the main underlying contribution of this paper. Whereas the standard DTW loop used by PrundedDTW requires that the minimum of three previous values be computed for each new cell of the matrix, our decomposition allows many cells to be updated considering only one (line~\ref{alg:EAPrunedDTW:1m}) or two (line~\ref{alg:EAPrunedDTW:2m}) previous values, saving considerable computation. \section{\label{sec-experimentations}Experiments} We created the ``UCR MON Suite'' \footnote{UCR from Monash University\newline\hspace*{1.8em}\url{https://github.com/MonashTS/UCR-Monash}}, available online with the experimental results and analysis script. Just like the ``UCR USP Suite'' \footnote{UCR from the Universidade de São Paulo\newline\hspace*{1.8em}\url{https://sites.google.com/view/ucruspsuite}} which uses PrunedDTW, it is a modification of the original ``UCR Suite''\footnote{\url{http://www.cs.ucr.edu/~eamonn/UCRsuite.html}}. It uses our EAPrunedDTW algorithm with support for a warping window and upper bound tightening (present in both the UCR and the UCR USP suites). Given EAPrunedDTW's efficiency, it is also interesting to assess how it performs without lower bounding, so we added the fourth variant ``UCR MON nolb''. Note that this last variant cannot tighten the upper bound, as this relies on information computed by lower bounds. We compare the four suites on the same computer equipped with an AMD Opteron 6338P at 2.3Ghz (RAM is not limiting). We reproduced the experiments from the UCR USP paper~\cite{silva_speeding_2018} over the same datasets. See~\cite{silva_speeding_2018} for a detailed description, and how they have been obtained. The data originated from: \begin{description} \item[\cite{bachlin_wearable_2010}] Freezing of Gait (FoG) \item[\cite{pettersen_soccer_2014}] Athletic performance monitoring (Soccer) \item[\cite{reiss_introducing_2012}] Physical activity monitoring (PAMAP2) \item[\cite{goldberger_physiobank_2000,moody_impact_2001}] MIT-BIH Arrhythmia Database (ECG) \item[\cite{murray_data_2015}] Electrical load measurements (REFIT) \item[\cite{kachuee_cuff-less_2015}] Photoplethysmography (PPG) \end{description} Each dataset is composed of a long reference $R$ series, and 5 queries $Q_{1 \leq n \leq 5}$ of length 1024. For each $Q_n$, the algorithm locates the closest subsequence in $R$ under several conditions of query's length and warping window ratio of that length. A query's length can be 128, 256, 512 and 1024 (taking a prefix for lengths smaller than 1024), and the window's ratio is taken among $\{0.1, 0.2, 0.3, 0.4, 0.5\}$. This generates 20 experiments per query, 100 experiments per dataset and so 600 experiments per algorithm. We note that our results for the UCR and UCR USP suites are in line with those published in~\cite{silva_speeding_2018}. We present the results in Figure~\ref{fig:exp}. For each data set we indicate the proportion of the DTW computations that are pruned by each of the three lower bounds used in the UCR Suite, and the remaining proportion for which the DTW computation is performed. Note that our algorithm is only applied to these latter cases. The more computations that are pruned, the less opportunity our algorithm has to demonstrate its relative capacity. UCR MON is overall the fastest, completing the experiments in $473150$ seconds (5 days 11h25m50s), which is $8.778$ times faster than UCR ($4153309$ seconds, i.e.{} 48 days 1h41m49s), and $2.036$ times faster than UCR USP ($963251$ seconds, i.e.{} 11 days 3h34m11s, $4.312$ times faster than UCR). Its advantage is clear for long series (length 1024, Figure \ref{fig:exp:lenght}), where it is faster than UCR from 3.73 times (FoG) up to 9.72 times (PPG), and is faster than UCR USP from 1.93 (PPG) up to 3.6 (FoG). In some cases the overhead is not compensated by the gain, and our algorithm is slower but the difference stays overall small. Our algorithm is slower than UCR in 44 ($7.3\%$) cases over 600 by an average of $0.971$ seconds, and at most by $9.06$ seconds. It is slower than UCR USP in 66 ($11\%$) cases by an average of $1$ seconds, and at most by $10.98$ seconds. In comparison, UCR USP is slower than UCR in 108 ($18\%$) cases, by an average of $55.11$ seconds, and at most by $986.15$ seconds. The most interesting results come from UCR MON nolb. They show that lower bounds are dispensable, UCR MON nolb completing the experiments in $644652$ seconds (7 days 11h04m12s). It is faster overall than both UCR (speedup $6.443$) and UCR USP (speedup $1.494$). It is however slower than UCR in 364 ($60.06\%$) cases, by an average of $174.372$ seconds, and at most $6392$ seconds. Higher ratios of DTW computation lead to higher differences, especially as the window size and length increase. A major exception is the REFIT dataset: even if it has a higher ratio of DTW computations than PAMAP2, UCR MON nolb only starts to be competitive with a length of 1024. Another interesting observation is that varying the window size has less impact on our algorithms than the others. Again, this is very remarkable with REFIT. We explain this by the following: at first, a small window (around $0.1$, $0.2$) gives a fast result without leaving room for a lot of pruning. As the window increases (around $0.3$, $0.4$), more and more pruning becomes possible, compensating both for the associated overhead and the increased numbers of cells to compute. This continues up to a point (around $0.4$, $0.5$) where increasing the window is nearly fully compensated by pruning, with most extra cells being pruned. Further increases to the window result in ever more pruning, having little overall impact on runtime. Interestingly, UCR USP does not exhibit this behaviour. \begin{figure*}[!p] \centering \subfloat[][\label{fig:exp:lenght}Average runtimes by varying the query length. Plotted values represent the average runtime over 5 queries and varying window ratio. ]{% \includegraphics[width=0.81\linewidth]{figures/time_per_qlength.pdf} }% \vspace{1ex} \subfloat[][\label{fig:exp:wratio}Average runtimes by varying the window ratio. Plotted values represent the average runtime over 5 queries and varying query length. ]{% \includegraphics[width=0.81\linewidth]{figures/time_per_wratio.pdf} } \caption{\label{fig:exp} Average runtimes per dataset of UCR, UCR USP, UCR MON and UCR MON without lower bound, by query length and window ratios. Also show effectiveness of lower bounds pruning per datasets, applicable for all but UCR\_MON\_nolb which is 100\% DTW. } \end{figure*} \section{\label{sec-conclusion}Conclusion and future work} We present EAPrunedDTW, a new version of the PrunedDTW algorithm that supports highly effective pruning and early abandoning. We implemented it in the UCR Suite, and show it being currently the overall fastest available way of performing similarity search. The main innovations of EAPrunedDTW are to use the collision of the left and right borders to trigger early abandoning, saving the need to keep track of the minimum value so far, and a decomposition that allows many cells to be updated by considering only one or two previous values as opposed to the three previous values always required by PrunedDTW. We also show that similarity search is tractable without using lower bounds, opening it to distance measures other than DTW. Indeed, many elastic measures share the same structure as DTW \cite{marteau_time_2009}, only differing in their cost function, without having lower bounds that are as efficient to compute, if any. In essence we should be able to speed up most of elastic distances, improving computation time in most scenarios where best candidates are required. This includes nearest neighbour classification, which in turn is widely used in several ensemble classifiers. We note that the Elastic Ensemble was removed from a revision of Hive Cote due to its computation time \cite{bagnall_tale_2020}, something that may not be necessary with our algorithm. Our next steps will be to adapt our algorithm to other elastic distances and implement them in ensemble classifiers such as Elastic Ensemble~\cite{lines_time_2015}, Proximity Forest~\cite{lucas_proximity_2019} and TS-Chief~\cite{shifaz_ts-chief_2020}. \printbibliography \end{document}
{'timestamp': '2020-10-13T02:26:23', 'yymm': '2010', 'arxiv_id': '2010.05371', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05371'}
arxiv
\section{Introduction} In this paper, we consider the task of predicting the etch rate in silicon wafer production. While we frame this as a prediction task, our interest is in gaining an insight into the sources of process variability in plasma etching rather than very accurate prediction. Because we have insight as an objective we are interested in $k$-Nearest Neighbour ($k$-NN) classifiers because of their interpretability. In the production of silicon wafers, the etch rate is critically important because it directly influences the precision of the silicon structures. If a transistor gate length is too large the device speed is reduced, it if is too small it will leak. So it is important to be able to control the etch rate very precisely\cite{macgearailt2015process,flamm1981design}. It is common to describe plasma etching as a cooking process or a recipe. As the recipe progresses different gases are introduced in the chamber to promote specific effects. Optical emission spectroscopy (OES) is the most widely used technique to track what is going on within the chamber \cite{shul1997high}. In the data we analyze here, the outcome is the etch rate, and the predictive variables are time-series spectra across 2048 wavelengths. The process takes about 42 seconds, the spectra are sampled at 1.3Hz so each of the 2048 OES time-series contains about 57 ticks \cite{macgearailt2015process}. With our objective of identifying sources of process variability, we are interested in identifying systematic differences in OES time-series that are predictive of differences in etch rate. In the next section, we introduce the problem domain and describe the data on which the analysis is based. In section \ref{sec:models} we describe the prediction models we use and we discuss the results of the evaluation in section \ref{sec:eval}. Some conclusions and directions for future work are presented in section \ref{sec:conc}. \section{The Problem Domain} Plasma etching is an integral part of the pipeline in wafer manufacturing. This process is conducted within specialised etch chambers where etchant gases in plasma form are directed towards the wafer surface where the exposed material is removed. This removal of material contributes to the formation of semiconductor components on the wafer \cite{flamm1981design,lynn2012global,lynn2012real}. The etching process involves chemical reactions that emit a spectrum of frequencies of electromagnetic radiation, which can be captured by a spectroscope. The captured spectroscopic data for each wafer is a high dimensional multivariate time series where each dimension represents one wavelength through a period of time during the etching process \cite{macgearailt2015process}. \begin{figure}[H] \includegraphics[width=330pt]{images/spec.jpg} \caption{Spectroscopic representation of a wafer datum.} \label{fig:spec_data} \end{figure} Figure~\ref{fig:spec_data} shows the spectroscopic data for a typical plasma etching process in 3D. There are 2048 wavelengths plotted on the x-axis but it is clear that interesting peaks show up only on a small subset of these. Time is plotted on the y-axis and the height (z-axis) shows the intensity. In the analysis presented here the machine learning task is to predict the etch rate from this time-series data (a regression task). In earlier work, this has been done by representing the time series by four summary statistics and using multivariate regression on these statistics \cite{lynn2012global,lynn2012real}. The four statistics are produced by dividing the time series into two stages and representing each stage using mean and standard deviation. The two stages are clearly visible in Figure \ref{fig:spec_data}. \subsection{The Data} \label{sec:data} Altogether we have data on the production of \num{1771} wafers. For each of these wafers, we have an estimate of the average etch rate which we take as the dependent variable. As stated already, our ML objective is to predict the etch rate, a regression task. For each wafer, we have the full OES time-series as shown in Figure \ref{fig:spec_data}. This is sampled across \num{2048} wavelengths and contains about 57 ticks for each wavelength. Rather than consider all \num{2048} wavelengths, in consultation with a domain expert, we reduced this to 38 wavelengths with peaks known to correspond to the key compounds involved in the plasma etching process. It is clear from looking at the spectra in Figures \ref{fig:spec_data} that the process has two distinct stages. For this reason, the time-series data can be significantly reduced by simply representing each spectrum time series by four aggregate statistics, the mean and standard deviation in stages 1 and 2. In this way, each wafer can be represented by $2048 \times 4$ data points rather than $2048 \times 60$ data points in the full time-series representation. \section{Prediction Models}\label{sec:models} Given our objective of gaining insights from the data we are interested in $k$-Nearest Neighbour regression using DTW on the spectra time-series as the similarity measure. The analysis of time-series classification algorithms presented by Bagnall \emph{et al.} \cite{bagnall2017great} shows that 1-NN DTW is an effective method for time-series classification, if not as accurate as state-of-the-art ensemble methods such as COTE. We compare $k$-NN DTW against two base-line predictors, multivariate regression on the aggregate statistics and $k$-NN on the aggregate statistics. So we consider three prediction models: \begin{enumerate} \item \textbf{R-4M} Multivariate regression using the four aggregate statistics. \item \textbf{$k$-NN-4M} $k$-NN regression ($k=5$) using the four aggregate statistics. \item \textbf{$k$-NN DTW} $k$-NN using DTW ($k=5$) as the similarity measure (see section \ref{sec:DTW} for details). \end{enumerate} When these are compared they are always compared on the same underlying wavelengths; for instance in Figure \ref{fig:comparison} they are compared over 1 to 11 wavelengths. \subsection{Dynamic Time Warping}\label{sec:DTW} To find the distance between two data series, the Euclidean formula is a popular choice. But when dealing with time-series data where the series may be displaced in time, the Euclidean distance may be large when the two series are similar, just off slightly on the timeline. To tackle this situation Dynamic Time Warping offers us the malleability of mapping the two data series in a non-linear fashion by warping the time axis \cite{keogh2001derivative}. It creates a cost matrix where the cells contain the distance value of the corresponding data-points and then finds the shortest path through the grid, which minimizes the total distance between them. \begin{figure}[H]% \centering \subfloat[Two time series displaced in time.]{{\includegraphics[width=5.65cm]{images/dtw-blank.png} }}% \subfloat[Mapping of data-points without warping.]{{\includegraphics[width=5.65cm]{images/dtw-linear.png} }}% \qquad \subfloat[Mapping of data-points with warping.]{{\includegraphics[width=5.65cm]{images/dtw-warp.png} }}% \caption{Dynamic Time Warping.}% \label{fig:dtw}% \end{figure} The figure above illustrates the non-linear mapping done by DTW when we give it a suitable extent of data-points, i.e. max warping window, to consider while fetching the shortest path. Initially, when we restrict our algorithm with no warping being allowed, the data points are linearly mapped between the two data series based on the common time axis value. As seen in Figure~\ref{fig:dtw}(b), the algorithm fails to map the trend of a time series data to another. But when we grant the DTW algorithm the flexibility of considering a warping window, the algorithm performs remarkably when mapping the data-points following the trend of the time-series data, which can be visualized in Figure~\ref{fig:dtw}(c). \section{Evaluation}\label{sec:eval} As mentioned in the Introduction, we are more concerned with gaining insights into the factors that influence outcomes that the ability to predict the outcomes themselves. For this reason, we are evaluating the potential of DTW to reveal systematic patterns in the data. \subsection{Parameter Selection} As stated in section \ref{sec:data}, domain knowledge indicates that the \num{2048} wavelengths can be reduced to \num{38}. Through a preliminary feature selection analysis, this was reduced further to 11 wavelengths that were found to be predictive for at least one of the three models. In the next subsection we report on the impact of these 11 wavelengths on prediction accuracy then we conclude the evaluations with some comments on insights. For $k$-NN neighbourhood size ($k$) is a crucial parameter governing performance. Fig. \ref{fig:parameter}(a) shows the impact of different values of $k$ for the $k$-NN-4M model. Given that the best performance is achieved when $k=5$ we use this for both $k$-NN models. \begin{figure}[H]% \centering \subfloat[$k$-NN-4M performance when trained on 4 summary metrics of a single wavelength against different neighbourhood sizes.]{{\includegraphics[width=5.65cm]{images/neighbours.png} }}% \qquad \subfloat[$k$-NN-DTW performance when trained on a single wavelength against different warping-window sizes.]{{\includegraphics[width=5.65cm]{images/warping_window.png} }}% \caption{Effect on the performance of $k$-Nearest Neighbour models with different parameters.}% \label{fig:parameter}% \end{figure} For DTW the size of the warping window has an impact \cite{ratanamahatana_keogh_2005} so we tried different values between 0 and 4. Fig. \ref{fig:parameter}(b) shows the impact of the warping-window on the performance of $k$-NN-DTW model trained on a single wavelength. The model performs the worst when we set the warping-window size to be 0, which is a simple Euclidean distance calculation between the two time-series data. The model performs significantly better when we allow warping but the performance does not improve above a warping window size of one so that parameter value was chosen. \subsection{Prediction Accuracy} Figure \ref{fig:comparison} summarizes the results of a 10-fold cross-validation analysis of the three prediction models using the 11 wavelengths. For each wavelength, the $k$-NN-DTW model has access to the full time-series representation and the other two models use the four summary statistics only. Unsurprisingly, when only a single wavelength is considered, the Mean Absolute Percentage Error (MAPE) of the DTW model is significantly better than the models using the four summary statistics. However, as more wavelengths are added the performance of the $k$-NN-DTW model does not improve and the other models close the gap. \begin{figure}[h] \centering \includegraphics[width=9cm]{images/model_comparison_stdev_txt.png} \caption{Comparison between different regression models. The shading shows the standard deviation.} \label{fig:comparison} \end{figure} If prediction accuracy were our core objective then it seems that DTW does not offer any benefits because a feature vector based on summary statistics from a wider set of wavelengths provides accuracy that is even slightly better. The results in Figure \ref{fig:comparison} suggest that $k$-NN with four summary statistics from 11 wavelengths (44 features) has the lowest MAPE score. This might be interpreted as a variation on the modern wisdom that ``\emph{more data is better than smarter algorithms}" \cite{halevy2009unreasonable}. It is a variation in the sense that the benefits of big data are understood to derive from a large number of examples. Whereas in our case the advantage comes from more extensive data on each example. If summary statistics are available across many wavelengths there is no benefit in using DTW (the smart algorithm in this case). \subsection{Insights} The objective in using DTW to identify nearest neighbours was to see if an interpretable measure of similarity would offer insights into the factors influencing outcomes. To test this we selected two wafers, one with the highest etch rate and one with the lowest etch rate and examined their nearest and furthest neighbours as measured by DTW on the first wavelength in Figure \ref{fig:comparison} (564.96nm). Looking at the wafer with the high etch rate first (Figure \ref{fig:insight} (a)) we see that it matches its nearest and furthest neighbours well all along the time series until the end of the second phase where the intensity of the wavelength starts to drop off. It is clear that the nearest neighbour matches perfectly here while this region of the time series accounts for the main difference between the query case and it's most distant neighbour. \begin{figure}[H]% \centering \subfloat[Wafer with highest etch rate.]{{\includegraphics[width=5.65cm]{images/thigh.jpg} }}% \qquad \subfloat[Wafer with lowest etch rate.]{{\includegraphics[width=5.65cm]{images/tlow.jpg} }}% \caption{Nearest and furthest neighbours of a wafer based on a single informative wavelength.}% \label{fig:insight}% \end{figure} When we turn to the wafer with the low etch rate (Figure \ref{fig:insight} (b)) it appears that the same region of the time-series seems also to account for the difference between the query case and the most different neighbour. This supports the conclusion that this phase of the process is the source of variability in the etch rate. \section{Conclusions \& Future Work}\label{sec:conc} While the work reported here is about predictive analytics the motivation is more to discover insights into factors that influence outcomes rather than generating very accurate predictions. For this reason, we focus on $k$-NN DTW as a model that is interpretable. While this research is still ongoing we report two findings here: \begin{itemize} \item Using DTW does improve prediction accuracy over models that use summary statistics of the time series on a single wavelength. However, when other wavelengths are considered the benefits of using DTW are no longer apparent. \item DTW does seem to offer interpretability benefits through the analysis of nearest and furthest neighbours to identify regions of the time series where differences are apparent. \end{itemize} \section{ Acknowledgments} This publication has resulted from research supported in part by a grant from Science Foundation Ireland (SFI) under Grant Number 16/RC/3872 and is co-funded under the European Regional Development Fund.
{'timestamp': '2020-10-13T02:22:55', 'yymm': '2010', 'arxiv_id': '2010.05270', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05270'}
arxiv
\section{MMH$^*$}\label{Sec 1} Universal hashing, introduced by Carter and Wegman \cite{CW}, is of great importance in computer science with many applications. Cryptography, information security, complexity theory, randomized algorithms, and data structures are just a few areas that universal hash functions and their variants have been used as a fundamental tool. In \cite{HK}, definitions of various kinds of universal hash functions gathered from the literature are presented; we mention some of them here. \begin{definition} \label{def:Uni hash} Let $H$ be a family of functions from a domain $D$ to a range $R$. Let $\varepsilon$ be a constant such that $\frac{1}{|R|} \leq \varepsilon < 1$. The probabilities below are taken over the random choice of hash function $h$ from the set $H$. \noindent\textit{(i)} The family $H$ is a {\it universal family of hash functions} if for any two distinct $x,y\in D$, we have $\text{Pr}_{h \leftarrow H}[h(x) = h(y)] \leq \frac{1}{|R|}$. Also, $H$ is an {\it $\varepsilon$-almost-universal} ($\varepsilon$-AU) {\it family of hash functions} if for any two distinct $x,y\in D$, we have $\text{Pr}_{h \leftarrow H}[h(x) = h(y)] \leq \varepsilon$. \noindent\textit{(ii)} Suppose $R$ is an Abelian group. The family $H$ is a $\triangle$-{\it universal family of hash functions} if for any two distinct $x,y\in D$, and all $b\in R$, we have $\text{Pr}_{h \leftarrow H}[h(x) - h(y) = b] = \frac{1}{|R|}$, where ` $-$ ' denotes the group subtraction operation. Also, $H$ is an {\it $\varepsilon$-almost-$\triangle$-universal} ($\varepsilon$-A$\triangle$U) {\it family of hash functions} if for any two distinct $x,y\in D$, and all $b\in R$, we have $\text{Pr}_{h \leftarrow H}[h(x) - h(y) = b] \leq \varepsilon$. \end{definition} It is worth mentioning that $\varepsilon$-A$\triangle$U families have also important applications in computer science, in particular, in cryptography. For example, these families can be used in message authentication. Informally, it is possible to design a message authentication scheme using $\varepsilon$-A$\triangle$U families such that two parties can exchange signed messages over an unreliable channel and the probability that an adversary can forge a valid signed message to be sent across the channel is at most $\varepsilon$ (\cite{HK}). The following family, named MMH$^*$ by Halevi and Krawczyk \cite{HK} in 1997, is a well-known $\triangle$-universal hash function family. \begin{definition}\label{def:MMH$^*$} Let $p$ be a prime and $k$ be a positive integer. The family MMH$^*$ is defined as follows: \begin{align}\label{MMH*} \text{MMH}^*:=\lbrace g_{\mathbf{x}} \; : \; \mathbb{Z}_p^k \rightarrow \mathbb{Z}_p \; | \; \mathbf{x}\in \mathbb{Z}_p^k \rbrace, \end{align} where \begin{align}\label{MMH* for 2} g_{\mathbf{x}}(\mathbf{m}) := \mathbf{m} \cdot \mathbf{x} \pmod{p} = \sum_{i=1}^k m_ix_i \pmod{p}, \end{align} for any $\mathbf{x}=\langle x_1, \ldots, x_k \rangle \in \mathbb{Z}_p^k$, and any $\mathbf{m}=\langle m_1, \ldots, m_k \rangle \in \mathbb{Z}_p^k$. \end{definition} It appears that Gilbert, MacWilliams, and Sloane \cite{GMS} first discovered MMH$^*$ (but in the finite geometry setting). However, many resources attribute MMH$^*$ to Carter and Wegman \cite{CW}. Halevi and Krawczyk \cite{HK} proved that MMH$^*$ is a $\triangle$-universal family of hash functions. We also remark that, recently, Leiserson et al. \cite{LSS} rediscovered MMH$^*$ (called it ``DOTMIX compression function family") and using the same method as Halevi and Krawczyk, proved that DOTMIX is $\triangle$-universal. They then apply this result to the problem of deterministic parallel random-number generation for dynamic multithreading platforms in parallel computing. \begin{theorem} \label{thm:MMH* UNI} The family \textnormal{MMH}$^*$ is a $\triangle$-universal family of hash functions. \end{theorem} \section{GMMH$^*$}\label{Sec 2} Given that, in the definition of MMH$^*$, the modulus is a prime, it is natural to ask what happens if the modulus is an arbitrary integer $n>1$. Is the resulting family still $\triangle$-universal? If not, what can we say about $\varepsilon$-almost-universality or $\varepsilon$-almost-$\triangle$-universality of this new family? This is an interesting and natural problem, and while it has a simple solution (see, Theorem~\ref{thm:GMMH* UNI} below), to the best of our knowledge there are no results regarding this problem in the literature. First, we define a generalization of MMH$^*$, namely, GMMH$^*$, with the same construction as MMH$^*$ except that we use an arbitrary integer $n>1$ instead of prime $p$. \begin{definition}\label{def:GMMH$^*$} Let $n$ and $k$ be positive integers $(n>1)$. The family GMMH$^*$ is defined as follows: \begin{align}\label{GMMH*} \text{GMMH}^*:=\lbrace h_{\mathbf{x}} \; : \; \mathbb{Z}_n^k \rightarrow \mathbb{Z}_n \; | \; \mathbf{x}\in \mathbb{Z}_n^k \rbrace, \end{align} where \begin{align}\label{GMMH* for 2} h_{\mathbf{x}}(\mathbf{m}) := \mathbf{m} \cdot \mathbf{x} \pmod{n} = \sum_{i=1}^k m_ix_i \pmod{n}, \end{align} for any $\mathbf{x}=\langle x_1, \ldots, x_k \rangle \in \mathbb{Z}_n^k$, and any $\mathbf{m}=\langle m_1, \ldots, m_k \rangle \in \mathbb{Z}_n^k$. \end{definition} MMH$^*$ has found important applications, however, in applications that, for some reasons, we have to work in the ring $\mathbb{Z}_n$, the family GMMH$^*$ may be used. The following result, proved by D. N. Lehmer \cite{LEH2}, is the main ingredient in the proof of Theorem~\ref{thm:GMMH* UNI}. \begin{proposition}\label{Prop: lin cong} Let $a_1,\ldots,a_k,b,n\in \mathbb{Z}$, $n\geq 1$. The linear congruence $a_1x_1+\cdots +a_kx_k\equiv b \pmod{n}$ has a solution $\langle x_1,\ldots,x_k \rangle \in \mathbb{Z}_{n}^k$ if and only if $\ell \mid b$, where $\ell=\gcd(a_1, \ldots, a_k, n)$. Furthermore, if this condition is satisfied, then there are $\ell n^{k-1}$ solutions. \end{proposition} Now, we are ready to state and prove the following result about $\varepsilon$-almost-$\triangle$-universality of GMMH$^*$. \begin{theorem} \label{thm:GMMH* UNI} Let $n$ and $k$ be positive integers $(n>1)$. The family \textnormal{GMMH}$^*$ is $\frac{1}{p}$-\textnormal{A}$\triangle$\textnormal{U}, where $p$ is the smallest prime divisor of $n$. This bound is tight. \end{theorem} \begin{proof} Suppose that $n$ has the prime factorization $n=p_1^{r_1}\ldots p_s^{r_s}$, where $p_1 < \cdots < p_s$ are primes and $r_1,\ldots,r_s$ are positive integers. Let $\mathbf{m}=\langle m_1, \ldots, m_k \rangle \in \mathbb{Z}_n^k$ and $\mathbf{m}'= \langle m'_1, \ldots, m'_k \rangle \in \mathbb{Z}_n^k$ be any two distinct messages. Put $\mathbf{a}=\langle a_1,\dots,a_k \rangle = \mathbf{m}-\mathbf{m}'$. For every $b\in \mathbb{Z}_n$ we have \begin{align*} h_{\mathbf{x}}(\mathbf{m})-h_{\mathbf{x}}(\mathbf{m'})=b \Longleftrightarrow \sum_{i=1}^k m_ix_i - \sum_{i=1}^k m'_ix_i \equiv b \pmod{n} \Longleftrightarrow \sum_{i=1}^k a_ix_i \equiv b \pmod{n}. \end{align*} Note that since $\langle x_1,\ldots,x_k \rangle \in \mathbb{Z}_{n}^k$, we have $n^k$ ordered $k$-tuples $\langle x_1, \ldots, x_k \rangle$. Also, since $\mathbf{m}\not=\mathbf{m}'$, there exists some $i_0$ such that $a_{i_0} \not= 0$. Now, we need to find the maximum number of solutions of the above linear congruence over all choices of $\mathbf{a}=\langle a_1,\dots,a_k \rangle \in \mathbb{Z}_n^k \setminus \lbrace \mathbf{0} \rbrace$ and $b\in \mathbb{Z}_n$. By Proposition~\ref{Prop: lin cong}, if $\ell=\gcd(a_1, \ldots, a_k, n) \nmid b$ then the linear congruence $a_1x_1+\cdots +a_kx_k\equiv b \pmod{n}$ has no solution, and if $\ell=\gcd(a_1, \ldots, a_k, n) \mid b$ then the linear congruence has $\ell n^{k-1}$ solutions. Thus, we need to find the maximum of $\ell=\gcd(a_1, \ldots, a_k, n)$ over all choices of $\mathbf{a}=\langle a_1,\dots,a_k \rangle \in \mathbb{Z}_n^k \setminus \lbrace \mathbf{0} \rbrace$. Clearly, $$ \max_{\mathbf{a}=\langle a_1,\dots,a_k \rangle \in \mathbb{Z}_n^k \setminus \lbrace \mathbf{0} \rbrace}\gcd(a_1, \ldots, a_k, n) $$ is achieved when $a_{i_0}=p_1^{r_1-1}p_2^{r_2}\ldots p_s^{r_s}=\frac{n}{p_1}$, and $a_i=0$ ($i \not= i_0$). So, we get $$ \max_{\mathbf{a}=\langle a_1,\dots,a_k \rangle \in \mathbb{Z}_n^k \setminus \lbrace \mathbf{0} \rbrace} \gcd(a_1, \ldots, a_k, n)=p_1^{r_1-1}p_2^{r_2}\ldots p_s^{r_s}=\frac{n}{p_1}. $$ Therefore, for any two distinct messages $\mathbf{m}, \mathbf{m}' \in \mathbb{Z}_n^k$, and all $b\in \mathbb{Z}_n$, we have \begin{align*} \text{Pr}_{h_{\mathbf{x}} \leftarrow \text{GMMH}^*}[h_{\mathbf{x}}(\mathbf{m})-h_{\mathbf{x}}(\mathbf{m'})=b] \leq \max_{\mathbf{a}=\langle a_1,\dots,a_k \rangle \in \mathbb{Z}_n^k \setminus \lbrace \mathbf{0} \rbrace} \frac{n^{k-1}\gcd(a_1, \ldots, a_k, n)}{n^k}= \frac{1}{p_1}. \end{align*} This means that GMMH$^*$ is $\frac{1}{p_1}$-A$\triangle$U. Clearly, this bound is tight; take, for example, $a_1=\frac{n}{p_1}$ and $a_2=\cdots=a_k=0$. \end{proof} \begin{corollary} If in \textnormal{Theorem~\ref{thm:GMMH* UNI}} we let $n$ be a prime then we obtain \textnormal{Theorem~\ref{thm:MMH* UNI}}. \end{corollary} \begin{proof} When $n$ is prime, $\gcd_{\mathbf{a}=\langle a_1,\dots,a_k \rangle \in \mathbb{Z}_n^k \setminus \lbrace \mathbf{0} \rbrace}(a_1, \ldots, a_k, n)=1$, so we get $\triangle$-universality. \end{proof} We remark that if in the family GMMH$^*$ we let the keys $\mathbf{x}=\langle x_1, \ldots, x_k \rangle \in \mathbb{Z}_n^k$ satisfy the general conditions $\gcd(x_i,n)=t_i$ ($1\leq i\leq k$), where $t_1,\ldots,t_k$ are given positive divisors of $n$, then the resulting family, which was called GRDH in \cite{BKSTT2}, is no longer `always' $\varepsilon$-A$\triangle$U. In fact, it was shown in \cite{BKSTT2} that the family GRDH is $\varepsilon$-A$\triangle$U for some $\varepsilon<1$ if and only if $n$ is odd and $\gcd(x_i,n)=t_i=1$ (that is, $x_i \in \mathbb{Z}_n^{*}$) for all $i$. Furthermore, if these conditions are satisfied then GRDH is $\frac{1}{p-1}$-A$\triangle$U, where $p$ is the smallest prime divisor of $n$ (this bound is also tight). This result is then applied in giving a generalization of a recent authentication code with secrecy. A key ingredient in the proofs in \cite{BKSTT2} is an explicit formula for the number of solutions of restricted linear congruences (a restricted version of Proposition~\ref{Prop: lin cong}), recently obtained by Bibak et al. \cite{BKSTT}, using properties of Ramanujan sums and of the finite Fourier transform of arithmetic functions. \section*{Acknowledgements} The authors would like to thank the editor and anonymous referees for helpful comments. During the preparation of this work the first author was supported by a Fellowship from the University of Victoria (UVic Fellowship).
{'timestamp': '2020-10-13T02:27:35', 'yymm': '2010', 'arxiv_id': '2010.05420', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05420'}
arxiv
\section{Experiments} \begin{figure*}[t!] \setlength\tabcolsep{1pt} \def1{0.5} \centering \begin{tabular}{cccccccc} \includegraphics[width=0.12\linewidth]{images/results/images/Paraguay_657443_swir_1124_592.png} & \includegraphics[width=0.12\linewidth]{images/results/gt/Paraguay_657443_swir_1124_592.png} & \includegraphics[width=0.12\linewidth]{images/results/unet_refiner/Paraguay_657443_swir_1124_592.png} & \includegraphics[width=0.12\linewidth]{images/results/swir_synth/Paraguay_657443_swir_1124_592.png} & \includegraphics[width=0.12\linewidth]{images/results/swir_synth_thresh/Paraguay_657443_swir_1124_592.png} & \includegraphics[width=0.12\linewidth]{images/results/full/Paraguay_657443_swir_1124_592.png} & \includegraphics[width=0.12\linewidth]{images/results/swir_synth_nir/Paraguay_657443_swir_1124_592.png} & \includegraphics[width=0.12\linewidth]{images/results/full_nir/Paraguay_657443_swir_1124_592.png}\\ \includegraphics[width=0.12\linewidth]{images/results/images/Ghana_868803_swir_592_50.png} & \includegraphics[width=0.12\linewidth]{images/results/gt/Ghana_868803_swir_592_50.png} & \includegraphics[width=0.12\linewidth]{images/results/unet_refiner/Ghana_868803_swir_592_50.png} & \includegraphics[width=0.12\linewidth]{images/results/swir_synth/Ghana_868803_swir_592_50.png} & \includegraphics[width=0.12\linewidth]{images/results/swir_synth_thresh/Ghana_868803_swir_592_50.png} & \includegraphics[width=0.12\linewidth]{images/results/full/Ghana_868803_swir_592_50.png} & \includegraphics[width=0.12\linewidth]{images/results/swir_synth_nir/Ghana_868803_swir_592_50.png} & \includegraphics[width=0.12\linewidth]{images/results/full_nir/Ghana_868803_swir_592_50.png}\\ \includegraphics[width=0.12\linewidth]{images/results/images/Paraguay_657443_swir_592_592.png} & \includegraphics[width=0.12\linewidth]{images/results/gt/Paraguay_657443_swir_592_592.png} & \includegraphics[width=0.12\linewidth]{images/results/unet_refiner/Paraguay_657443_swir_592_592.png} & \includegraphics[width=0.12\linewidth]{images/results/swir_synth/Paraguay_657443_swir_592_592.png} & \includegraphics[width=0.12\linewidth]{images/results/swir_synth_thresh/Paraguay_657443_swir_592_592.png} & \includegraphics[width=0.12\linewidth]{images/results/full/Paraguay_657443_swir_592_592.png} & \includegraphics[width=0.12\linewidth]{images/results/swir_synth_nir/Paraguay_657443_swir_592_592.png} & \includegraphics[width=0.12\linewidth]{images/results/full_nir/Paraguay_657443_swir_592_592.png}\\ \includegraphics[width=0.12\linewidth]{images/results/images/Paraguay_657443_swir_1124_50.png} & \includegraphics[width=0.12\linewidth]{images/results/gt/Paraguay_657443_swir_1124_50.png} & \includegraphics[width=0.12\linewidth]{images/results/unet_refiner/Paraguay_657443_swir_1124_50.png} & \includegraphics[width=0.12\linewidth]{images/results/swir_synth/Paraguay_657443_swir_1124_50.png} & \includegraphics[width=0.12\linewidth]{images/results/swir_synth_thresh/Paraguay_657443_swir_1124_50.png} & \includegraphics[width=0.12\linewidth]{images/results/full/Paraguay_657443_swir_1124_50.png} & \includegraphics[width=0.12\linewidth]{images/results/swir_synth_nir/Paraguay_657443_swir_1124_50.png} & \includegraphics[width=0.12\linewidth]{images/results/full_nir/Paraguay_657443_swir_1124_50.png}\\ Input Image & Ground Truth & \multicolumn{1}{m{2cm}}{\centering U-Net w/ Refiner} & SWIR-Synth & \multicolumn{1}{m{2cm}}{\centering SWIR-Synth Thresh.} & \multicolumn{1}{m{2cm}}{\centering H2O-Net (RGB)} & \multicolumn{1}{m{2cm}}{\centering SWIR-Synth (RGB+NIR)} & \multicolumn{1}{m{2cm}}{\centering H2O-Net (RGB+NIR)} \end{tabular} \vspace{-0.5em} \caption{Qualitative comparison with SOTA methods on PlanetScope \cite{planet_2020}. H2O-Net results shows that synthesizing SWIR data allows robust segmentation performance in high resolution imagery. It can be seen that adding NIR signals to training and inference improves results in both for segmentation and synthesized SWIR. Blue and white predictions correspond to water and non-water pixels. Best viewed in color and zoomed.} \vspace{-1.8em} \label{qualresults} \end{figure*} \subsection{Training and Evaluation Setup} We train all networks from scratch using Adam optimizer \cite{kingma2014adam} with starting learning rates of 2e-4 for generator, 6e-4 for discriminator, 1e-3 for segmentor, and 1e-2 for refiner. We set $\beta$'s for the Adam optimizer to 0.4 and 0.99 and cosine annealing scheduler \cite{loshchilov2016sgdr} for all networks. Training data used is split 90/5/5 with normalization transformation with zero mean and unit variance applied before input. The generator is first trained for 5 epochs before adding the discriminator, which are trained together for an additional 30 epochs. The segmentation network is then added to the network to train jointly for another 60 epochs. For performance evaluation we report Mean Intersection over Union (mIoU), Pixel Accuracy (PA), and Frequency Weighted Intersection over Union (FW-IoU). The metrics are calculated as follows \begin{equation} \begin{aligned} &\text{PA} = \frac{\sum_{i} n_{ii}}{\sum_{i} t_i} \text{ ,}\\ &\text{mIoU} = \frac{1}{n_{c}} \sum_{i} \frac{n_{ii}}{t_i + \sum_{j} n_{ji} - n_{ii}} \text{ ,}\\ &\text{FW-IoU} = (\sum_{k} t_k)^{-1} \sum_{i} \frac{t_in_{ii}}{t_i + \sum_jn_{ji}-n_{ii}} \text{ ,}\\ \end{aligned} \label{metrics} \end{equation} where $n_{ij}$ is the number of pixels of class $i$ predicted as class $j$, $t_i$ is total number of pixels for class $i$, and $n_c$ is the number of classes. \subsection{Datasets} \label{section:datasets} We train our method and baselines on Sentinel 2 satellite data which is an optical satellite providing RGB, NIR, Narrow NIR, Water vapor, Cirrus, SWIR\textsubscript{1}, and SWIR\textsubscript{2} signals at 10 to 60 meters per pixel. The training dataset is comprised of 3676 images of size 512$\times$512 containing RGB and SWIR\textsubscript{2} data resampled to 10 meters per pixel. For evaluation we use PlanetScope \cite{planet_2020} and Drone Deploy \cite{dronedeploy} datasets. PlanetScope is a high resolution optical satellite providing RGB and NIR signals at 3 meter per pixel. In order to evaluate both our refiner network, and H2O-Net on the same data, we obtain overlapping crops in both Sentinel-2 and PlanetScope to obtain SWIR\textsubscript{2} signals measured by Sentinel-2, resampled and stacked with PlanetScope data. Note that this overlap is not a common occurrence and only provided with 246 evaluation images, which were then manually annotated. Drone Deploy \cite{dronedeploy} is a high altitude fully annotated aerial imagery dataset with 55 orthomosaic images with 10 centimeters per pixel resolution. We generate 775, 512$\times$512 crops that contain at least 10\% water pixels, which are split to 50/20/30 for fine-tuning, validation and testing sets. \subsection{Baselines} \label{section:baselines} This work explores methods relevant to remote sensing and semantic segmentation. Since there is no other work that segments water from satellite imagery without supervision, we compare the closest possible methods. From the remote sensing domain, we use \cite{cooley2017tracking} as a baseline since they use the same evaluation dataset, PlanetScope. It utilizes NDWI thresholding, using NIR signals available in PlanetScope, which are not used in the deep learning baselines. Although the additional information gives NDWI and MNDWI thresholding methods an advantage, we are interested in what can be achieved without this information. Of the semantic segmentation methods, we show U-Net \cite{ronneberger2015u} and DeepLabv3 \cite{chen2017rethinking}. Training those methods follow similar approach to H2O-Net, where we train the networks on low resolution imagery, and predict on high resolution imagery. We include performances of those methods supervised by thresholded MNDWI (coarse labels) and refined labels. All methods were trained from scratch to ensure fair comparison. For methods reporting on DroneDeploy dataset (more details in section \ref{section:ablation}), we fine-tune the models using the given ground truth data before evaluation. Note that all methods were trained from scratch to ensure fair comparison. \begin{table*}[t] \centering \resizebox{0.85\textwidth}{!}{% \begin{tabular}{@{\hspace{2em}}ccccc@{\hspace{2em}}} \toprule Dataset & \multicolumn{4}{c}{PlanetScope \cite{planet_2020}} \\ \midrule Method & Bands Used & Pixel Accuracy (\%) & mIoU (\%) & FW-IoU (\%) \\ \midrule NDWI Thresholding ($\geq -0.1$) \cite{cooley2017tracking,mcfeeters_use_1996} & RGB+NIR& 72.35 & 63.26 & 61.53 \\ SWIR-Synth Thresholding ($\geq 0.35$) & RGB+NIR & 85.47 & 71.93 & 74.49 \\ H2O-Net (Ours) & RGB+NIR & \textbf{87.23} & \textbf{74.52} & \textbf{76.88} \\ \midrule DeepLab v3 \cite{chen2017rethinking} & RGB & 57.03 & 31.46 & 29.61 \\ DeepLab v3 (w/ refiner) & RGB & 59.22 & 33.74 & 39.89 \\ U-Net \cite{ronneberger2015u} & RGB & 64.01 & 42.63 & 49.49 \\ U-Net (w/ refiner) & RGB & 66.81 & 48.18 & 50.98 \\ SWIR-Synth Thresholding ($\geq 0.35$) & RGB & 69.23 & 53.31 & 53.97 \\ H2O-Net (Ours) & RGB & \textbf{76.19} & \textbf{60.92} & \textbf{62.42} \\ \bottomrule \end{tabular}% } \vspace{-0.2 em} \caption{Pixel accuracy (\%), Mean Intersection over Union (\%), and Frequency-Weighted Intersection over Union (\%) accuracy (higher is better) on high resolution satellite imagery PlanetScope dataset. Reported performance is with respect to water segmentation. It is evident from the table that when we train our method with both RGB and NIR signals, we significantly outperform classical methods that also use NIR signals.} \vspace{-1.2em} \label{tab:results} \end{table*} \section{Introduction} Natural disasters cause over 300 billion dollars a year in economic loss, with majority damages done by floods \cite{hallegatte2016unbreakable, guha2015dat}, affecting over 2.3 billion people \cite{wahlstrom2015human}. Recent work in poverty dynamics \cite{dang2014remained,baez2015gone} show that natural disasters disproportionately impact poor communities, and push 26 million people into poverty every year \cite{hallegatte2016unbreakable}, with recovery time of up to a decade \cite{dercon2014live}. Difficulties in flood prediction and low response capabilities also make floods the natural disaster with the highest impact rate \cite{jonkman2005global,pesaresi2017atlas}, accounting for 57\% of all natural disaster victims \cite{guha2012annual}. The use of satellite for active flood risk assessment and real-time flood response have shown to greatly mitigate flood damages and decreased recovery time \cite{alfieri2018global, oddo_value_2019}. Satellite data comes from two main sources: government and commercial satellites. Government optical satellites tend to be equipped with a large variety of sensors (Red, Green, Blue, Coastal aerosol, Red Edge (RE\textsubscript{1}, RE\textsubscript{2}), Near Infra Red (NIR), Narrow NIR, Water vapor, Cirrus, Short Wave Infra Red (SWIR\textsubscript{1}, SWIR\textsubscript{2})) often used in flood detection, but have lower resolution data and have infrequent revisit times over given regions, ranging from 6 to 16 day periods \cite{drusch2012sentinel}. Commercial satellites typically only provide RGB + NIR imagery, but offer higher resolution data with a revisit time of 1 day \cite{murthy2014skysat,anderson2012worldview}. This means that useful data essential for flood detection has low resolution and is only available once every 6 days under optimal conditions, making it unusable for real-time flood forecasting and evacuation alarming. While commercial satellites have high revisit times essential for real time flood detection, they lack instruments to detect them reliably. Note that neither sources provides direct indication of water presence or ground truth data. Our method aims to use the best from both worlds through a domain adaptation approach, transferring knowledge from government satellite data onto commercial satellites data, providing essential instruments for flood segmentation in high resolution data that is available in near real time. To achieve near real time flood segmentation, this work tackles two challenges common in remote sensing and flood detection systems. The first is the lack of pixel-wise ground truth data and annotation difficulties stemming from complex structures and obstructions such as small streams, clouds, and cloud shadows often occurring in satellite imagery, especially during flood events. Current work \cite{bonafilia2020sen1floods11,cooley_tracking_2017} are able to get coarse masks using classic thresholding methods often used in remote sensing \cite{han2005study}; however, those are often noisy and unreliable for supervision. We solve that by sampling high confidence ground truth points to train a lightweight refiner network on-the-fly and predict the remaining pixels to obtain more reliable source of supervision. The second challenge is detection of floods in high resolution and high temporal frequency satellite imagery. As mentioned before, floods often require near real time response which is only possible in low latency commercial satellites, and those are not equipped with instruments reliable enough to detect water presence. We address this issue by learning to synthesize SWIR signals from low resolution data using an attention driven generative adversarial network, which are concatenated to the input image and fed to a segmentation network supervised by the refined mask. The primary contributions of this work are as follows: \begin{itemize} \item We propose a method named H2O-Network that learns SWIR signal synthesis in lower resolution data as a domain adaptation mechanism for accurate flood segmentation in high resolution satellite imagery using self-supervision and label refinement. \item We present a simple run-time refiner that utilizes our adaptive distance map method for coarse-to-fine mask generation. \item We outperform SOTA remote sensing and semantic segmentation methods for flood segmentation. \end{itemize} \section{H2O Network} \subsection{Remote Sensing Overview} Inundation in medium resolution sensors such as Landsat and Sentinel-2 typically rely on water absorption in the SWIR and NIR bands. A commonly used water index, MNDWI (the Modified Normalized Water Index, equation \ref{mndwi_eq}) calculates the normalized difference between the green and SWIR bands to emphasize surface water and reduce noise from soil and built up areas \cite{xu_modification_2006}. The MNDWI is a significant improvement over NDWI, which relies on the normalized difference between green and NIR bands \cite{mcfeeters_use_1996}. The improvement mainly stems from SWIR\textsubscript{2} unperturbed atmospheric window often occurring in longer wavelength signals as they tend to penetrate the atmosphere more easily. However, the SWIR\textsubscript{2} band is notably absent from most commercial sensors. Thresholding, normalized differencing, or more complex combinations of SWIR are used for both Landsat and Sentinel 2 algorithms. In Landsat, SWIR (1560- 1660 nm, Landsat-8 Band 6) and NIR (630-690 nm, Landsat-8 Band 4) are used with with other bands to detect water \cite{yang_rivwidthcloud:_2019, feyisa_automated_2014, chignell_multi-temporal_2015, donchyts_global_2016, devries_automated_2017}. Algorithms to map surface water for Sentinel-2 similarly rely on water’s absorption in SWIR (1539-1681 nm, Band 11) and NIR (768-796 nm, Band 8) \cite{du2016water}. However, both Landsat and Sentinel-2 still suffer from misclassifications of water and cloud shadows, which both have low reflectance values in SWIR and NIR. The MNDWI is calculated using \begin{equation} \begin{aligned} MNDWI = \frac{G - SWIR_{2}}{G + SWIR_{2}} \textit{, } \end{aligned} \label{mndwi_eq} \end{equation} where G represents the green channel. \subsection{Problem Formulation and Overview} This work aims to learn a mapping between the visual domain $X_{LR} \in \mathbf{R}^{H\times W \times 3}$ of low resolution imagery, and Short Wave Infra Red (SWIR\textsubscript{2}) signals $S \in \mathbf{R}^{H \times W \times 1}$ to improve semantic segmentation prediction, $\Tilde{Y}_{HR} \in \mathbf{R}^{H \times W \times C}$, of flood events in high resolution satellite data, $X_{HR} \in \mathbf{R}^{H\times W \times 3}$, in an unsupervised approach. Since the task of direct segmentation in high resolution imagery, $X_{HR} \Rightarrow \Tilde{Y}_{HR}$, without ground truth is challenging, we bridge the gap by learning signals highly correlative with water presence as a domain adaptation step. During segmentation training, we add a self-supervision method using on-the-fly mask refinement of coarse labels, $Y_{C}$, obtained via classical remote sensing methods, and refined using our lightweight refiner network. During training, the network learns $X_{LR} \Rightarrow \Tilde{S}_{LR} \Rightarrow \Tilde{Y}_{LR}$, which is applied on high resolution data, $X_{HR} \Rightarrow \Tilde{S}_{HR} \Rightarrow \Tilde{Y}_{HR}$. \subsection{SWIR-Synth Network} SWIR-Synth is constructed as an image-to-image translation generative adversarial network where we aim to translate images from the visual domain to the longer wavelengths domain. Let $x \in \mathbf{R}^{H\times W \times 3}$ be an image from the source domain with an associated SWIR map $s \in \mathbf{R}^{H \times W \times 1}$. The network $G_{SWIR-Synth}$ seeks to synthesize SWIR\textsubscript{2} signals $\Tilde{s} = G_{SWIR-Synth}(x)$ by minimizing the overall loss function \begin{equation} \begin{aligned} \mathcal{L}_{GAN}(S,\Tilde{S}) = &\lambda_0\mathcal{L}_{\text{G}}(S,\Tilde{S}) + \lambda_1\mathcal{L}_{\text{D}}(S,\Tilde{S}) \\ & + \lambda_2\mathcal{L}_{\text{F}}(S,\Tilde{S})\text{,} \end{aligned} \end{equation} where $\mathcal{L}_{\text{G}}$, $\mathcal{L}_{\text{D}}$, $\mathcal{L}_{\text{F}}$ are the generator, discriminator and feature matching losses, and $\lambda_{\ast}$ represents the weights of losses. As in typical Generative Adversarial Networks (GAN) methods, the generator aims to minimize the objective against an adversarial discriminator that tries to maximize it. \vspace{-1em} \paragraph{Generator Loss} Generator $G$ learns output $\Tilde{s}$ by minimizing two objective functions: pixel-wise squared error between $s \in S$ and $\Tilde{s} \in \Tilde{S}$, and patch-wise squared error of discriminator output of the generated data. The first objective penalizes inaccurate RGB to SWIR\textsubscript{2} mapping, with the second objective penalize for patches deemed ``fake" by the discriminator. More formally, \begin{equation} \begin{aligned} \mathcal{L}_{G}(S,\Tilde{S}) = \mathbf{E}(||s - \Tilde{s}||_{2}) + \mathbf{E}(||1-D(\Tilde{s})||_{2}) \end{aligned} \end{equation} \paragraph{Adversarial Loss} This loss aims to align the features distributions of the two domains by predicting the target labels of the synthesized data. SWIR-Synth is rewarded when it ``fools" the discriminator, resulting in better synthesized output. Here, we utilize a Markovian discriminator (PatchGAN) thoroughly explored in \cite{li2016precomputed}, where the discriminator aims to classify $N\times N$ sub-patches of the generated image, with each patch classified as ``real" or ``fake." The final optimization objective of the discriminator is \begin{equation} \begin{aligned} \mathcal{L}_{D}(S,\Tilde{S}) = \mathbf{E}(||D(\Tilde{s})||_{2}) + \mathbf{E}(||1-D(s)||_{2})\textit{.} \end{aligned} \end{equation} \vspace{-2.2em} \paragraph{Feature Matching Loss} Difficult to learn latent patterns often occurring in satellite imagery cause unstable training of the model, which we solve using feature matching loss introduced in \cite{salimans2016improved}. We extract features from discriminator's penultimate layer for both real and synthesized samples, and minimize the squared distance between them. The objective function is \begin{equation} \begin{aligned} \mathcal{L}_{F}(S,\Tilde{S}) = \mathbf{E}(||D^{[n-1]}(s) - D^{[n-1]}(\Tilde{s})||_{2}) \textit{,} \end{aligned} \end{equation} where $n$ represents the number of layers in discriminator $D$, and $D^{[n-1]}(\cdot)$ represents the output of the discriminator's $n-1$ layer. \begin{table*}[t!] \centering \resizebox{\textwidth}{!}{% \begin{tabular}{ccccc} \toprule Method & Additional Train Time (sec/iter) & Pixel Accuracy (\%) & mIoU (\%) & FW-IoU (\%) \\ \midrule MNDWI Thresholding ($\leq 0.35$) & \textbf{0} & 84.86 & 76.23 & 79.91 \\ Refiner (Ours, without Adaptive Distance Maps) & 0.21 & 85.34 & 81.41 & 80.12 \\ Refiner (Ours, with Adaptive Distance Maps) & 0.36 & \textbf{89.46} & \textbf{84.41} & \textbf{83.04} \\ \bottomrule\\ \end{tabular} } \vspace{-1.5em} \caption{Mean Intersection over Union (\%), pixel accuracy (\%), and frequency weighted intersection over union (\%) metrics (higher is better) for refiner network evaluation on manually annotated PlanetScope.} \label{table:refinermetrics} \end{table*} \begin{figure}[t!] \centering \includegraphics[width=0.5\textwidth]{model/refinerv3_edited_3.png} \caption{Overview of self-supervision architecture. High confidence points are first sampled from MNDWI and are used to obtain adaptive distance map and as ground truth to the refiner network. Adaptive distance map is concatenated to MNDWI as a 2 channel input to the refiner network. Blue and red dots represent points sampled from water and non-water pixels respectively. Blue and white predicted pixels represent water and non-water pixels. Best viewed in color.} \label{fig:refiner} \vspace{-1.2em} \end{figure} \begin{figure*}[t!] \setlength\tabcolsep{2pt} \def1{1} \centering \begin{tabular}{cccccc} \includegraphics[width=0.14\linewidth]{images/results/images/Mekong_16233_swir_50_592.png}& \includegraphics[width=0.14\linewidth]{images/results/refiner/Mekong_16233_swir_50_592_mndwi.png}& \includegraphics[width=0.14\linewidth]{images/results/refiner/Mekong_16233_swir_50_592_gt.png} & \includegraphics[width=0.14\linewidth]{images/results/refiner/Mekong_16233_swir_50_592_thresh.png} & \includegraphics[width=0.14\linewidth]{images/results/refiner/Mekong_16233_swir_50_592_dm.png} & \includegraphics[width=0.14\linewidth]{images/results/refiner/Mekong_16233_swir_50_592_refined.png} \\ \includegraphics[width=0.14\linewidth]{images/results/images/Mekong_16233_swir_592_50.png}& \includegraphics[width=0.14\linewidth]{images/results/refiner/Mekong_16233_swir_592_50_mndwi.png} & \includegraphics[width=0.14\linewidth]{images/results/refiner/Mekong_16233_swir_592_50_gt.png} & \includegraphics[width=0.14\linewidth]{images/results/refiner/Mekong_16233_swir_592_50_thresh.png} & \includegraphics[width=0.14\linewidth]{images/results/refiner/Mekong_16233_swir_592_50_dm.png} & \includegraphics[width=0.14\linewidth]{images/results/refiner/Mekong_16233_swir_592_50_refined.png} \\ Image & MNDWI & Ground Truth & MNDWI Threshold & Distance Map & Refined Mask \end{tabular} \vspace{-0.25cm} \caption{Qualitative results of our refiner on PlanetScope \cite{planet_2020}. Our refiner provides better ground truth for the segmentation network without hand-labeled data. Our refiner samples high confidence points from MNDWI used to generate adaptive distance maps, which are then concatenated to MNDWI to make 2 channel input to the refiner. Blue and white predicted pixels represent water and non-water pixels. Best viewed in color and zoomed.} \vspace{-0.5cm} \label{refiner_qualresults} \end{figure*} \subsection{Refiner/Self-Supervision} This work introduces a run time refiner able to generalize over a batch input for the purpose of improving coarse masks obtained via MNDWI thresholding. Let sample $(x \in \mathbf{R}^{H\times W \times 3} ,m \in \mathbf{R}^{H \times W \times 1})$ be an image-MNDWI pair. We define high confidence water and non-water pixels using high and low thresholds, $\phi_H$ and $\phi_L$, on $m$ to obtain a set of locations, $(p_{wx}, p_{wy}) \in P_{w}$ and $(p_{\bar{w}x}, p_{\bar{w}y}) \in P_{\bar{w}} $, corresponding to water (positive) and non-water (negative) points. Note that $|P_w| + |P_{\bar{w}}| \leq |m|$, where $|\cdot|$ is the cardinality of that set. A distance map function is then used to transform $P_w$ and $P_{\bar{w}}$ to distance maps $D_{w} \in \mathbf{R}^{H \times W \times 1} $, and $D_{\bar{w}} \in \mathbf{R}^{H \times W \times 1}$, respectively. Distance maps are calculated by taking the minimum Euclidean distance between a positive point and a set of negative points. For example, to obtain distance map $D_{w}$, we calculate pixel value $D_{w}^{i,j}$ at location $(i,j)$ with the set of points $P_w$ using $D(x,y|P_w) = min_{\forall p_{wx},p_{wy}}\sqrt{(x-p_{wx})^2 + (y-p_{wy})^2}$, where $(x,y)$ is any point in the image. This is repeated until distance values are obtained for all pixels in both $D_{w}$ and $D_{\bar{w}}$. Traditionally, $D_{w}$ and $D_{\bar{w}}$ would be concatenated to the input image, but this proves to degrade results when the number of sampled points is large. Instead, we dynamically select one distance map that represents the class with highest points density. Class-wise points density of objects is typically comparable in common datasets such as COCO, ADE20K and PASCAL \cite{zhou2017scene, lin2014microsoft, Everingham10}, where objects have similar size and scale. In flood events datasets, classes rarely occur in similar magnitudes, often resulting in sparsely sampled points for one class, and densely sampled points for another class. We define the adaptive distance map, $D_{a}$, as the distance map of the densely sampled points, normalized such that higher values represent the positive class (water), and lower values represent the negative class (no-water). We then construct the network input, $I$, by concatenating MNDWI, $m$, and the adaptive distance map, $D_a$, and use it to train our refiner network, a lightweight convolution refining network, supervised by $P_w$ and $P_{\bar{w}}$, with the rest of the pixels ignored. The network minimizes \begin{equation} \mathcal{L}_{R}(P_w,P_{\bar{w}},\Tilde{y})=-\sum_{p_w} log(\Tilde{y}) - \sum_{p_{\bar{w}}} (1-log(\Tilde{y})) \text{.} \end{equation} Note that the loss function ignores pixels not in the set $P_w \cup P_{\bar{w}}$. After the network is trained for $k$ iterations, it predicts on the same image to obtain mask values for the rest, previously ignored pixels, to produce a pseudo-mask ground truth $\Tilde{Y}_{R}$ fed to the segmentation network. The intuition behind this method is to predict the labels of the entire image given a small set of high confidence labeled pixels. \subsection{Segmentation Network} An encoder-decoder architecture takes a concatenation of RGB image $X$ and synthesized SWIR $\Tilde{S}$ as a 4 channel input, and aims to predict pixel-wise labels $\Tilde{Y}$ that minimize the cross entropy loss between $\Tilde{Y}$ and $Y_{R}$. We define the segmentation loss by \begin{equation} \mathcal{L}_{S}(Y_R,\Tilde{Y})=-\sum log(\Tilde{Y}) - \sum (1-log(\Tilde{Y})) \text{.} \end{equation} In practice, this network has two roles: it fine-tunes SWIR-Synth by penalizing low synthesized SWIR values (water presence) when water labels are not present, and it learns to correlate RGB and SWIR pairs input to water pixels. \section{Related Work} \paragraph{Computer Vision and Remote Sensing} Computer vision and remote sensing commonly align in land cover classification \cite{belgiu_random_2016, van_tricht_synergistic_2018-1}, flood detection \cite{shen_near-real-time_2019-1}, weather prediction \cite{klein2015dynamic}, and precision agriculture \cite{akiva2020finding} using data from government satellites Sentinel-2 and Landsat-8 \cite{sentinelhub} and commercial satellites PlanetScope and WorldView \cite{planet_2020}. Early and current work use thresholded Normalized Water Index (NDWI) and Modified Normalized Water Index (MNDWI) \cite{cooley_tracking_2017,xu_modification_2006} for permanent water segmentation, providing quick and somewhat reliable ground truth data for random forests and support vector machines methods used for land cover classifications \cite{belgiu_random_2016, van_tricht_synergistic_2018-1} and flood detection \cite{shen_near-real-time_2019-1}. Recently published remote sensing datasets \cite{schmitt_sen12ms_2019, bonafilia_sen1floods11_2020, alemohammad2019radiant} have encouraged development of deep learning methods which showed improved capabilities in identifying clouds and cloud shadows \cite{zantedeschi_cumulo:_2019,wieland_multi-sensor_2019}, water \cite{isikdogan_seeing_2019, isikdogan_surface_2017}, inundation \cite{bonafilia2020sen1floods11}, and crop conditions \cite{alcantara2012mapping,akiva2020finding} more accurately than threshold based algorithms when labeled data is available. \vspace{-1.5em} \paragraph{Semantic Segmentation} Semantic segmentation is the task of assigning class labels to specific pixels in input images. This has been a fundamental computer vision task, with fully connected networks (FCN) \cite{long2015fully} serving as a foundation for semantic segmentation methods in recent years. The encoder-decoder architecture learns optimal interpolation of dense features to recover original resolution and capture scene details. U-Net \cite{ronneberger2015u} is one notable recent method which uses skip connections for better feature propagation similar to \cite{he2016deep}. PSP-Net, DeepLab, and FPN \cite{lin2017feature,chen2017rethinking,zhao2017pyramid} use spatial pyramid pooling to obtain multi scale contextual features useful for segmentation. The importance of contextual features have been further illustrated in \cite{yu2015multi, yu2017dilated}, which expand receptive fields using dilated convolutions, capturing more contextual information without increasing the number of parameters. Our approach uses U-Net for the segmentation network, but can practically integrate with any other segmentation methods. Interactive segmentation \cite{grady2006random,rother2004grabcut,gulshan2010geodesic,hariharan2011semantic,bai2014error,li2018interactive,xu2016deep,maninis2018deep,jang2019interactive} considers a set of inputs, generally points or scribbles, provided by a user as guidance for semantic segmentation. Classical methods \cite{grady2006random,gulshan2010geodesic,hariharan2011semantic,bai2014error,rother2004grabcut} set this task as an optimization problem, using heuristics and greedy approaches without considering global and local semantic information, while deep learning methods \cite{xu2016deep,liew2017regional,li2018interactive,maninis2018deep, jang2019interactive} utilize global semantic information with respect to the user input. Early work \cite{xu2016deep} stacked input images with distance maps generated from user inputs as network input, essentially generating dense features from sparse input, greatly improving segmentation performance compared to classical methods. Subsequent works commonly follow this approach with added modules such as patch-wise prediction for refinement \cite{liew2017regional}, multi-mask prediction for every object \cite{li2018interactive}, and a seed generator for automatic user input \cite{song2018seednet}. While our work employs elements often seen in interactive segmentation, it removes the interactive part by automatically sampling high confidence points as user input. While this removes the need for user input, it creates potential for class-wise imbalance sampling in cases when an image is fully or almost fully covered with one class. We address this issue by using our adaptive distance map generation that considers the class-wise samples density, allowing more stable predictions. \vspace{-1.5em} \paragraph{Domain Adaptation} Domain adaptation seeks to transfer knowledge from the labeled source domain to an unlabeled target domain. Traditional domain adaption work has focused on classification and detection tasks \cite{saito2018maximum,tzeng2014deep,ganin2016domain,long2015learning,long2017deep,tzeng2017adversarial}, with more recent work showing advances in semantic segmentation \cite{chen2019domain, pan2020unsupervised,park2019preserving,vu2019advent}. Generally, domain adaptation for semantic segmentation is more complex than for classification and detection since its output often involves highly structured and complex semantic information. Most domain adaptation models are comprised of two networks: one for feature adaptation learning, and another for task learning. ADVENT \cite{vu2019advent} improves semantic segmentation through entropy map adaptation to push decision boundaries toward low density regions in target domain. Wu et al. \cite{wu2018dcan} learns to reduce domain shift at both pixel and feature levels using channel-wise feature alignment in image generator and segmentation networks. A similar approach is used in \cite{hoffman2018cycada}, with alignments occurring in both image space and latent space, which are learnt through cycle consistency loss \cite{zhu2017unpaired}. Here, our method learns to generate SWIR signals from our source domain, low resolution satellite data, and transfer that knowledge to our target domain, high resolution satellite data, to improve semantic segmentation. According to our knowledge, we are the first to achieve this task using only RGB inputs, and first to utilize this method as a domain adaptation step. \vspace{-1.5em} \paragraph{Generative Models} Generative models in the context of domain adaptation has gained traction in recent years. Initial approaches use StyleGAN and Pix2Pix \cite{Isola_2017_CVPR,karras2019style} methods as a data augmentation step, learning domain-invariant features by modifying textures and appearances \cite{hoffman2018cycada,wu2018dcan}. More recent works use image-to-image translation techniques to transfer features available in one domain to another, providing additional data applicable to target domain data \cite{wu2018dcan,chang2019all,ying2019x2ct,pan2020unsupervised}. StandardGAN \cite{tasar2020standardgan} builds on StyleGAN to standardize inputs by enforcing similar styles in satellite data to reduce domain gap. DUNIT \cite{bhattacharjee2020dunit} combines style and content from source and target images by first generating style features from the style image, and concatenates them to features from content domain as input to a third generator. The closest method to our work is S2A \cite{rout2020s2a}, which synthesizes SWIR signals using Wasserstein GAN \cite{arjovsky2017wasserstein} with enlarged receptive fields using high dilation and spatial attention modules. A major difference between our work and S2A is that S2A uses NIR signals during synthesis training and inference. NIR signals greatly correlate with SWIR\textsubscript{2} signals ($r^2(NIR,SWIR_2) \approx 0.82$) \cite{du2016water}, practically diminishing the role of visual queues in the data. On the contrary, our approach only uses RGB input for SWIR synthesis, making the task more complex due to a large domain gap, but also more generalizable to other domains that use aerial or satellite imagery and don't contain NIR data. Additionally, \cite{rout2020s2a} aims to solely synthesize SWIR\textsubscript{2} signals without inferring on the data, mainly framed as an image-to-image translation algorithm. The paper provides suggestions to applications such as wetland delineation, but incorrectly evaluates its performance for the task. Their results compare ground truth and predicted wetlands obtained by thresholding ground truth and predicted MNDWI, which is composed of synthesized SWIR and green bands. Since the green band is constant in both ground truth and prediction, this metric is redundant and reduces to simply the difference between ground truth and predicted SWIR. Since generating ground truth via thresholding is often noisy, pixel-wise labels become susceptible to common false positives, making it unreliable data to evaluate against. In this work, we define the task of synthesizing SWIR signals as a domain adaption step for flood segmentation in high resolution satellite imagery. We manually annotate a test dataset guided by SWIR signals to empirically evaluate our results. To our knowledge, this work is a first attempt at learning SWIR signals from visual cues and transferring it to high resolution domain for semantic segmentation. \begin{figure*}[t!] \centering \includegraphics[width=0.9\textwidth]{model/satflow_horizonal6_worded.png} \caption{H2O-Net training and inference pipelines. H2O-Net uses Sentinel-2 (low resolution) satellite data to learn synthetic SWIR\textsubscript{2} signals and flood segmentation self-supervised by refined ground truth. It is then evaluated on PlanetScope (high resolution) data. The training pipeline feeds RGB through SWIR-Synth, an adversarial adaptation network, which is then input to the segmentation network, which is self-supervised by refined masks.} \vspace{-1.5em} \label{fig:my_label} \end{figure*} \section{Results} Figure \ref{qualresults} shows the qualitative results for the task of semantic segmentation. Our method, H2O-Net, shows the most consistent results out of the compared baselines. Table \ref{tab:results} shows the quantitative performance of our method compared to SOTA methods in semantic segmentation and remote sensing. Figure \ref{qualresults} shows that H2O-Net is able to finely segment small streams and muddy flood waters compared to isolatedly trained segmentation network. It can be seen that narrowing the domain gap through synthesized SWIR\textsubscript{2} can significantly increase performance. For the refiner, figure \ref{fig:refiner} and table \ref{table:refinermetrics} show superior performance both qualitatively and quantitatively for obtaining self-supervised ground truth data. It is evident from the results that training on coarse labels alone is not enough to provide reliable segmentation prediction in high resolution imagery, and adding the refined masks for supervision improves performance overall. While thresholding methods used in remote sensing performed relatively well compared to deep learning methods, it is important to emphasize that explicit NIR and SWIR\textsubscript{2} reflectance data of the scene was available during evaluation, which is not available for deep learning methods. For that, we also include metrics of our method trained and evaluated with NIR signals. It can be seen that such signals provides significant boost in performance both qualitatively and quantitatively. Since DroneDeploy \cite{dronedeploy} does not provide such data, those methods are also not reported for that dataset. Additional qualitative results and implementation details for H2O-Net, SWIR-Synth, refiner, and baseline networks are available in the supplementary. \subsection{Domain Transferability Study} \label{section:ablation} We explore the effect of SWIR-Synth and H2O-Net on aerial imagery. The domain gap between low resolution satellite imagery and high resolution aerial imagery (10 meters/pixel compared to 10 centimeters/pixel) is even larger than the domain gap between low and high resolution satellite imagery (10 meters/pixel compared to 3 meters/pixel), making it a more challenging task. Additionally, this dataset does not have flood related imagery, as it was collected over parks and residential areas featuring pools, fountains, and lakes, which inherently have different structures than flood events imagery. Another challenge is in data representation domain gap, as satellite data measures reflectance values for RGB and SWIR\textsubscript{2} signals, while Drone Deploy provides digital values (0-255). Figure 2 in supplementary material and table \ref{tab:dd_results} show the qualitative and quantitative results on DroneDeploy \cite{dronedeploy} dataset after fine-tuning the segmentation network. The results show that despite such domain gap, our method still improves accuracy for water segmentation. In supplementary material we show challenging examples occurring in urban areas. Asphalt and roof-tops often have similar SWIR\textsubscript{2} responses to water, which is inherently also learned to be generated by the SWIR-Synth output. \begin{table}[t] \centering \resizebox{\columnwidth}{!}{% \begin{tabular}{@{}cccc@{}} \toprule Dataset & \multicolumn{3}{c}{Drone Deploy \cite{dronedeploy}} \\ \midrule Method $\backslash$ Metric & PA (\%) & mIoU (\%) & FW-IoU (\%) \\ \midrule DeepLab v3 \cite{chen2017rethinking} & 88.14 & 56.62 & 77.92 \\ U-Net \cite{ronneberger2015u} & 91.11 & 68.99 & 83.64 \\ SWIR-Synth Thresholding ($\geq 0.35$) & 59.31 & 39.24 & 48.37 \\ H2O-Net (Ours) & \textbf{92.71} & \textbf{75.25} & \textbf{86.65} \\ \bottomrule \end{tabular}% } \vspace{-0.5em} \caption{Domain Transferability Study. Pixel accuracy (\%), Mean Intersection over Union (\%), and Frequency-Weighted Intersection over Union (\%) accuracy (higher is better) on DroneDeploy, a high resolution aerial imagery dataset. Reported performance is with respect to water segmentation.} \vspace{-1.8em} \label{tab:dd_results} \end{table} \subsection{Conclusion} This work presents a novel approach to address difficulties in flood response time and support, allowing detection of floods in high resolution, high temporal frequency satellites without explicit annotation efforts. We propose the H2O-Network which employs SWIR\textsubscript{2} synthesis as a domain adaptation step for semantic segmentation using a self-supervised approach. We hope that this work will provide additional route to save lives and property in communities susceptible to such natural disasters. Our approach also shows that detecting and segmenting objects that have reflectance properties may benefit from such domain adaptation step seeking to gain additional features in the target domain. Important to note that ideally, such application in practice would make use of NIR signals which is often available in commercial satellites, but we choose to omit such data to demonstrate our approach on datasets with a larger domain gap. \newcolumntype{Y}{>{\centering\arraybackslash}X} \section{Implementation Details} \subsection{SWIR-Synth Network Architecture} SWIR-SynthNet is structured as an image-to-image translation network. The generator is constructed of 3 encoding blocks, and 3 decoding blocks with skip connections. Each encoding block is comprised of a spectrally normalized convolution layer with a 3$\times$3 kernel and 1 padding, batch normalization layer, leaky rectified linear unit (ReLU) with slope of 0.2 and a dropout layer. Each block output is then down-sampled by a factor of 2 using a strided convolution layer. Decoding blocks first upsample input using a spectrally normalized transposed convolution layer with a 4$\times$4 kernel size and a stride of 2, followed by a spectrally normalized convolution layer with a 3$\times$3 kernel and 1 padding, batch normalization layer, leaky ReLU with slope of 0.2 and a dropout layer. Decoding blocks take a concatenation of the previous decoding block and output of the corresponding encoder block. The discriminator has 5 blocks each with a spectrally normalized convolution layer with 4$\times$4 kernel size, and stride of 2, followed by a batch normalization, and a ReLU activation function. A self-attention module similar to \cite{zhang2019self} was added after the second and forth blocks. The last layer of the last block outputs the features tensor for the feature loss, which is also used as an input to a Sigmoid activation layer for the adversarial loss. \subsection{Segmentation Architecture} The segmentation network uses an encoder-decoder architecture similar to U-Net \cite{ronneberger2015u}, with 5 encoding blocks and 5 decoding blocks with skip connections. Encoding blocks comprise of two spectrally normalized convolution layers, batch normalization layer, and LeakyReLU layer. Each block is followed by a strided convolution layer acting as a pooling layer. The decoder also has 5 blocks, each comprised of transposed convolution layer for upsampling, two spectrally normalized convolution layers, batch normalization layer, and a Leaky ReLU layer. Skip connections are used for corresponding encoding and decoding blocks. This architecture was also used for the U-Net baseline method to ensure consistency and fairness in evaluation. \subsection{Refiner Architecture} has one encoder block and one decoder block. The encoder block consists of 2 convolution layers each followed by a normalization layer, batch normalization layer after first convolution and instance normalization layer after second convolution, and a Leaky ReLU layer. The decoder block first upsamples features using bilinear interpolation, followed by 2 convolution layers, normalization layers, and Leaky ReLU layers. For high confidence points sampling, we use $\phi_H$ of 0.5, and $\phi_L$ of -0.2. \section{Additional Qualitative Results} Here we provide additional qualitative result to illustrate performance in each stage of H2O-Net. Figure \ref{fig:low_res_swir_synth} illustrates features SWIR-Synth learns in low resolution data, showing the input image, ground truth SWIR\textsubscript{2}, synthesized SWIR\textsubscript{2}, thresholded mask obtained from ground truth SWIR\textsubscript{2}, and predicted thresholded mask obtained from synthesized SWIR\textsubscript{2}. Figure \ref{fig:high_res_swir_synth} demonstrate SWIR-Synth qualitative performance on high resolution data. Figure \ref{fig:low_res_refiner} show refiner performance on low resolution data. Figure \ref{supp:qual_results} shows additional results on PlanetScope \cite{planet_2020}, and figure \ref{supp:dd_qual} shows qualitative results on DroneDeploy \cite{dronedeploy}.
{'timestamp': '2020-10-13T02:24:29', 'yymm': '2010', 'arxiv_id': '2010.05309', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05309'}
arxiv
\section{Agents, Rationality, and Inquiry} The study and modeling of defeasible reasoning unites epistemologists with those working in artificial intelligence (AI). This convergence is due, in part, to a joint interest in epistemic rationality. Traditionally, epistemically rational behavior is conceived in terms of conformity with rules, standards, or ideals specifying the conditions under which an agent is permitted (or obliged) to form or withhold beliefs. Since these norms are commonly understood as admitting exceptions or conflicts, the concept of defeasibility has occupied an important role in their study. Epistemic rationality is thus often identified with the defeasible inferences an agent is (epistemically) permitted to draw. Naturally, this is especially relevant to work in AI, where the goal is, \textit{inter alia}, the construction of artificial agents capable of operating with a range of information sources in an epistemically rational manner. It would be a mistake, however, to think that epistemic rationality only governs the formation or withholding of beliefs. In recent years, epistemologists and philosophers of science have come to recognize an array of non-doxastic or quasi-doxastic states and processes that are subject to epistemic norms \citep{Fleisher2018,Friedman2013a,Lacey2015,Whitcomb2017,Palmira2019}. These include, most notably, the attitudes associated with our core epistemic practice of \textit{inquiry}. An inquiring agent aims to improve its epistemic standing with respect to some subject-matter---i.e. to obtain, in some sense, the correct answer to a question---and undertakes certain actions in order to do so, e.g. gathering evidence. But since it is possible to perform those same actions so as to mislead others into thinking that one is inquiring, these actions cannot be sufficient. To qualify as genuinely inquiring into an issue, an agent must have an \textit{interrogative attitude} that is oriented toward settling the question at hand and that is sensitive to information bearing on it \citep{Friedman2013a}. In contrast with propositional attitudes like belief, the contents of these attitudes are questions. Interrogative attitudes include \textit{wondering}, \textit{being curious}, \textit{investigating}, \textit{contemplating}, \textit{deliberating}, and \textit{suspending judgment} about $ Q $. In what follows, we use the verb-phrase ``inquiring into $ Q $'' as a place-holder for any one of these attitudes. One way to think about the epistemic norms that govern inquiry, then, is to consider when it is epistemically rational for an agent to adopt an interrogative attitude toward a question, i.e. to inquire into $ Q $. Following \cite{Friedman2019a}, we'll refer to the norms that govern these attitudes and to the rationality they embody as \textit{zetetic} from the ancient Greek word for inquiry, \textit{z\^{e}t\^{e}sis}. Unfortunately, this new line of research has yet to make full contact with the field of AI, despite the latter's obvious interest in developing systems that perform information-seeking operations. Intelligent agents are able, e.g., to search for relevant information at appropriate intervals and to `raise' or `drop' questions in response to changes in information states. Behaviors such as these may serve as an intermediate step toward an agent's goal of maximizing some external reward. But inquisitive behavior and the states underlying it can play other roles as well. For instance, in environments where extrinsic rewards are scarce, interrogative attitudes such as \textit{curiosity} can serve as intrinsic reward signals, encouraging the agent to explore its environment, develop successful strategies, and learn useful skills \citep{Burda2018,Graziano2011,Pathak2017,Pape2012}. Among the areas where such artificially curious agents might have a significant impact is in the automation of scientific discovery \citep{Savage2012}. Autonomous agents capable of scientific activity will need to be able to determine which lines of inquiry are worth pursuing. So, automating these decisions via artificial curiosity is likely to be central to the project of automating scientific activity in general. Extending the study of epistemic rationality to the behavior and attitudes associated with inquiry is therefore important for epistemologists and AI researchers alike. Typically, defeasible inferences are understood along the lines of the ``If-Then-Unless'' pattern, where conclusions (the `Then' part) are drawn `usually', `normally', or `by default' when certain information is present (the `If' part) but are withheld, relinquished, or bracketed when information defeating that inference is detected (the `Unless' part).\fnmark{def} An agent who draws such inferences in the presence of defeaters exhibits, \textit{ceteris paribus}, a sort of incoherence, such as that associated with having inconsistent beliefs or adopting incompatible doxastic attitudes toward the same content. If epistemic rationality is generally associated with defeasible inferences, then we would expect zetetic rationality to be similarly defeasible. But what collateral states would make it irrational or incoherent for an agent to adopt an interrogative attitude like \textit{wondering whether} $ p $? \fntext{def}{See \cite{Bloeser2013} for a nice discussion of the extensive literature on defeasibility across logic, epistemology, and law.} Linguistic practice provides a clue. A speaker who asks a question often flouts conversational maxims when it is common knowledge that it knows or fully believes the answer.\fnmark{test} Of course, it is often quite useful and even necessary to flout such maxims in order to achieve certain communicative goals, e.g. to feign ignorance. But the dialectical proscription on asking information-seeking questions for which one has the answer may reveal a distinctly epistemic norm. The suggestion that has recently emerged is that it is epistemically irrational, at least \textit{prima facie}, to adopt interrogative attitudes toward questions whose answer is (already) believed or known. Stated more carefully, an agent's epistemic license or entitlement to inquire into a question is defeated when it knows or is licensed to believe its answer \citep{Friedman2017,Friedman2017a,Whitcomb2017}. To give zetetic rationality its due, this \textit{erotetic defeat} needs to be investigated alongside the kinds of defeat that are traditionally represented in nonomonotonic logics. \fntext{test}{\hspace{1mm}One obvious exception is when a speaker asks a so-called ``exam question'' and intends to test the addressee's knowledge.} The goal of this paper is to lay the ground for a formal study of zetetic rationality that is of recognizable import to epistemologists---at least to those who work in the formal and logical areas of that field---as well as to AI researchers. To do so, we examine defeasible inferences involving the contents of interrogative attitudes, i.e. questions, in addition to the contents of doxastic attitudes, i.e. propositions. The former have traditionally been the subject matter of erotetic logic. What we propose, then, is a defeasible erotetic logic with the computational properties needed to inform the design of zetetically intelligent systems. We draw on work in \textsc{Inferential Erotetic Logic} (IEL), as it provides a familiar truth-conditional semantics for erotetic inferences and identifies some of them as nonmonotonic \citep{Wisniewski1995,Wisniewski2013}. While the relations between questions and answers have received various logical treatments \citep{Belnap1976,Hamblin1958,Hintikka2007,Ciardelli2018}, IEL is rather unique in its focus on inferences among questions themselves. IEL's approach is to start with a standard propositional language and to enrich it syntactically with question-forming vocabulary. Following the \textit{set-of-answers} methodology, IEL represents questions as sets of their possible direct answers, with the latter being construed as syntactically distinct, well-formed formulas (wffs) of the propositional language. In virtue of this capacious construal of questions, IEL can readily accommodate the popular intensional semantics for natural language interrogatives that treats questions (i.e. the content of interrogative clauses) as partitions of logical space \citep{Groenendijk1996}. In recent years, the logical study of questions has benefited from the rise of inquisitive semantics, a program which, unlike IEL, does not assume a syntactic distinction between declaratives and interrogatives but rather provides a unified semantic account according to which informative content may be distinguished from inquisitive content. Fortunately, many of the relations IEL studies have known correlates in inquisitive semantics \citep{Winiewski2015}. What we want is a calculus that facilitates (re)construction of reasoning in which interrogative attitudes are adopted and abandoned. IEL is a good resource for this, given that some of its relations are nonmonotonic. Unfortunately, there has been very little proof theoretic work done with erotetic logics, let alone IEl. The few calculi that exist for species of IEL's relations either do not encode defeasibility \citep{Wisniewski2016,Wisniewski2004,Leszczyska-Jasion2008,Leszczynska-Jasion2013}, or do not capture the type of defeasible erotetic inferences that take questions as both premises and conclusion \citep{Meheus1999,Meheus2001,Millson2019}. In fact, the calculus presented in \cite{Millson2019}, $ \mathsf{LK^?} $, cannot capture these inferences at all. The limitation arises from the fact that sequents in $ \mathsf{LK^?} $ contain an auxiliary syntactic parameter---so-called ``Background Sets''---that preserve a `trace' of active formulas that are otherwise eliminated as the proof proceeds downward. Although they greatly aid the proof of a cut-elimination theorem, these background sets prevent the representation of erotetic defeat in cases of question-to-question inferences and produce a significant syntactic `bloat,' since the size of background sets increases dramatically through the course of a proof.\fnmark{lemma3} The system presented here does away with the background-set device and offers a far more streamlined and elegant calculus---one that is shown to be sound and complete without the use of a cut rule. \fntext{lemma3}{In \cite{Millson2019}, the background-set device facilitates the proof of the property established in Lemma \ref{lem:Derivable_undefeated_provable_SCs} below.} Filling this proof-theroetic lacuna is a central aim of the present work. We offer a decidable sequent calculus that is sound and complete for IEL's defeasible erotetic-inferential relations. The calculus includes introduction and elimination rules for interrogative-forming expressions that correspond, intuitively, to the adoption of interrogative attitudes. We hope, then, to have an (informally) well-founded and (formally) well-behaved calculus for studying zetetically rational agents. The system presented here might aid the engineering and design of such agents. For instance, if the logic is decidable for proofs of defeasible inferences between questions, then an automated theorem prover (ATP) could help agents determine which auxiliary or subordinate questions they are epistemically permitted to inquire into given their initial question(s) and knowledge base. Since the inferences are erotetically defeasible, the ATP could also be used to tell the agent when it has obtained an answer to one of its questions and thus is no longer licensed to inquire. Such an ATP could nicely complement the reinforcement learning of artificially curious agents. The paper proceeds by introducing IEL's semantic definitions for two types of erotetic inference (\S \ref{sec:IEL}). Next, we define a sequent calculus for the language of classical propositional logic (CPL) that tracks the defeat of sequents on the basis of a finite set of defeaters assigned to each atom by the axioms (\S \ref{subsec:SCS?}). We then extend the calculus with rules for erotetic formulas (\S \ref{subsec:SCp?rules}) and show that the calculus is decidable and is sound and complete for IEL's defeasible erotetic inference-relations (\S \ref{sec:Results}). We finish with a worked example (\S \ref{sec:ex}) and some suggestions for future development (\S \ref{sec:concl}). \section{Erotetic Inferences}\label{sec:IEL} Inferential Erotetic Logic (IEL) studies the relations underwriting two patterns of reasoning in which questions play a crucial role. The first occurs when information `opens up' or makes salient a set of possibilities, each of which provides a possible answer to a particular question. In these situations, we might say that our state of information, set of beliefs, or theoretical commitments gives rise to or \textit{evokes} a question. For example, knowing that someone broke the vase may give rise to the question of who, among a certain set of individuals, broke it. It's natural to think of our reasoning here as one of inferring questions from statements. But we also infer questions from other questions. We may find that progress can be made in answering one question by answering another. If we are trying to figure out who broke the vase and we have evidence that whoever broke it is wearing sandals, we can narrow down the set of potential culprits by asking who of them is wearing sandals. Here, our initial question, together with our evidence regarding the culprit's footwear, form the premises from which we infer the latter question. The first of these patterns is called question or erotetic \textit{evocation}, the second, \textit{erotetic implication} (hereafter: e-implication). Evocation and e-implication specify conditions under which an agent is entitled to ask or inquire into a question, in the sense of adopting an interrogative attitude. By contrast, erotetic defeat describes a situation in which an agent is not licensed or is forbidden to inquire into a question. So evocation and e-implication are undermined when an agent has an answer to the relevant questions. In drawing one of these types of inference, agents reserve the right, so to speak, to retract or withhold their entitlement to inquire in the light of further evidence, i.e. if they obtain the answers to their questions. Evocation, for instance, fails to obtain when the declarative premises entail an answer to the evoked question. Similarly, e-implication may fail when the premises entail an answer to the initial (i.e. implying) question. Since an agent may deploy these inference-patterns only insofar as it doesn't already have the answers to its questions, IEL provides inferential relations that conform to our intuitions about erotetic defeat. Initially proposed by Andrzej Wi\'{s}niewski, \textsc{Inferential Erotetic Logic} (IEL) offers a generalized semantic account of evocation and e-implication. Since our aim is to develop a proof theory for these inferences with the prospects of implementation---.e.g. in the form of an automated theorem prover---we will be concerned with the expression of these inferences in a familiar logical language, namely, that of classical propositional logic (CPL). We focus on what is known in IEL as ``regular" e-implication, which is transitive. Doing so allows us to formulate a calculus that can be equipped with a cut rule that applies to either d-wffs or e-wffs. In the conclusion, we propose an extension of the calculus that covers these non-regular inferences. Let $ \mathcal{L} $ be a formal language composed of two disjoint fragments. The first, $ \mathcal{L}_d $, consists of declarative well-formed formulas (hereafter: `d-wffs' or `statements'); the second, $ \mathcal{L}_e $, consists of interrogative formulas (hereafter: `e-wffs' or `questions'). The ``declarative part'' of $ \mathcal{L} $, i.e. $ \mathcal{L}_d $, is the language of classical propositional logic (CPL) with a countable set of atoms, $ \mathcal{A} $, which are denoted $p,q,r, s, t, u, v$, sometimes with subscripts. Arbitrary d-wffs are represented by $A, B, C, D$, (possibly empty) sets of d-wffs by $ X, \varUpsilon, Z $, and (possibly empty) sets of sets of d-wffs by $ \mathbf{S}, \mathbf{T}, \mathbf{U}, \mathbf{V}$---each may be indexed with the help of subscripts. The ``erotetic'' part of $ \mathcal{L} $, is formed by enriching $ \mathcal{L}_d $ with ``?,'' ``\{ ,'' ``\},'' and the comma---thus yielding e-wffs such as $ ?\{p\wedge q, r\vee q, \neg p \} $. The metavariables $ Q, R $ range over e-wffs. We refer to the d-wffs from which questions are formed as their \textit{direct answers} and will use $ d(\cdot) $ to denote the function that maps questions to the set of their direct answers. So, when $Q = ?\{p, \neg q \} $, $ dQ = \{p, \neg q\} $. We stipulate that $ \mathsf{card}(dQ)\geq 2 $ for any $ Q\in\mathcal{L}$. The metavariables $ F, G, H $ range over formulas and $ \Gamma, \Delta $ over sets of formulas of either type (i.e. statements or questions) in $ \mathcal{L} $. We will use `$ = $' to denote both set-theoretic identity as well as syntactic equivalence \begin{definition}[Syntax of $ \mathcal{L} $]\label{def:syntax_L} $ \mathcal{L} $ is the smallest set meeting the following criteria: \begin{itemize} \item[(i)] If $ A \in \mathcal{L}_d$, then $ A \in \mathcal{L} $. \item[(ii)] If $ A_{1},\ldots,A_{n} (n >1) \in \mathcal{L}_d$ and $ A_{1},\ldots,A_{n}$ are pairwise syntactically distinct, i.e., non-equiform, then $ ?\{A_{1},\ldots,A_{n}\} \in \mathcal{L}$. \item[(iii)] Nothing else is a member of $ \mathcal{L}$. \end{itemize} \end{definition} In their most general form, evocation and e-implication are explicated in terms of two entailment relations, one for single-conclusions and another for multiple conclusions. But since we will be working in the restricted context of CPL, we only need to use the standard, single-conclusion entailment relation for classical logic, denoted by `$ \vDash $.' The reader is welcome to supply this relation with her preferred semantics for CPL. \begin{definition}[Evocation]\label{def:erotetic_evocation} If set of d-wffs, $ X $, evokes a question, $ Q $, we write $ X\rightarrowtail Q $. \begin{equation}\nonumber X\rightarrowtail Q \textit{\:\:iff\:\:} \begin{cases} \text{(i)} & X \vDash \bigvee dQ {\:\:but} \\ \text{(ii)} & \forall A \in dQ (X \nvDash A) \end{cases} \end{equation} \end{definition} The first condition for erotetic evocation requires that an evoked question, $ Q $, has a true direct answer if the evoking set consists of truths. A question is said to be \textit{sound} iff at least one direct answer to the question is true. So the first clause of Definition \ref{def:erotetic_evocation} amounts to transmission of truth to soundness. The second condition says that no single direct answer to $ Q $ is entailed by $ X $. This constraint encodes the concept of erotetic defeat---i.e. when an agent's information state (already) entails a direct answer to a question, it is not entitled to inquire into it. Since it is possible for $ X\rightarrowtail Q $ to hold while for some $ X'\supset X $, $ X'\not\!\rightarrowtail Q $, the evocation relation is not monotonic. IEL describes a variety of e-implication relations, but for our purposes, we want to focus on one that is both transitive---so that we may have a rule of \textit{cut} in our system---and defeasible. In the language of IEL, such a relation is \textit{strong}, in the sense of being defeasible, and \textit{regular} in the sense that each answer to the implied question entails an answer to the implying one, rather than merely entailing a proper subset of answers as general e-implication does. \begin{definition}[Strong Regular Erotetic Implication, e$_{sr}$-implication]\label{def:sr_e-imp} If a question $ Q $ strongly regularly implies a question $ Q' $ on the basis of a set of d-wffs $ X $, we write $ X\mid Q \twoheadrightarrow Q' $. \begin{equation}\nonumber X\mid Q \twoheadrightarrow Q' \textit{\:\:iff\:\:} \begin{cases} \text{(i)} & \forall A \in dQ\: (X \cup \{A\} \vDash \bigvee dQ' ) {\:\:and} \\ \text{(ii)} & \forall B \in dQ'\:\exists A \in dQ \,(X \cup \{B\} \vDash A) {\:\:but}\\ \text{(iii)} & \forall A \in dQ\: (X \nvDash A) \end{cases} \end{equation} \end{definition} The first clause in Definition \ref{def:sr_e-imp} says that the implying question, together with a set of auxiliary d-wffs, $ X $, entails that at least one direct answers to the implied question is true. This ensures that the relation transmits the soundness of $ Q $ and the truth of $ X $ to the soundness of $ Q' $. The second clause guarantees that $ Q' $ is \textit{cognitively useful} relative to $ X $ and $ Q $, in the sense that each direct answer to the implied question, together with the auxiliary d-wffs, provides an answer to the initial, implying question. (For the general relation of e-implication, cognitive utility need only consist in \textit{narrowing down} the set of direct answers to the implying question). This condition aims to redeem the intuition that pursuing an implied question is an epistemically rational way of inquiring into the implying question---i.e. that drawing inferences in conformity with e-implication is a rational way of making progress in inquiry. The third clause in Definition \ref{def:sr_e-imp} ``strengthens'' regular e-implication into a nonmonontonic relation by encoding the conditions of erotetic defeat. It tells us that the erotetic inference is defeated when an agent is (already) entitled to believe an answer to its implying question. The statements of defeasibility in these definitions are quite similar. We may consider both evocation and strong regular e-implication (hereafter: e$_{sr}$-implication) as specifying conditions under which an agent is entitled to inquire into a question that forms the conclusion of an inference. Definition \ref{def:erotetic_evocation}(ii) tells us that this entitlement is lost if an agent has or acquires information that licenses a belief in one of its answers. In other words, agents should not inquire into questions for which they have the answer. Definition \ref{def:sr_e-imp}(iii) states that this entitlement is lost if an agent has or acquires information that licenses it to believe the initial, implying question's answer. The entitlement to inquire into the implied question, $ Q' $, is, after all, based on its entitlement to inquire into the initial question, $ Q $---i.e. inquiry into $ Q' $ is a kind of rational strategy for pursing inquiry into $ Q $. Thus, if an agent has the answer to $ Q $ there ceases to be a reason, \textit{ceteris paribus}, to inquire into $ Q' $. But if condition (ii) in Definition \ref{def:sr_e-imp} holds, then e$_{sr}$-implication will be similarly defeated when an agent has an answer to the implied question, $ Q' $, since if $ X\vDash B $ for some $ B\in dQ' $ and if $ \forall B \in dQ', X \cup \{B\} \vDash A $ for some $ A\in dQ $, then $ X\vDash A $, thus violating (iii). Evocation and e$_{sr}$-implication are both therefore defeated when the declarative premises entail answers to their question-conclusions. Some other features of IEL's representation of erotetic defeat are worth considering. Both inferences are defeated, for instance, when their declarative premises are inconsistent. If $ X\vDash $, then $ X\not\!\rightarrowtail Q $ and $ X\mid Q \not\twoheadrightarrow Q' $, since $ X\vDash A $ for any $ A \in dQ $. This result obtains because of CPL's respect for the principle of explosion or \textit{ex contradictione quod libet}. Philosophers, logicians, and AI researchers have long criticized the principle of explosion as unrepresentative of ordinary reasoning and have promoted paraconsistent systems in which it does not hold. But the behavior of evocation and e$_{sr}$-implication here appears to capture an important kind of incoherence that characterizes agents trying to conduct inquiry in the midst of inconsistent information. The calculus we present below respects this fact and treats an inference with inconsistent premises, i.e. any sequent with an inconsistent antecedent, as defeated. Thus, technically speaking, the system is paraconsistent insofar as there is no provable sequent corresponding to the principle of \textit{ex contradictione quod libet}. Both evocations and e$_{sr}$-implications are also defeated when one of their questions has tautologous direct answers, i.e. if some $ A\in dQ $ is valid in CPL. If there is some $ A \in dQ$ such that $ \vDash A $, then $ X\not\!\rightarrowtail Q $ and $ X\mid Q \not\twoheadrightarrow Q' $, since $ X\vDash A $. Concerns about this behavior may be raised on the grounds that it encodes an unrealistic assumption of logical omniscience. Even highly rational agents often fail to recognize the logical consequences of their beliefs, let alone tautologies. So, it seems equally unrealistic to model agents as infallible detectors of logical truths. But the defeat of these inferences in cases where their question have tautological answers aligns with the intuition that questions with such non-factual answers are often redundant, pointless, or otherwise fail to facilitate rational inquiry, at least that which deals with empirical subject matter. Again, exploring alternative formulations of these inferential relations that do not behave in this manner may be worthwhile. \section{The Calculus $ \mathsf{SC}^? $}\label{sec:SCp?} Now that we've seen the kinds of defeasible relations that IEL has to offer, the challenge is to devise a proof theory capable of encoding these relations as inference rules. Since we want our calculus to incorporate defeasible inferences involving both declarative and erotetic formulas, and since each rule will either introduce or eliminate a connective, we will have distinct rules for propositional and erotetic connectives, with the latter confined to interrogative-forming expressions of the form ``$ ?\{\ldots\} $''. We begin by formulating the calculus for d-wffs, $\mathsf{SC}^\mathbf{S} $ and proceed by extending it with rules for e-wffs. \subsection{The propositional sequent calculus $\mathsf{SC}^\mathbf{S} $}\label{subsec:SCS?} Our calculus for defeasible propositional inferences, $\mathsf{SC}^\mathbf{S} $, uses standard multiple-succedent sequents composed of \textit{sets} of formulas, e.g., $\Gamma\vdash\Delta $. Formulas on the left side of the turnstile are called the \textit{antecedent}; on the right side they are called the \textit{succedent}. Commas in the antecedent are read conjunctively and those in the succedent are read disjunctively. The formula with the connective in a rule is the \textit{principal} formula of that rule, and its components in the premises are the \textit{active} formulas. The remaining elements of sequents are referred to as \textit{side formulas}. But unlike standard sequents, ours include a set of sets of d-wffs, called a \textit{defeater set}, just below our turnstile, e.g. $ \Gamma\sststile{\mathbf{S}}{}\Delta $.\fnmark{Piazza} \fntext{Piazza}{The syntax of $\mathsf{SC}^\mathbf{S} $ sequents is inspired by the calculus in \cite{Piazza2017}. } We interpret sequents as representing a relationship that preserves an agent's epistemic entitlement to adopt doxastic and interrogative attitudes. We use the terms `entitled,' `licensed,' `rational,' and `permissible' interchangeably to denote this preserved status. Thus, a provable sequent says that any agent entitled to \textit{believe} the statements and to \textit{inquire into} the questions in the antecedent is entitled to \textit{believe} or \textit{inquire into} at least one of the statements/questions in the succedent. While sequents represent rules of entitlement-preserving inference, the rules of our calculus are meta-rules of inference---i.e., they tell us what rules of inference are legitimate given the axioms. Defeater sets represent situations in which one is not permitted to draw the inference represented by the sequent. A purely declarative sequent such as $ A\sststile{\{C_1, C_2\}, \{C_3\}}{}B $ says that an agent who is entitled to believe that $ A $ is entitled to believe that $ B $ unless it is entitled to believe $ C_1 $ or $ C_2 $ or to believe that $ C_3 $. As this interpretation suggests, a sequent is defeated when an agent is licensed to believe at least one statement in a member (set) of the defeater set. (As we explain in Section \ref{subsec:ED}, treating defeater sets as sets of sets permits us to represent the peculiar conditions of erotetic defeat.) D-wffs in the antecedent of a sequent specify which statements an agent is entitled to believe. Roughly put, a sequent is defeated when some statement in a member (set) of the defeater set is the (classical) logical consequence of its antecedent. This amounts to assuming that an agent's belief set is closed under (classical) logical consequence. $\mathsf{SC}^\mathbf{S} $ is inspired by Smullyan's \citeyearpar{Smullyan1968} ``symmetric'' sequent calculus for CPL, $ \mathscr{S} $, though it departs from that calculus in certain respects, canvassed below. The core characteristic of $ \mathscr{S} $ that is carried over to $\mathsf{SC}^\mathbf{S} $ is that the calculus does not allow for switching formulas from one side of a sequent to another. Consequently, an end-sequent's subformulas occur on the same side of the turnstile throughout a derivation. As we shall see, this constraint is important for preserving the intuitive meaning of defeasible sequents. The rules for $\mathsf{SC}^\mathbf{S} $ are given in Figure \ref{fig:SCd}. Note that sets of side formulas that appear in these rules are represented by $\Gamma$ and $ \Delta $ which we defined as ranging over members of $ \mathcal{P}(\mathcal{L}).$ Strictly speaking, however, $\mathsf{SC}^\mathbf{S} $ is defined over $ \mathcal{L}_d $. We use the metavariables $ \Gamma, \Delta $ to obviate re-writing the rules when we extend the calculus for $ \mathcal{L} $. Like Smullyan's $ \mathscr{S} $, our calculus, $\mathsf{SC}^\mathbf{S} $, replaces the familiar negation rules of $ \mathsf{LK} $ with rules for double negation and De Morgan's Laws, as well as two additional axioms. But in contrast with $ \mathscr{S} $, $\mathsf{SC}^\mathbf{S} $ includes structural rules, multiplicative rather than additive versions of the rules for connectives, and axioms (four rather than three as in $ \mathscr{S} $) that do not permit arbitrary side-formulas. Proofs in the calculus are the familiar tree structures of sequent calculi, but since sequents may be defeated, we distinguish between derivations (i.e. trees constructed via the application of rules irrespective of whether the sequents are defeated) and proofs (i.e. trees in which no defeated sequents occur). \begin{definition}[Derivation, Proof, Paraproof]\label{def:proof} If a defeasible sequent, $\Gamma\sststile{\mathbf{S}}{}\Delta $, occurs at the root of a finitely branching tree, $ \pi $, whose nodes are defeasible sequents recursively built up from axioms by means of the rules of $ \mathsf{SC}^\mathbf{S}$ ($ \mathsf{SC}^?$), then $ \pi $ is said to be a \textit{derivation} of $ \Gamma\sststile{\mathbf{S}}{}\Delta $. If, additionally, each sequent in $ \pi $ is undefeated, then $ \pi $ is said to be a \textit{proof} of $ \Gamma\sststile{\mathbf{S}}{}\Delta $ in $\mathsf{SC}^\mathbf{S}$ ($ \mathsf{SC}^?$),\, otherwise $ \pi $ is called a \textit{paraproof} of $\Gamma\sststile{\mathbf{S}}{}\Delta $. \end{definition} So defeat and defeasibility play no role in determining which sequents are derivable in $\mathsf{SC}^\mathbf{S} $. Indeed, if we restrict our attention to derivable sequents in $\mathsf{SC}^\mathbf{S} $, we have a calculus that is but a variation of Smullyan's $ \mathscr{S} $---differing in the aspects noted above. \begin{lemma}\label{lem:SCtoSCS} $ X\sststile{\mathbf{S}}{}\varUpsilon$ is derivable in $\mathsf{SC}^\mathbf{S} $ iff $ X\vdash\varUpsilon $ is provable in $ \mathscr{S} $. \end{lemma} Smullyan's $ \mathscr{S} $ is sound and complete for CPL. So, it follows from Lemma \ref{lem:SCtoSCS} that the antecedent of any sequent derivable in $\mathsf{SC}^\mathbf{S} $ classically entails the disjunction of the elements in the succedent. \begin{lemma}\label{lem:SCS=CPL} $ X\sststile{\mathbf{S}}{}\varUpsilon$ is derivable in $\mathsf{SC}^\mathbf{S} $ iff $ X\vDash\bigvee\varUpsilon $. \end{lemma} Derivations in the system therefore constitute a calculus that is sound and complete for CPL. The upshot of the distinction between derivations and proofs in $\mathsf{SC}^\mathbf{S} $ is that we are able to mobilize the classical consequence relation without having to appeal to an ``external'' calculus. This, in turn, permits us to define the conditions of defeat internally, making $\mathsf{SC}^\mathbf{S} $, in a sense, self-contained. \begin{definition}[Defeat in $\mathsf{SC}^\mathbf{S} $]\label{def:defeat_in_SCd} A sequent is defeated just in case there is sequent derivable in $\mathsf{SC}^\mathbf{S} $ that has the same antecedent and a succedent that is a member of the original sequent's defeater set. (The content of the defeater set of this derivable sequent, i.e. $\mathbf{T}$, is irrelevant.) $$ X\sststile{\mathbf{S}}{}\varUpsilon\text{ \: is defeated \textit{iff} \:} \exists Z\in\mathbf{S} \text{\, such that \,} X\sststile{\mathbf{T}}{}Z \text{\:is derivable in \:}\mathsf{SC}^\mathbf{S}. $$ \end{definition} The definition of \textit{defeat} is designed to redeem certain intuitions about defeasible inferences. For instance, if $ A $ defeats an inference, then an agent entitled to $ A\wedge B $ ought not to make it (Example \ref{ex:con_in_ant}). Conversely, if $ A \wedge B $ defeats an inference but neither $ A $ nor $ B $ does by itself, then the agent entitled to only one of the conjuncts may still draw the inference (Example \ref{ex:con_in_def}). Similarly, if $ A\vee B $ defeats an inference, then the inference is defeated if the agent is entitled to either of the disjuncts (Example \ref{ex:dis_in_def}). Finally, if $ A $ defeats an inference, then entitlement to $ A\vee B $ need not force an agent to reject it, since entitlement to $ B $ would preserve the propriety of the inference (Example \ref{ex:dis_in_ant}). \begin{example}\label{ex:con_in_ant} $ p\wedge q \sststile{ \{\{p \}\} }{} \Delta $ is defeated. \end{example} \begin{example}\label{ex:con_in_def} $ p\sststile{\{\{p \wedge q\}\}}{} \Delta $ is undefeated. \end{example} \begin{example}\label{ex:dis_in_def} $ p \sststile{\{\{p\vee q \}\}}{} \Delta $ is defeated. \end{example} \begin{example}\label{ex:dis_in_ant} $ p \vee q \sststile{\{\{p\}\}}{} \Delta $ is undefeated. \end{example} Notice that when a sequent has an empty defeater set, i.e. $ \Gamma\sststile{\emptyset}{}\Delta $, the defeat mechanism in $\mathsf{SC}^\mathbf{S} $ is idle. Typically, defeasible logics contain defeasible or ``non-strict'' rules and indefeasible or ``strict'' rules. In $\mathsf{SC}^\mathbf{S} $ strict inference rules are represented by these sequents with empty defeater sets, while defeasible inferences are captured by sequents with nonempty defeater sets. (Since axioms may have empty or nonempty defeater sets, the calculus permits a mix of strict and non-strict rules.) With the notion of defeat in hand, we can now observe the advantage accrued by using ``symmetric'' sequent rules---namely, to remain faithful to the informal reading of sequents as ordinary defeasible inferences and, in keeping with that goal, to ensure that unary (i.e. one-premise) rules preserve defeat downward and undefeatedness upward. \begin{fact}[Unary Rules Preserve Defeat Downward]\label{fact:DdefeatUnary} If $ \Gamma\sststile{\mathbf{S}}{}\Delta $ follows from $ \Gamma'\sststile{\mathbf{S'}}{}\Delta' $ via a unary rule (i.e. $\mathsf{LW},\mathsf{RW},\mathsf{DE},{\wedge}{\vdash}, {\vdash}{\vee}, {\neg}{\neg}{\vdash}, {\vdash}{\neg}{\neg},\\ {\vdash}{\neg}{\wedge}, {\neg}{\vee}{\vdash} $), then $ \Gamma\sststile{\mathbf{S}}{}\Delta $ is defeated if $ \Gamma'\sststile{\mathbf{S'}}{}\Delta' $ is defeated. Contrapositively, if $ \Gamma\sststile{\mathbf{S}}{}\Delta $ is undefeated, then $ \Gamma'\sststile{\mathbf{S'}}{}\Delta' $ is undefeated. \end{fact} \noindent The right rule for negation in $ \mathsf{LK} $, on the other hand, frustrates both desiderata. $$\begin{prooftree \Hypo{\Gamma,A\sststile{\mathbf{S}}{}\Delta} \Infer1[$\vdash\neg$]{\Gamma\sststile{\mathbf{S}}{}\neg A, \Delta} \end{prooftree}$$ \noindent If, e.g., $ A \in \bigcup\mathbf{S} $, then the upper sequent is defeated while the lower sequent is not. It is rather counter-intuitive to think that applying a purely logical, unary rule of meta-inference should have this effect. Moreover, it is quite difficult to give an intuitively plausible reading of this rule as it appears to warrant an agent's abandoning entitlement to a belief, i.e. that $ A $. The binary rules ${\vdash}{\wedge}$ and ${\vdash}{\neg\vee}$ also preserve defeat downwards and undefeatedness upwards. They share this property in virtue of their multiplicative formulation. Since the antecedents of premises-sequents in this rule are combined in the conclusion, any defeat that occurs in the premises is carried downward. \begin{fact}[${\vdash}{\wedge}$ and ${\vdash}{\neg\vee}$ Preserve Defeat Downward]\label{fact:Ddefeattwobinary} If $ \Gamma\sststile{\mathbf{S}}{}\Delta $ follows from $ \Gamma'\sststile{\mathbf{S'}}{}\Delta' $ and $ \Gamma''\sststile{\mathbf{S''}}{}\Delta'' $ via ${\vdash}{\wedge}$ or ${\vdash}{\neg\vee}$, then $ \Gamma\sststile{\mathbf{S}}{}\Delta $ is defeated if either $ \Gamma'\sststile{\mathbf{S'}}{}\Delta' $ or $ \Gamma''\sststile{\mathbf{S''}}{}\Delta'' $ is defeated. Contrapositively, if $ \Gamma\sststile{\mathbf{S}}{}\Delta $ is undefeated, then $ \Gamma'\sststile{\mathbf{S'}}{}\Delta' $ and $ \Gamma''\sststile{\mathbf{S''}}{}\Delta'' $ are undefeated. \end{fact} In contrast, the binary rules $ {\vee}{\vdash} $ and $ {\neg}{\wedge}{\vdash} $ permit the derivation of undefeated sequents from defeated ones. This fact, which figures prominently in the proof of Lemma \ref{lem:Derivable_undefeated_provable_SCs} below, arises because the rules' active formulas are logically stronger than their principal formula. Consequently, a member of the conclusion's defeater set may follow (classically) from either of the premises' antecedents while not following from the conclusion's. \begin{fact}[Derivation of Undefeated Sequents from Defeated Ones]\label{fact:DeriUNDefeat} Undefeated sequents can only be derived from (one or more) defeated sequents via $ {\vee}{\vdash} $ and $ {\neg}{\wedge}{\vdash} $. \end{fact} The inclusion in $\mathsf{SC}^\mathbf{S} $ of a rule for left weakening may surprise the reader, as this rule is typically associated with monotonicity. When a sequent's antecedent is weakened by a formula that entails a member of the defeater set, however, the result is a defeated sequent. As Definition \ref{def:proof} makes clear, proofs in the calculus must not contain defeated sequents. Thus, provability in the calculus will indeed conform to nonmonotonicity. A rule for expanding the defeater set, $ \mathsf{DE} $, is also provided in order to represent cases of reasoning in which new information about defeaters is acquired. While undefeated sequents can only be obtained from defeated ones via $ {\vee}{\vdash} $ or $ {\neg}{\wedge}{\vdash} $, defeated sequents may be derived from undefeated ones by any rule that expands the antecedent or defeater set of the conclusion. These include not only $\mathsf{LW},\mathsf{DE}$ but also the multiplicative binary rules ${\vee}{\vdash}, {\vdash}{\wedge}, {\neg}{\wedge}{\vdash}, {\vdash}{\neg}{\vee} $. \begin{fact}[Derivation of Defeated Sequents]\label{fact:DeriDefeat} Defeated sequents can only be derived from (one or more) undefeated sequents via $\mathsf{LW},\mathsf{DE}, {\vee}{\vdash}, {\vdash}{\wedge},\\ {\neg}{\wedge}{\vdash}, {\vdash}{\neg}{\vee} $. \end{fact} The engine of defeat in the calculus are the axioms and their respective defeater sets. The rules $ ax_1, ax_2 $ and $ ax_3 $ provide sequents with equivalent, possibly empty defeater sets. The members of these sets encode (extra-logical) conditions under which an agent is not entitled to believe that the atom is true. We restrict these sets to literal formulas and insist that they not include the atom that they introduce or its negation, i.e. $ p, \neg p\not\in\bigcup\mathbf{S} $. This constraint ensures that the axioms will not introduce defeated sequents. Moreover, permitting the negations of atoms in the defeater sets would be redundant; inconsistent antecedents uniformly yield defeated sequents, since $ A, \neg A \vdash_\mathsf{SC} X $ for any set $ X \in \mathcal{L}_d $. Among other things, this means that there is no provable \textit{defeasible} sequent in $ \mathsf{SC}^\mathbf{S} $ corresponding to the law of \textit{ex contradictione quod libet} and to this extent, the calculus behaves paraconsistently. However, initial sequents of the form $ p,\neg p\vdash $ derived by the rule $ ax_4 $ are exempted from this behavior and their defeater sets are empty. The reasons for this are both conceptual and technical. The technical reason is that, as just noted, any sequent with an inconsistent antecedent and nonempty defeater set is automatically defeated. The conceptual reason is that defeaters follow the conclusions of inferences, in the sense that they tell agents when they are not authorized to infer beliefs. So it is only when formulas occur on the right-hand side of the turnstile that defeaters specific to those formulas are relevant. The calculus' ``symmetric'' logical rules ensure that these defeaters travel with their respective formulas, so to speak, throughout a derivation. \begin{definition}[Axiom Defeater Sets]\label{def:const-axioms} For any atom $ p $, we assign a set of (sets of) defeaters, denoted $ \mathcal{S}_p $, such that $ \bigcup\mathcal{S}_p \subset (\mathcal{A}\cup \{\neg q \mid q\in \mathcal{A}\}) \backslash \{p, \neg p\} $ \end{definition} Given the ``symmetric'' structure of $\mathsf{SC}^\mathbf{S} $, this constraint guarantees that the end-sequent of any $ \mathsf{RW} $-free derivation will contain, in its defeater set, the defeaters of every atom that occurs in the succedent. \begin{fact}\label{fact:atomdefeatpres} If $ \Gamma\sststile{\mathbf{S}}{}\Delta $ is the end-sequent of a $ \mathsf{RW} $-free derivation in $\mathsf{SC}^\mathbf{S} $, then $ \mathcal{S}_p \subset\mathbf{S}$ for all $ p\in \mathcal{A}(\Delta) $, where $ \mathcal{A}(\Delta) $ denotes the set of atoms that occur in any member of $ \Delta $. \end{fact} We close this section by establishing the soundness and completeness of the propositional calculus $\mathsf{SC}^\mathbf{S}$. \begin{definition}[Compatibility, $ \succsim $ for $\mathsf{SC}^\mathbf{S}$]\label{def:compatinSCs} When a set of d-wffs, $X$, and a set of sets of d-wffs, $ \mathbf{S} $, fail to meet the conditions of defeat, they are said to be \textit{compatible}. We use the symbol `$ \succsim $' to denote this relationship, which we define formally as follows: $$ X\succsim\mathbf{S} \:\textit{iff}\text{\:\:there is }no\:\,\varUpsilon\in\mathbf{S}\text{\, such that \,} \Gamma\sststile{\mathbf{T}}{} \varUpsilon\:\text{is derivable in}\: \mathsf{SC}^\mathbf{S}.$$ We omit set notation on the left-hand side when there is no threat of misunderstanding, writing $ X, A \succsim \mathbf{S\cup T} $ for $ X\cup\{A\} \succsim \mathbf{S}\cup\mathbf{T} $. When this relation fails to hold, we say that $ X $ and $ \mathbf{S} $ are \textit{incompatible} and express this by writing: $ X\not\succsim\mathbf{S} $. \end{definition} Although derivable sequents correspond to classical entailments, not all derivations are proofs. Thus, to establish the completeness of the calculus, we must show that every derivable \textit{undefeated} sequent has a proof. \begin{lemma}[Derivable undefeated sequents are provable]\label{lem:Derivable_undefeated_provable_SCs} If $ X\sststile{\mathbf{S}}{}\varUpsilon$ is undefeated (i.e. $ X\succsim\mathbf{S} $) and derivable in $\mathsf{SC}^\mathbf{S} $, then there is a proof of $ X\sststile{\mathbf{S}}{}\varUpsilon$ in $\mathsf{SC}^\mathbf{S} $. \begin{proof} We proceed by induction on proof-height. For the base case, $ X\sststile{\mathbf{S}}{}\varUpsilon$ is obtained by an application of an axiom, and since it is undefeated (in fact following the constraints imposed on axiom defeater sets, it must be undefeated), the result is a proof. For induction, assume that any undefeated sequent whose derivation height is $ \leq h$ has a proof and that $ X\sststile{\mathbf{S}}{}\varUpsilon$ has a derivation height of $ h+1 $. The proof for the inductive case utilizes the following technique. Take the derivation of $ X\sststile{\mathbf{S}}{}\varUpsilon$ and for every sequent that occurs in the proof, replace its defeater set with the empty set. Next, remove every instance of the $ \mathsf{DE} $-rule---these are now redundant given that all sequents have empty defeater sets. Finally apply $ \mathsf{DE} $ to the end-sequent as needed to obtain its original defeater set. By hypothesis, the end-sequent is undefeated and all other sequents in the derivation are undefeated either because they are the result of applying $ \mathsf{DE} $ to obtain the original end-sequent or because their defeater sets are empty. The derivation thus obtained is a proof. We illustrate this technique with the following example. $$\begin{prooftree}[template = \small$\inserttext$] \Hypo{} \Infer1[$ ax. $]{p \sststile{\{\{t\}\}}{} p} \Hypo{} \Infer1[$ ax. $]{r \sststile{\{\{p\}\}}{} r} \Infer2[${\vdash}{\wedge}$]{ p, r \sststile{\{\{t\},\{p\}\}}{} p\wedge r} \Hypo{} \Infer1[$ ax. $]{q \sststile{\{\{s\}\}}{} q} \Infer1[$\mathsf{DE}$]{q \sststile{\{\{s\},\{q\}\}}{} q} \Infer2[${\vee}{\vdash}$]{ p\vee q, r \sststile{\{\{t\},\{p\},\{s\},\{q\}\}}{} p\wedge r, q} \end{prooftree}$$ \vspace{2mm} \noindent Since $ p, r \sststile{\mathbf{S}}{} p$ is derivable in $ \mathsf{SC}^\mathbf{S} $ we know that $ p, r\not\succsim \{\{p\},\{s\}\} $ and that $ p, r \sststile{\{\{p\},\{s\}\}}{} p\wedge r $ is thus defeated. Similarly, $ q \sststile{\{\{s\},\{q\}\}}{} q $ is defeated. We now apply the technique described above to obtain a proof. $$\begin{prooftree}[template = \small$\inserttext$] \Hypo{} \Infer1[$ ax. $]{p \sststile{\emptyset}{} p} \Hypo{} \Infer1[$ ax. $]{r \sststile{\emptyset}{} r} \Infer2[${\vdash}{\wedge}$]{ p, r \sststile{\emptyset}{} p\wedge r} \Hypo{} \Infer1[$ ax. $]{q \sststile{\emptyset}{} q} \Infer2[${\vee}{\vdash}$]{ p\vee q, r \sststile{\emptyset}{} p\wedge r, q} \Infer1[$\mathsf{DE}$]{ p\vee q, r \sststile{\{\{t\}}{} p\wedge r, q} \Ellipsis{}{} \Infer1[$\mathsf{DE}$]{ p\vee q, r \sststile{\{\{t\},\{p\},\{s\},\{q\}\}}{} p\wedge r, q} \end{prooftree}$$ \vspace{2mm} \end{proof} \end{lemma} \begin{lemma}[Soundness and Completeness of $\mathsf{SC}^\mathbf{S} $]\label{lem:Sound&CompleteSCs} $ X\sststile{\mathbf{S}}{}\varUpsilon$ is provable in $\mathsf{SC}^\mathbf{S} $ iff $ X\vDash\bigvee\varUpsilon $ and $ X\nvDash\bigvee(\bigcup\mathbf{S}) $. \begin{proof} ($ \Rightarrow $) By Lemma \ref{lem:SCS=CPL} and Definition \ref{def:compatinSCs}, it follows that $ X\nvDash\bigvee(\bigcup\mathbf{S}) $ iff $X\succsim\mathbf{S}$. Since, according to Definition \ref{def:proof}, every provable sequent is derivable and undefeated (i.e. $X\succsim\mathbf{S}$), we obtain the desired result via Lemmas \ref{lem:SCS=CPL} and \ref{lem:Derivable_undefeated_provable_SCs}.\\ ($ \Leftarrow $) From Lemmas \ref{lem:SCS=CPL} and \ref{lem:Derivable_undefeated_provable_SCs}. \end{proof} \end{lemma} \subsection{Erotetic Defeat in $\mathsf{SC}^{?}$}\label{subsec:ED} We now extend $ \mathsf{SC}^\mathbf{S}$ to $\mathsf{SC}^{?}$, whose rules are presented in Figure \ref{fig:SC?}. The axioms for this extension remain unchanged, as do the logical rules that apply to d-wffs, now explicitly restricted to the latter. The rule for defeater set expansion, $ \mathsf{DE} $ is also preserved, but $ \mathsf{LW} $ and $\mathsf{RW} $ are generalized to apply to any formula in $ \mathcal{L} $, as ranged over by the variables $ F, G, H $. Finally, $\mathsf{SC}^{?}$ contains four rules that yield e-wffs in sequents. We discuss each in detail below, but first we define defeat in $\mathsf{SC}^{?}$. We extend the notion of defeat conservatively to ensure that sequents which are defeated in $\mathsf{SC}^\mathbf{S}$ remain defeated in $\mathsf{SC}^{?}$. To that end, we introduce the function, $\mathcal{E}(\cdot)$, which maps subsets of $ \mathcal{L} $ to subsets of $\mathcal{L}_d $. This function allows us to define defeat in $\mathsf{SC}^{?}$ in terms of defeat in $\mathsf{SC}^\mathbf{S}$. \begin{definition}[$\mathcal{E}(\cdot)$]\label{def:EClo} Recall that d-wffs are ranged over by the variables $ A,B,C $ (with subscripts). Let $ \mathcal{E}(\Gamma) $ denote the set that results from removing all e-wffs from $ \Gamma $ and replacing them with a disjunction of their declarative constituents, i.e. $$ \mathcal{E}(\Gamma) = \{A: A\in\Gamma\}\cup\{A_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} A_n: \:?\{A_1,\ldots,A_n\} \in \Gamma\}$$ \noindent We say that $ \mathcal{E}(\Gamma) $ \textit{declarativizes} $ \Gamma $. \end{definition} \begin{definition}[Defeat in $\mathsf{SC}^{?}$]\label{def:defeat} A sequent in $\mathsf{SC}^{?}$ is defeated just in case a sequent with the declarativized antecedent and a succedent composed of at least one member of the defeater set is derivable in $\mathsf{SC}^\mathbf{S} $. $$\Gamma\sststile{\mathbf{S}}{}\Delta\text{\,\,is defeated \textit{iff}\,} \exists X\in\mathbf{S} \text{\,\,such that\,\,} \mathcal{E}(\Gamma)\sststile{\mathbf{T}}{} X \text{\,is derivable in\,\,}\mathsf{SC}^\mathbf{S}.$$ \end{definition} We are now able to see how erotetic defeat is represented in our calculus and to explain why defeater sets are drawn from subsets of $ \mathcal{P}(\mathcal{P}(\mathcal{L}_d)) $. Recall that, in general, an erotetic inference is defeated when an agent is licensed to believe a direct answer to the relevant question---i.e. the question to which the agent would otherwise be licensed to inquire into. In order to capture this phenomenon, we must represent situations in which an agent is entitled to inquire into a question on the grounds of her entitlement to believe that at least one of its answers is true but in which, if the agent \textit{were} to gain entitlement to a particular answer, she would lose her license to inquire into it. Erotetic inferences are permissible when an agent knows that at least one answer to its question is true without knowing which one, but are not permissible when the agent knows a particular answer. Representing information about defeaters as sets of sets allows us to capture these situations. Consider the following: \begin{example}\label{ex:Q_in_succ} $ p\vee\neg p\sststile{\{\{p\}\{\neg p\}\}}{} \:?\{p, \neg p\} $ \end{example} \noindent If the sequent in Example \ref{ex:Q_in_succ} is provable, then the agent's entitlement to $ p\vee\neg p $ licenses it to inquire into the question $ ?\{p, \neg p\} $, since it is entitled to believe that at least one of its answers is true. But were the agent to obtain information that licensed the belief that $ p $ or that $ \neg p $---represented by adding either d-wff to the antecedent---it would forfeit that entitlement. Placing each direct answer to the succedent-question as a singleton in the defeater set has the effect of maintaining entitlement to believe that at least one answer to a question is true while barring such entitlement when a particular direct answer is obtained. As we shall demonstrate, Example \ref{ex:Q_in_succ} is interpretable as an inference rule underwritten by the evocation relation. Sequent-analogs to e$_{sr}$-implication are also available. The sequent in Example \ref{ex:Q_in_eimp} would be defeated were either $ q $ or $r $ (i.e. the direct answers to the implying question) added to its antecedent. \begin{example}\label{ex:Q_in_eimp} $ \neg p \vee q, p \vee r, ?\{q, r\}\sststile{\{\{q\}\{r\}\}}{} \:?\{p, \neg p\} $ \end{example} \subsection{Rules for E-wffs in $\mathsf{SC}^{?}$}\label{subsec:SCp?rules} Let us now turn to the e-wff rules in the calculus. As set-theoretic notation often becomes cumbersome, we avail ourselves of the following abbreviations. \begin{definition}[Abbreviations]\label{def:abbrev} \hspace{1mm} \begin{itemize} \item $ ?[A_{\mid n}] $ abbreviates $ ?\{A_{1},\ldots,A_{n}\} $. \item $ [A_{\mid n}] $ abbreviates $ \{A_{1},\ldots,A_{n}\} $. \item $ \Gamma_{\mid n} $ and $ \mathbf{S}_{\mid n} $ abbreviate $ \Gamma_1 \cup \ldots \cup \Gamma_n$ and $ \mathbf{S}_1 \cup \ldots \cup \mathbf{S}_n$, respectively. \item $ [\mathbb{A}_{\mid n}] $ abbreviates $ \{\{A_{1}\},\ldots,\{A_{n}\}\} $. \end{itemize} \end{definition} $\mathsf{SC}^{?}$ provides right and left rules for e-wffs (i.e., $ {\vdash}{?_1} $,$ {\vdash}{?_2} $, $ {?}{\vdash_1} $, and $ {?}{\vdash_2}$). Since right and left rules for connectives in a sequent calculus correspond, respectively, to the introduction and elimination rules in natural deduction, we will say that the rules $ {\vdash}{?_1} $ and $ {\vdash}{?_2} $ govern the introduction of e-wffs and that $ {?}{\vdash_1} $ and $ {?}{\vdash_2}$ govern their elimination. Two pairs of introduction and elimination rules are needed to capture the distinction between evocation and e-implication. Both inference types have questions as their conclusions, but while the premises of the latter also include a question, those of the former do not. To represent evocation, we need a rule that permits the introduction (resp. elimination) of e-wffs in sequents whose antecedents (resp. succedents) consist solely of d-wffs, while representing implication requires a rule that permits such introduction (resp. elimination) in cases when the antecedents (resp. succedents) also contain e-wffs. It is natural to think that beliefs alone license inquiry in a manner that differs from the way beliefs \textit{plus} prior inquisitive commitments, represented by questions, license further inquiry. Formulating two versions of each introduction and elimination rule is an elegant way to respect this difference. Let's examine $ {\vdash}{?_1} $. $$\begin{prooftree \Hypo{ X\sststile{\mathbf{S} }{} A_1,\ldots,A_n, \Delta} \Infer1[$\vdash?_{\scriptstyle 1}$]{X\sststile{\mathbf{S}\,\cup\,\{\{A_1\},\ldots,\{A_n\}\}}{} \: ?\{A_1,\ldots,A_n\}, \Delta} \end{prooftree}$$ \vspace{.5mm} \noindent Ignoring side formulas, we read the rule as saying that an agent entitled to believe that some statement in the set $ \{A_{1},\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi,A_{n}\} $ is true is thereby entitled to inquire into the question $ ?\{A_{1},\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi,A_{n}\} $, so long as she is not entitled to believe any particular member of that set, i.e. any direct answer to the question. While this rule is intended to capture evocation, it actually represents a more general relationship, since the succedents of the premise and conclusion may include a set of side formulas composed of d-wffs or e-wffs. The generality of the rule is motivated by the desire to formulate rules for e-wffs that conform to the standard format of multiple-succedent calculi. When there are no side formulas, the rule $\vdash?_{\scriptstyle 1}$ faithfully depicts evocation, as demonstrated by Theorem \ref{thrm:S+C_EE} below. The first condition in Definition \ref{def:erotetic_evocation} is satisfied by the fact that the succedent of the premise, i.e.$ \{A_1,\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi,A_n\} $, contains all of the direct answers to the question in the succedent of the conclusion, i.e., $?\{A_1,\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi,A_n\} $. Satisfying the second condition of erotetic evocation, i.e. the one concerning its defeasibility, requires significant exploitation of the defeater set mechanism. Recall that this condition prohibits evocation whenever the set of d-wffs entails a direct answer to the evoked question. By including singletons of each direct answer in the defeater set of the conclusion, $ \vdash ?_1 $ guarantees that the set of auxiliary d-wffs does not entail a direct answer to the evoked question. Since defeat is defined as a relation between the d-wffs in the antecedent set on one hand, and members of the defeater set on the other, the inclusion of direct answers as separate sets permits $ X $ to fulfill the second condition without jeopardizing its satisfaction of the first. Let us now consider the left-rule for e-wffs, $ {?}{\vdash_1} $. $$\begin{prooftree \Hypo{\Gamma_1, A_1 \sststile{\mathbf{S}_1}{} X_1} \Hypo{\hspace{-5.5mm}\ldots\Gamma_n, A_n \sststile{\mathbf{S}_n }{} X_n} \Infer2[${?}{\vdash_{\scriptstyle 1}}$]{ \Gamma_{\mid n}, ?\{A_1,\ldots,A_n\} \sststile{\mathbf{S}_{\mid n}\,\cup\,\{\{A_1\},\ldots,\{A_n\}\}}{}X_{\mid n}} \end{prooftree}$$ Again ignoring side formulas, the rule says that an agent entitled to believe at least one member of a set of statements, $ X $, on the basis of its entitlement to believe $ A_1 $ or \ldots or $ A_n $ is also entitled to $ X $ on the basis of its entitlement to inquire into the question $ ?\{A_{1},\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi,A_{n}\} $, so long as it is not licensed to believe one of its answers. The observant reader will no doubt have noticed that $ {\vdash}{?_1} $ and $ {?}{\vdash_1} $ are essentially expanded versions of the classical elimination rules for $ \vee $ in $ \mathsf{SC}^\mathbf{S} $. This overlap is to be expected, since questions in IEL for classical logic \textit{presuppose} that at least one of their possible answers is true. However, the addition of formulas to the conclusion's defeater set shows that $ {\vdash}{?_1} $ (resp. $ {?}{\vdash_1} $) is not equivalent to $ \vdash\vee $ (resp. $ \vee\vdash $). We now turn to the second introduction rule for e-wffs, i.e., $ \vdash ?_2 $. $$\begin{prooftree}[template = \small$\inserttext$] \Hypo{\Gamma_1, ?[A_{\mid n}]\sststile{\mathbf{S}}{}[B_{\mid m}], \Delta_1} \Hypo{\Gamma_2, B_{1}\sststile{\mathbf{T}_{1} }{} A_i, \Delta_2} \Hypo{\hspace{-6.5mm}\ldots\Gamma_{m+1}, B_{m}\sststile{\mathbf{T}_{m} }{} A_{j}, \Delta_{m+1}} \Infer3[${\vdash}{?_{\scriptstyle 2}}$]{ \Gamma_{\mid m+1} , ?[A_{\mid n}] \sststile{\mathbf{S}\,\cup\,\mathbf{T}_{\mid m}\cup\,\{\{A_1\},\ldots,\{A_n\}\}}{} \,?[B_{\mid m}], \Delta_{\mid m+1}} \end{prooftree}$$ This rule may be read top-down, omitting side formulas, as follows: anyone entitled to believe that $ B_1 $ or \ldots or $ B_m $ on the basis of its entitlement to inquire into $ ?\{A_{1},\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi,A_{n}\} $ and whose entitlement to believe any member of $ \{B_{1},\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi,B_{n}\} $ licenses an answer to that question (i.e. $ \{A_i,\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi,A_j\} \subseteq \{A_{1},\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi,A_{n}\}$), is thereby entitled to inquire into $ ?\{B_{1},\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi,B_{n}\}$, so long as she is not licensed to believe one of its answers. The rule is intended to capture the relation of e$_{sr}$-implication. The left-most premise roughly corresponds to the first clause in Definition \ref{def:sr_e-imp}, according to which an answer to the implying question, together with the set of d-wffs, entails that there is a true answer to the implied question. The premises to the right roughly correspond to the second condition, according to which, an answer to the implied question, together with the set of d-wffs, entails an answer to the implying question. The presence of the direct answers to $ ?\{A_{1},\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi,A_{n}\} $ as singletons in the conclusion's defeater set attempts to capture e$_{sr}$-implication as stated in Definition \ref{def:sr_e-imp}'s third clause. We note that the d-wffs that appear in the succedent of the second set of premise, i.e. $ A_i,\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi,A_j $, may include any of those that occur in $ \{A_{1},\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi, A_{n}\} $. They need not exhaust the latter and it is perfectly acceptable that $ i=j $. This applies to the proviso on $ {?}{\vdash_2} $ as well. Admittedly, $ {\vdash}{?_2} $ encodes less restrictive conditions than those imposed by e$_{sr}$-implication insofar as it permits side formulas of either the declarative or erotetic sort. Again, this liberalization brings the rule into conformity with standard rules in classical sequent calculi. Finally, we turn to $ {?}{\vdash_2} $ (see Figure \ref{fig:SC?}). We read the rule top-down, omitting side formulas, as follows: an agent who is entitled to inquire into $ ?\{B_1,\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi, B_m\} $ on the basis of entitlement to believe any statement from the set $\{A_{1},\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi, A_{n}\} $ and who is entitled to believe some statement in the latter on the basis of her entitlement to believe any statement in $ \{B_1,\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi, B_m\} $, is thereby licensed to inquire into $ ?\{B_1,\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi, B_m\} $ if she is entitled to inquire into $ ?\{A_{1},\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi, A_{n}\} $, so long as she is not licensed to believe one of its answers. Recall that the motivation behind $ \vdash ?_1 $ and $ \vdash ?_2 $ is that in order to represent evocation and e$_{sr}$-implication, a calculus needs to distinguish between inferences in which a question follows from a set of statements and those in which a question follows from at least one question. Symmetry demands that we respect this difference in our elimination rules as well. \section{Main Results}\label{sec:Results} We move now to proving that certain classes of sequents in $\mathsf{SC}^{?}$ are sound and complete with respect to evocation and e$_{sr}$-implication. We begin with some helpful Lemmas. \begin{definition}[Compatibility, $ \succsim $, in $ \mathsf{SC}^? $]\label{def:compat_in_SC?} When a set of formulas, $ \Gamma $, and a set of sets of d-wffs, $ \mathbf{S} $, fail to meet the conditions of defeat, they are said to be \textit{compatible}. We use the symbol `$ \succsim $' to denote this relationship, which we define formally as follows: $$ \Gamma\succsim\mathbf{S} \:\textit{iff}\text{\:\:there is no}\:\,X\in\mathbf{S}\text{\, such that \,} \mathcal{E}(\Gamma)\sststile{\mathbf{T}}{} X\:\text{is derivable in}\: \mathsf{SC}^\mathbf{S}.$$ Again, we use the comma for set union when there is no threat of misunderstanding. \end{definition} \begin{definition}[Provability of sequents in $ \mathsf{SC}^{?} $] We write $\Gamma \sststile{\mathbf{S}}{\mathsf{SC}^{?}} \Delta $ to denote the fact that there is a proof of $ \Gamma \sststile{\mathbf{S}}{} \Delta $ in $ \mathsf{SC}^{?} $. \end{definition} \begin{lemma}[Height-Preserving Invertibility of $ {\vee}{\vdash} $]\label{lem:invert-LV} If $ \Gamma, A_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} A_n\sststile{\mathbf{S}}{} \Delta $ has a proof height $ \leq h $, then $ \Gamma', A_i \sststile{\mathbf{S'}}{} \Delta' $ for all $ i\in\{1,\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi,n\} $ and some $ \Gamma'\subseteq \Gamma, \Delta' \subseteq\Delta, \mathbf{S'}\subseteq\mathbf{S} $ have proofs of height $ \leq h $. \begin{proof} By induction on proof height. For the base case, $ \Gamma, A_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} A_n\sststile{\mathbf{S}}{} \Delta $ cannot be obtained directly from an axiom. For induction, assume that height-preserving inversion holds up to height $ h $ and that $ \Gamma, A_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} A_n\sststile{\mathbf{S}}{} \Delta $ has a proof of height $ h+1 $. From Definition \ref{def:proof}, it follows by this hypothesis that the premises employed to derive $ \Gamma, A_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} A_n\sststile{\mathbf{S}}{} \Delta $ are undefeated, and thus we need only show that there is a height-preserving derivation. There are two cases:\\ \textit{Case 1:} $ A_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} A_n $ is principal in the last rule. It must be obtained via $ \mathsf{LW} $ or $ {\vee}{\vdash} $. Assume the latter. So, $ \Gamma_1, A_1 \sststile{\mathbf{S}_1}{} \Delta_1 $ and $\Gamma_n, A_2{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} A_n \sststile{\mathbf{S}_n }{}\Delta_n $, where $ \mathbf{S}_{\mid n} = \mathbf{S}; \Gamma_{\mid n} = \Gamma;$ and $ \Delta_{\mid n} = \Delta$, have derivations $ \leq h$. The first of these sequents satisfies the claim's consequent, while the second is covered by our inductive hypothesis. If $ A_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} A_n $ is obtained by $ \mathsf{LW} $, then $ \Gamma \sststile{\mathbf{S}}{} \Delta $ has a derivation of height $ \leq h $. We apply $ \mathsf{LW} $ to obtain the sequents $ \Gamma, A_i \sststile{\mathbf{S}}{} \Delta $ for all $ i\in\{1,\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi,n\} $ with proof heights $ \leq h+1 $. \textit{Case 2:} $ A_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} A_n$ is not principal in the last rule. Then it has no more than two premises $ \Gamma'', A_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} A_n\sststile{\mathbf{S''}}{} \Delta'' $ and $ \Gamma''', A_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} A_n\sststile{\mathbf{S'''}}{} \Delta''' $ with proof heights $ \leq h $, so by inductive hypothesis $ \Gamma'', A_i \sststile{\mathbf{S''}}{} \Delta'' $ and $ \Gamma''', A_i \sststile{\mathbf{S'''}}{} \Delta''' $ for all $ i\in\{1,\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi,n\} $ have proofs of height $ \leq h $. \end{proof} \end{lemma} \begin{lemma}[Height-Preserving Invertibility of $ {\vdash}{\vee} $]\label{lem:invert-RV} If $ \Gamma\sststile{\mathbf{S}}{}\! A_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} A_n, \Delta $ has a proof height $ \leq h $, then $ \Gamma\sststile{\mathbf{S}}{} A_1,\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi, A_n, \Delta $ has a proof of height $ \leq h $. \begin{proof} By induction on proof height. Assume height-preserving inversion up to $ h $ and let $ \Gamma\sststile{\mathbf{S}}{} A_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} A_n, \Delta $ have a proof height $ h+1 $. Again, it follows by this hypothesis that the premises used to derive this sequent are undefeated. If $ A_1\vee\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\vee A_n $ is the principal formula in the last rule, then $\Gamma\sststile{\mathbf{S}}{} A_1,\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi, A_n, \Delta$ has a proof of $ \leq h $. If $ A_1\vee\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\vee A_n $ is not principal in the last rule, then the conclusion follows from no more than two premises $\Gamma''\sststile{\mathbf{S''}}{} A_1\vee\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\vee A_n, \Delta'' $ and $\Gamma'''\sststile{\mathbf{S'''}}{} A_1\vee\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\vee A_n, \Delta''' $ with proof heights $ \leq h $. By inductive hypothesis, it follows that $ \Gamma''\sststile{\mathbf{S''}}{} A_1,\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi, A_n, \Delta'' $ and $ \Gamma'''\sststile{\mathbf{S'''}}{} A_1,\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi, A_n, \Delta''' $ have proofs of height $ \leq h $. Apply the last rule to obtain $ \Gamma\sststile{\mathbf{S}}{} A_1,\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi, A_n, \Delta $ with a proof of height $ \leq h+1 $. \end{proof} \end{lemma} \begin{lemma}\label{lem:lero} $ \Gamma, ?[A_{\mid n}]\sststile{\mathbf{S}}{\mathsf{SC}^{?}} \varUpsilon \:\: $ iff $ \:\: \Gamma, A_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} A_n\sststile{\mathbf{S}}{\mathsf{SC}^{?}} \varUpsilon $. \begin{proof} ($ \Rightarrow $) By induction on proof height. For the base case, $ \Gamma, ?[A_{\mid n}]\sststile{\mathbf{S}}{} \varUpsilon $ is not an axiom as it contains at least one e-wff. For induction, assume our result holds for all proofs of height $ \leq h $ and that $ \Gamma, ?[A_{\mid n}]\sststile{\mathbf{S}}{} \varUpsilon $ has a proof of height $ h+1 $. There are two cases.\\ \textit{Case 1:} If $ ?[A_{\mid n}] $ is the principal formula, then it is obtained via $ \mathsf{LW} $ or $ {?}{\vdash_1} $, since the succedent is declarative. Assume it is obtained by the latter. It follows that the premises of $ {?}{\vdash_1} $ are provable, i.e. $ \Gamma_1, A_1 \sststile{\mathbf{T}_1}{\mathsf{SC}^{?}} \varUpsilon_1 \ldots \Gamma_n, A_n \sststile{\mathbf{T}_n }{\mathsf{SC}^{?}} \varUpsilon_n $, where $ \Gamma_{\mid n} = \Gamma;$ $ \varUpsilon_{\mid n} = \varUpsilon$ and $ \mathbf{T}_{\mid n}\cup[\mathbb{A}_{\mid n}] = \mathbf{S}$. Since none of these premises is defeated, there is no $ i\in\{1,\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi,n\} $ such that $A_i\in\bigcup\mathbf{T}_i $. Successive applications of $ {\vee}{\vdash} $ and appropriate applications of $ \mathsf{DE} $ to these sequents (e.g. to add $ [\mathbb{A}_{\mid n}] $ to the defeater set if it is not already included) yield $ \Gamma, A_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} A_n\sststile{\mathbf{S}}{} \varUpsilon $. Since, by hypothesis, $ \Gamma, ?[A_{\mid n}]\sststile{\mathbf{S}}{} \varUpsilon $ is undefeated and since it follows from Definition \ref{def:EClo} that $\mathcal{E}(\Gamma\,\cup\,?[A_{\mid n}])= \mathcal{E}(\Gamma)\,\cup\, A_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} A_n $, we know that $ \Gamma\,\cup\, \{A_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} A_n\}\succsim \mathbf{S}$. So, $ \Gamma, A_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} A_n\sststile{\mathbf{S}}{\mathsf{SC}^{?}} \varUpsilon $. If $ ?[A_{\mid n}] $ is introduced via $ \mathsf{LW} $, then $ \Gamma \sststile{\mathbf{S}}{\mathsf{SC}^{?}} \varUpsilon $. We apply $ \mathsf{LW} $ to obtain a proof of $ \Gamma, A_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} A_n\sststile{\mathbf{S}}{} \varUpsilon $. \\ \textit{Case 2:} If $ ?[A_{\mid n}] $ is not principal in the last rule, then it follows from no more than two premises $ \Gamma', ?[A_{\mid n}]\sststile{\mathbf{S'}}{} \varUpsilon' $ and $ \Gamma'', ?[A_{\mid n}]\sststile{\mathbf{S''}}{} \varUpsilon'' $ with proof heights $ \leq h $. So by inductive hypothesis, $ \Gamma', A_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} A_n\sststile{\mathbf{S'}}{\mathsf{SC}^{?}} \varUpsilon' $ and $ \Gamma'', A_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} A_n\sststile{\mathbf{S''}}{\mathsf{SC}^{?}} \varUpsilon'' $. We apply the last rule to obtain a proof of $ \Gamma, A_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} A_n\sststile{\mathbf{S}}{} \varUpsilon $. ($ \Leftarrow $) Again, by induction on proof height. From Lemma \ref{lem:invert-LV}, we know that $ \Gamma', A_i \sststile{\mathbf{S'}}{\mathsf{SC}^{?}} \varUpsilon' $ for all $ i\in\{1,\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi,n\} $ and some $ \Gamma'\subseteq \Gamma, \varUpsilon' \subseteq\varUpsilon, \mathbf{S'}\subseteq\mathbf{S}$ have proof heights $ \leq h $. We apply $ {?}{\vdash_1} $ to these sequents to obtain a proof of $ \Gamma, ?[A_{\mid n}]\sststile{\mathbf{S}}{} \varUpsilon $. \end{proof} \end{lemma} \begin{lemma}\label{lem:rero $ X\sststile{\mathbf{S}}{\mathsf{SC}^{?}} ?[B_{\mid m}], \Delta \:\: $ iff $ \:\: X\sststile{\mathbf{S}}{\mathsf{SC}^{?}} B_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} B_m, \Delta $. \begin{proof} ($ \Rightarrow $) By induction on proof height. In the base case, $ X\sststile{\mathbf{S}}{} ?[B_{\mid m}], \Delta $ is not an axiom. For induction, we assume that the result holds for all proofs of height $ \leq h $ and that $ X\sststile{\mathbf{S}}{} ?[B_{\mid m}], \Delta $ has a proof of height $ h+1 $. Again there are two cases.\\ \textit{Case 1:} If $ ?[B_{\mid m}] $ is the principal formula, then it must be obtained via $ \mathsf{RW} $ or $ {\vdash}{?_1} $, since the antecedent is declarative. If it follows via the latter, the premise is provable, so $ X\sststile{\mathbf{T}}{\mathsf{SC}^{?}} B_1,\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi,B_m, \Delta $ where $ \mathbf{T}\cup[\mathbb{B}_{\mid m}]=\mathbf{S} $. We apply $ {\vdash}{\vee} $, followed, if needed, by $ \mathsf{DE} $ to add $[\mathbb{B}_{\mid m}] $ to $ \mathbf{T} $, and thus obtain a proof of $ X\sststile{\mathbf{S}}{\mathsf{SC}^{?}} B_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} B_m, \Delta $. If $ ?[B_{\mid m}] $ is introduced via $ \mathsf{RW} $, then $ X\sststile{\mathbf{S}}{\mathsf{SC}^{?}} \Delta $. Apply $ \mathsf{RW} $ to weaken the succedent by $ B_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} B_m $ and we have the desired proof.\\ \textit{Case 2:} If $ ?[B_{\mid m}] $ is the not principal in the last rule, then the conclusion follows from no more than two premises $X'\sststile{\mathbf{S'}}{} ?[B_{\mid m}], \Delta' $ and $X''\sststile{\mathbf{S''}}{} ?[B_{\mid m}], \Delta'' $ with proof heights $ \leq h $. So by inductive hypothesis $X'\sststile{\mathbf{S'}}{\mathsf{SC}^{?}} B_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} B_m, \Delta' $ and $X''\sststile{\mathbf{S''}}{\mathsf{SC}^{?}} B_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} B_m, \Delta'' $. We apply the last rule to obtain $ X\sststile{\mathbf{S}}{\mathsf{SC}^{?}} B_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} B_m, \Delta $. ($ \Leftarrow $) Again, by induction on proof height. From Lemma \ref{lem:invert-RV}, we know that $ \Gamma\sststile{\mathbf{S}}{\mathsf{SC}^{?}} B_1,\ldots, B_m, \Delta $ has a proof of height $ \leq h $. We apply $ {\vdash}{?_1} $ to obtain the desired sequent. \end{proof} \end{lemma} \begin{lemma}\label{lem:bero} $ X, ?[A_{\mid n}]\sststile{\mathbf{S}}{\mathsf{SC}^{?}} ?[B_{\mid m}], \varUpsilon \:$ iff\\ $(i)\: X, A_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} A_n\sststile{\mathbf{S}}{\mathsf{SC}^{?}} B_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} B_m, \varUpsilon $; and\\ (ii)\: for all $ j\in\{1,\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi,m\} $, there exists $ k\in\{1,\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi,n\} $ and exists $\mathbf{T} \subset \mathbf{S}$ such that $X, B_j \sststile{\mathbf{T}}{\mathsf{SC}^{?}} A_k , \varUpsilon $.\\ \begin{proof} $ (\Rightarrow) $ By induction on proof height. There are two cases.\\ \textit{Case 1:} Either $ ?[A_{\mid n}]$ or $ ?[B_{\mid m}]$ is principal in the last rule. There are three sub-cases.\\ (1a.) Suppose that the last rule applied is $ {?}{\vdash_2} $ and $ ?[A_{\mid n}]$ is principal. So, there are proofs of the left-hand set of premises in $ {?}{\vdash_2} $, i.e. sequents of the form $ X_i, A_i\sststile{\mathbf{S}_i}{} ?[B_{\mid m}], \varUpsilon_i $ for all $ i \in \{1,\ldots,n\} $. Iterative applications of $ {\vee}{\vdash} $ yield $ X', A_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} A_n\sststile{\mathbf{S'}}{} ?[B_{\mid m}], \varUpsilon' $ where $ X'\subseteq X$, $\varUpsilon' \subseteq\varUpsilon$ and $ \mathbf{S'}\subseteq\mathbf{S}$. From the appropriate applications of $ \mathsf{LW}, \mathsf{RW} $ and $ \mathsf{DE} $ we obtain $ X, A_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} A_n\sststile{\mathbf{S}}{} ?[B_{\mid m}], \varUpsilon$. From Lemma \ref{lem:rero}, it follows that $ X, A_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} A_n\sststile{\mathbf{S}}{\mathsf{SC}^{?}} B_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} B_m, \varUpsilon$, and condition (i) is satisfied. Similarly, it follows that there are proofs of the right-hand set of premises in $ {?}{\vdash_2} $, i.e. for all $ j\in\{1,\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi,m\}$, there exists $ k\in\{1,\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi,n\} $, $ X'\subseteq X, \varUpsilon'\subseteq\varUpsilon, $ and $ \mathbf{T}_{j}\subset\mathbf{S}$ such that $ X', B_j\sststile{\mathbf{T}_j}{} A_k, \varUpsilon'$. Note that since none of these premises is defeated, $ A_k\not\in\bigcup\mathbf{T}_j $. As $ \{A_k\}\in[\mathbb{A}_{\mid n}] $ and $[\mathbb{A}_{\mid n}]\subseteq\mathbf{S}$, the defeater sets of these sequents must be \textit{proper} subsets of the end-sequent's defeater set, i.e. for all $ j\in\{1,\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi,m\}$, $\mathbf{T}_j\subset\mathbf{S}$. By judicious applications of $ \mathsf{LW}, \mathsf{RW}, $ and $ \mathsf{DE} $ we arrive at proofs of the sequents $ X, B_j\sststile{\mathbf{T}}{} A_k, \varUpsilon$ for all $ j\in\{1,\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi,m\}$ and at least one $ k\in\{1,\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi,n\} $, where $ \mathbf{T} $---for reasons just mentioned---is some proper subset of $ \mathbf{S}$. Thus, condition (ii) is satisfied.\\ (1b.) Suppose that the last rule applied is ${\vdash}{?_2} $ and $ ?[B_{\mid m}]$ is principal. It follows that the left-hand sequent of that rule, $ X', ?[A_{\mid n}]\sststile{\mathbf{S}'}{} B_1,\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi, B_m, \varUpsilon' $ is provable, where $ X'\subseteq X$, $\varUpsilon' \subseteq\varUpsilon$ and $ \mathbf{S'}\subseteq\mathbf{S} $. We apply $ {\vdash}{\vee} $ to obtain $ X', ?[A_{\mid n}]\sststile{\mathbf{S}'}{} B_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} B_m, \varUpsilon' $ and from Lemma \ref{lem:lero} we have $ X', A_1\vee\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\vee A_n\sststile{\mathbf{S}'}{} B_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} B_m, \varUpsilon' $. Apply $ \mathsf{LW}, \mathsf{RW}, $ and $ \mathsf{DE} $ as needed to obtain $ X, A_1\vee\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\vee A_n\sststile{\mathbf{S}}{} B_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} B_m, \varUpsilon $, which satisfies condition (i). The right-hand set of premises in ${\vdash}{?_2} $ ensure that condition (ii) is satisfied in the manner of the first sub-case.\\ (1c.) If $ ?[A_{\mid n}]$ or $ ?[B_{\mid m}]$ is principle and the last rule is weakening, then the result follows by inductive hypothesis in the manner of Lemmas \ref{lem:lero} and \ref{lem:rero}.\\ \textit{Case 2:} Neither $ ?[A_{\mid n}]$ nor $ ?[B_{\mid m}]$ is principal in the last rule. So $ X, ?[A_{\mid n}]\sststile{\mathbf{S}}{} ?[B_{\mid m}], \varUpsilon $ follows from one or more premises covered by the inductive hypothesis. ($ \Leftarrow $) By induction on proof height of sequents in conditions (i) and (ii). Given condition (i), it follows from Lemma \ref{lem:invert-RV} that $ X, A_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} A_n \sststile{\mathbf{S}}{\mathsf{SC}^{?}} B_1,\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi, B_m,\Delta $ and from Lemma \ref{lem:lero} we obtain $ X, ?[A_{\mid n}] \sststile{\mathbf{S}}{} B_1,\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi, B_m,\Delta $. Condition (ii) then gives us the premises needed to apply $ {\vdash}{?_2} $, which yields $ X, ?[A_{\mid n}]\sststile{\mathbf{S}}{} ?[B_{\mid m}], \varUpsilon $. \end{proof} \end{lemma} \begin{corollary}\label{coro:declaredseq} If $\Gamma\sststile{\mathbf{S}}{\mathsf{SC}^{?}}\Delta $,\: then\:\: $ \mathcal{E}(\Gamma)\sststile{\mathbf{S}}{\mathsf{SC}^{?}}\mathcal{E}(\Delta) $. \begin{proof} Let $ \mathsf{E}(\cdot) $ be a function $ \mathcal{P}(\mathcal{L})\mapsto \mathbb{N} $ that returns the number of e-wffs in a set of formulas. We proceed by induction on the number of e-wffs in the left-hand sequent, i.e. $ \mathsf{E}(\Gamma\cup\Delta) $. For our base case, $ \mathsf{E}(\Gamma\cup\Delta) = 0$. So $ \Gamma\sststile{\mathbf{S}}{}\Delta $ contains no e-wffs and thus satisfies the conditional. For induction, assume our result holds for all sequents such that $ \mathsf{E}(\Gamma\cup\Delta) \leq n $. Now assume that $ \Gamma\sststile{\mathbf{S}}{}\Delta $ is such that $\mathsf{E}(\Gamma\cup\Delta) = n+1$. It follows from our inductive hypothesis that $ X\sststile{\mathbf{S}}{\mathsf{SC}^{?} }\varUpsilon $ where either $ X = \mathcal{E}(\Gamma\backslash\{Q\})$ or $\varUpsilon = \mathcal{E}(\Delta\backslash\{Q\})$ for some e-wff $ Q \in\Gamma\cup\Delta $. Thus we need only show that $ X\cup\mathcal{E}(\{Q\})\sststile{\mathbf{S}}{\mathsf{SC}^{?}}\varUpsilon $ and $ X\sststile{\mathbf{S}}{\mathsf{SC}^{?}}\varUpsilon\cup\mathcal{E}(\{Q\})$ and these follow from Lemmas \ref{lem:lero} and \ref{lem:rero}, respectively. \end{proof} \end{corollary} \begin{corollary}\label{coro:conversext} $\mathsf{SC}^{?}$ is a conservative extension of $\mathsf{SC}^{\mathbf{S}}$, that is, any sequent composed solely of d-wffs (i.e. formulas of $ \mathcal{L}_d $) that is provable in $\mathsf{SC}^{?}$is provable in $\mathsf{SC}^{\mathbf{S}}$ and vice versa. \end{corollary} Corollary \ref{coro:declaredseq} tells us that the declarativized version of any provable erotetic sequent (i.e. a sequent containing at least one e-wff) is also provable. This is not particularly surprising given the tight relationship between classical disjunctions and e-wffs. From the adequacy of the declarative calculus $ \mathsf{SC}^\mathbf{S} $ for CPL (i.e. Lemma \ref{lem:SCS=CPL}), it follows that two classes of defeasible sequents in $ \mathsf{SC}^{?}$ are sound and complete with respect to evocation (Definition \ref{def:erotetic_evocation}) and strong regular e-implication (Definition \ref{def:sr_e-imp}). \begin{theorem}\label{thrm:S+C_EE} $ X \rightarrowtail ?[A_{\mid n}]\: $ iff $\:X\sststile{\mathbf{S}\cup [\mathbb{A}_{\mid n}]}{\mathsf{SC}^{?}} \: ?[A_{\mid n}] $ for some (possibly empty) $ \mathbf{S}$. \begin{proof} ($\Rightarrow$) From Lemma \ref{lem:Sound&CompleteSCs}, the first condition in Definition \ref{def:erotetic_evocation} implies that $ X\sststile{\mathbf{S}}{\mathsf{SC}^{?}} A_1 \vee\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\vee A_n $ for some (possibly empty) $ \mathbf{S}$ and the second condition implies that $ X\succsim [\mathbb{A}_{\mid n}]$. Apply $ \mathsf{DE} $ to $ X\sststile{\mathbf{S}}{} A_1 \vee\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\vee A_n $ to obtain a proof of $ X\sststile{\mathbf{S}\cup[\mathbb{A}_{\mid n}]}{} A_1 \vee\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\vee A_n $. The result then follows by Lemma \ref{lem:rero}.\\ ($ \Leftarrow $) From Lemma \ref{lem:rero}, it follows by hypothesis that $ X\sststile{\mathbf{S}\cup[\mathbb{A}_{\mid n}]}{\mathsf{SC}^{?}} A_1 \vee\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\vee A_n $. Thus, $ X \succsim [\mathbb{A}_{\mid n}]$. By Definitions \ref{def:defeat} and \ref{def:compat_in_SC?} and Lemma \ref{lem:Sound&CompleteSCs}, it follows that the two conditions on erotetic evocation (Definition \ref{def:erotetic_evocation}) are satisfied. \end{proof} \end{theorem} \begin{theorem}\label{thrm:S+C_SR-EI} $X\mid\: ?[ A_{\mid n}] \twoheadrightarrow \:?[ B_{\mid m}]$ \:iff\: $ X, ?[ A_{\mid n}]\sststile{\mathbf{S}\cup [\mathbb{A}_{\mid n}]}{\mathsf{SC}^{?}} \: ?[ B_{\mid m}]$ for some (possibly empty) $ \mathbf{S}$. \begin{proof} ($\Rightarrow$) By Definition \ref{def:sr_e-imp} and Lemma \ref{lem:Sound&CompleteSCs}, it follows that (i) $ X, A_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} A_n\sststile{\mathbf{S}\cup[\mathbb{A}_{\mid n}]}{\mathsf{SC}^{?}} B_1\vee\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\vee B_m $, (since the third condition in Definition \ref{def:sr_e-imp} entails that $ X\succsim [\mathbb{A}_{\mid n}]$) and that (ii) for all $ j\in\{1,\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi,m\} $, there exists $ k\in\{1,\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi,n\} $ and exists $ \mathbf{T}\subset\mathbf{S}\cup[\mathbb{A}_{\mid n}] $ such that $ X, B_j \sststile{\mathbf{T}}{\mathsf{SC}^{?}} A_k $. The result is then obtained by Lemma \ref{lem:bero}.\\ ($ \Leftarrow $) From Lemma \ref{lem:bero}, it follows that (i) $ X, A_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} A_n\sststile{\mathbf{S}\cup[\mathbb{A}_{\mid n}]}{\mathsf{SC}^{?}} B_1{\vee}\!\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi\!{\vee} B_m $ and that (ii) for all $ j\in\{1,\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi,m\} $, there exists $ k\in\{1,\ifmmode\mathinner{\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em\ldotp\kern-0.1em}\else.\kern-0.13em.\kern-0.13em.\fi,n\} $ and exists $ \mathbf{T}\subset\mathbf{S}\cup[\mathbb{A}_{\mid n}] $ such that $ X, B_j \sststile{\mathbf{T}}{\mathsf{SC}^{?}} A_k $. From Definition \ref{def:sr_e-imp} and Lemma \ref{lem:Sound&CompleteSCs} we know that the three conditions on e$_{sr}$-implication (Definition \ref{def:sr_e-imp}) are satisfied. \end{proof} \end{theorem} \begin{theorem}\label{thrm:decidable} $ \mathsf{SC}^?$ is decidable. \begin{proof} We restrict our attention to derivations in $ \mathsf{SC}^{?}$ in which no sequent appears twice in a branch, following the usual reduction to \textit{concise} proofs. When confronted with an end-sequent $ \Gamma\sststile{\mathbf{S}}{}\Delta $, we must first determine whether it is defeated. If it is, then there is no proof. If it is undefeated, then we proceed in the manner of the standard \textit{proof search algorithm} for sequent calculi, i.e. we consider all the possible inference rules that could have $ \Gamma\sststile{\mathbf{S}}{}\Delta $ as a conclusion and construct a number of trees, one for each distinct possibility, writing down the premises of such rules above it. Matters are slightly complicated by the presence of the $ \mathsf{DE} $ rule. However, since the defeater sets of any sequent are finite, we know that there is an upper bound to the number of derivations for any end-sequent containing a nonempty defeater set. We then repeat this process for the premises of each successive rule, at each point checking to see whether the premises are defeated. If a premise is defeated in a tree, then, following Definition \ref{def:proof}, it is not a possible proof, and thus we turn to the remaining trees. We proceed in this fashion until we have trees with no defeated sequents whose leaves are axioms. \end{proof} \end{theorem} In order to reduce the length of proofs---a desideratum for any implementation of the system---we can add a \textit{cut} rule to the calculus, i.e: $$\begin{prooftree}[template = \small$\inserttext$] \Hypo{\Gamma\sststile{\mathbf{S}}{}F,\Delta} \Hypo{\Gamma', F\sststile{\mathbf{T}}{}\Delta'} \Infer2[$cut$]{ \Gamma',\Gamma\sststile{\mathbf{S}\,\cup\,\mathbf{T}}{}\Delta,\Delta'} \end{prooftree}$$ \noindent$ \mathsf{SC^?}$ is sound and complete for CPL and, as noted above, the relation of e$_{sr}$-implication is transitive, so this rule is admissible when the cut formula is either a d-wff or an e-wff. \section{Example}\label{sec:ex} Assume that an agent, $ \alpha $ is assigned the task of determining which of the following formulas is true: $ p, q $. Assume further, that $ \alpha $ has learned that $ \neg s \vee p $ and $s\vee q $ but has yet to obtain an answer to its principal question. Additionally, $ \alpha $'s knowledge base includes the information about defeaters. Writing `$ \rightsquigarrow $' for `defeats,' the information is as follows: $ \{r\}\rightsquigarrow s $, $ \{t\}\rightsquigarrow p $ and $ \{u, v\} \rightsquigarrow q $. Now, what question(s) should $ \alpha $ ask? There are various algorithms or heuristics the agent might operate with that determine or suggest ways of using $\mathsf{SC}^{?}$ to arrive at strategies for answering principal questions via sub-questions. Formulating such rules is an interesting exercise in its own right, but suppose that $ \alpha $ is provided with the following. \textbf{Erotetic Strategy:} For a question, $ Q $, and a set of facts, $ X $, determine whether you are licensed to inquire into $ ? A $ for any formula, $ A $, that occurs as a subformula in member of $ X $ but not in a member of $ dQ $, i.e. find a question, distinct from $ Q $, that is e$_{rs}$-implied by $ Q\cup X $. \textbf{Strategy Implementation in $ \mathsf{SC}^? $:} Try to prove $ X, Q \sststile{\mathbf{S}\cup\,[d\mathbb{Q}]}{}?A $ such that $ A \in \mathsf{Subform}(X)\backslash\mathsf{Subform}(dQ) $. The following proof realizes this strategy. $$\begin{prooftree}[template = \scriptsize$\inserttext$, separation = .5em] \Hypo{} \Infer1[${\scriptstyle ax_3}$]{ \quad\sststile{\{\{r\}\}}{} s, \neg s} \Infer1[$ {\scriptstyle \mathsf{LW}}$]{ ?\{p, q\}\sststile{\{\{r\}\}}{} s, \neg s } \Hypo{} \Infer1[$ {\scriptstyle ax_4}$]{ s, \neg s\sststile{\emptyset}{} \quad } \Hypo{} \Infer1[$ {\scriptstyle ax_1}$]{ p\sststile{\{\{t\}\}}{} p } \Infer2[$ {\scriptstyle {\vee}{\vdash}}$]{ \neg s \vee p, s \sststile{\{\{t\}\}}{} p } \Hypo{} \Infer1[$ {\scriptstyle ax_4}$]{ s, \neg s\sststile{\emptyset}{} \quad } \Hypo{} \Infer1[$ {\scriptstyle ax_1}$]{ q\sststile{\{\{u, v\}\}}{} q } \Infer2[$ {\scriptstyle {\vee}{\vdash}}$]{ s \vee q, \neg s \sststile{\{\{u, v\}\}}{} q } \Infer3[$\vdash?_{\scriptscriptstyle 2}$]{?\{p, q\}, \neg s \vee p, s\vee q\sststile{\{\{r\},\{t\},\{u, v\}, \{p\}, \{q\}\}}{}\: ?\{s, \neg s\}} \end{prooftree}$$ With the derivation of the end-sequent above, $ \alpha $ now has an erotetic inference that licenses it to inquire into $?\{s, \neg s\}$ as a means of answering $ ?\{p, q\} $. There are a few ways to conceive of $ \alpha $'s use of this inference. Perhaps the simplest is that once its derivation is obtained, $ \alpha $ transitions from its inference mode to data-collection, and back again, adding each new piece of information to the sequent's antecedent via $ \mathsf{LW} $ until the sequent is defeated. Such defeat then represents the fact that either $ \alpha $'s initial question has been answered (i.e. if the new antecedent implies $ p $ or $q$) or that exceptions to the inference's warrant have been found (i.e. if the new antecedent implies $\{r\},\{t\},$ or $\{u, v\}$). \section{Conclusion}\label{sec:concl} The calculus $ \mathsf{SC}^? $ satisfies our desiderata of an informally adequate and formally well-behaved calculus for defeasible erotetic inferences. The calculus' decidability makes it suitable for automated reasoning systems, such as ATPs discussed in the introduction. We think the system lays the ground for future investigations into the nature of erotetic defeasibility and the implementation of zetetically rational agents. There are several ways to augment or otherwise alter $\mathsf{SC}^{?}$ that might capture other types of erotetic inference or features of erotetic defeat. For instance, the defeater set mechanism is rather coarse-grained insofar as it assimilates information that undermines propositional inferences with that which undermines erotetic inferences, i.e. answers. A simple way to distinguish and track changes in these two data sets would be to adorn the turnstile with two defeater sets, one that retains the sets of initial sequents, and one that only encodes additions made via one of the e-wff rules. Defeater sets would still be assembled in the binary rules via set-union. Another way in which $\mathsf{SC}^{?}$ might be fruitfully developed would be to extend it in a such a way as to capture the general relation of erotetic implication, where implied questions need only entail proper subsets of answers to the implying question. To do so, we might let $ \Theta_i, \Theta_j $ stand for nonempty proper subsets of $ [ A_{\mid n}] $, i.e., $ \Theta_i, \Theta_j \in \mathcal{P}([ A_{\mid n}])/\{\emptyset, [ A_{\mid n}]\} $. By replacing $ A_i, A_j $ in $ {\vdash}{?_2} $ and $ {?}{\vdash_2} $ with $ \Theta_i, \Theta_j$, we obtain a rule that yields sequents that are sound and complete with respect to general erotetic implication. It would be quite interesting to see how $\mathsf{SC}^{?}$ compares to IEL's \textit{erotetic search scenarios}, which model the behavior of interrogators who answer a principle question by seeking out more easily or economically obtained answers to subordinate questions. Since strategies for resolving these scenarios are based on e-implicative relations, there are provable sequents in $\mathsf{SC}^{?}$ corresponding to each successful erotetic move. As algorithms for generating these scenarios have already been implemented \citep{Chlebowski2017,Bolotov2006,Leszczyska-Jasion2013,Lupkowski2015}, there is reason to think that implementing $\mathsf{SC}^{?}$ is both feasible and complementary of the systems for erotetic search scenarios. This would be one of the many ways to advance the study and design of zetetic agents. \renewcommand{\bibfont}{\small} \setlength{\bibsep}{6pt}
{'timestamp': '2020-10-13T02:24:05', 'yymm': '2010', 'arxiv_id': '2010.05293', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05293'}
arxiv
\section{Introduction} \label{sect:intro} We are interested in the relationship between a response variable $Y$ and a covariate $X$ governed by the generative model \begin{equation} \label{eq:model} Y | X = x \sim f \big(\cdot | \lambda(w_0, x) \big), \end{equation} where $\lambda$ is a pre-determined function that maps the weight $w_0$ and the covariate $X$ to the parameter of the conditional distribution of $Y$ given $X$. The weight $w_{0}$ is unknown and is the main quantity of interest to be estimated. Throughout this paper, we assume that the distribution $f$ belongs to the exponential family of distributions. Given a ground measure $\nu$ on $\mathcal Y$, the exponential family is characterized by the density function \[ f(y | \theta) = h(y) \exp\left( \inner{\theta}{T(y)} - \Psi(\theta)\right) \] with respect to $\nu$, where $\inner{\cdot}{\cdot}$ denotes the inner product, $\theta$ is the natural parameters, $\Psi$ is the log-partition function and $T$ is the sufficient statistics. The space of natural parameters is denoted by $\Theta = \left\{\theta:\int h(y)\exp(\inner{\theta}{T(y)})<\infty\right\} \subseteq \mathbb{R}^p$. We assume that the exponential family of distributions is regular, hence $\Theta$ is an open set, and $T_1(y),\ldots,T_p(y)$ are affinely independent~\cite[Chapter~8]{ref:barndorff2014introductory}. The generative setting~\eqref{eq:model} encapsulates numerous models which are suitable for regression and classification~\cite{ref:dobson2018introduction}. It ranges from logistic regression for classification~\cite{ref:hosmer2013applied}, Poisson counting regression~\cite{ref:hilbe2014poisson}, log-linear models~\cite{ref:christensen1990log} to numerous other generalized linear models~\cite{ref:dobson2018introduction}. Given data $\{(\widehat x_i, \widehat y_i)\}_{i = 1, \ldots, N}$ which are assumed to be independently and identically distributed (i.i.d.) following the generative model~\eqref{eq:model}, we want to estimate the true value of $w_0$ that dictates~\eqref{eq:model}. If we use $\wh \PP^{\text{emp}} = N^{-1} \sum_{i=1}^N \delta_{(\widehat x_i, \widehat y_i)}$ to denote the empirical distribution supported on the training data, and define $\ell_{\lambda}$ as the log-loss function with the parameter mapping $\lambda$ \begin{equation} \label{eq:logloss-def} \ell_\lambda(x, y, w) = \Psi( \lambda(w, x)) - \inner{T(y)}{\lambda(w, x)}, \end{equation} then the maximum likelihood estimation (MLE) produces an estimate $w_{MLE}$ by solving the following two equivalent optimization problems \begin{subequations} \begin{align} w_{MLE} &= \arg \min\limits_{w \in \mathcal W} \textstyle\sum_{i=1}^{N} \frac{1}{N} \left( \Psi( \lambda(w, \widehat x_i)) - \inner{T(\widehat y_i)}{ \lambda(w, \widehat x_i)} \right) \label{eq:MLE}\\ &= \arg \min\limits_{w \in \mathcal W} ~\mathds{E}_{\wh \PP^{\text{emp}}}[ \ell_\lambda(X, Y, w)]. \label{eq:MLE2} \end{align} \end{subequations} The popularity of MLE can be attributed to its consistency, asymptotic normality and efficiency~\cite[Section~5]{ref:vandervaart2000asymptotic}. Unfortunately, this estimator exhibits several drawbacks in the finite sample regime, or when the data carry high noise and may be corrupted. For example, the ML estimator for the Gaussian model recovers the sample mean, which is notoriously susceptible to outliers~\cite{ref:rousseeuw2011robust}. The MLE for multinomial logistic regression yields over-fitted models for small and medium sized data~\cite{ref:dejong2019sample}. Various strategies can be utilized to counter these adverse effects of the MLE in the limited data regime. The most common approach is to add a convex penalty term such as a 1-norm or 2-norm of $w$ into the objective function of problem~\eqref{eq:MLE} to obtain different regularization effects, see \cite{ref:andrew2004feature, ref:su2006efficient} for regularized logistic regression. However, this approach relies on strong prior assumptions, such as the sparsity of $w_0$ for the 1-norm regularization, which may rarely hold in reality. Recently, dropout training has been used to prevent overfit and improve the generalization of the MLE~\cite{ref:srivastava2014dropout,ref:wager2013dropout,ref:wang2013fast}. Specific instances of dropout have been shown to be equivalent to a 2-norm regularization upon a suitable transformation of the inputs~\cite[Section~4]{ref:wager2013dropout}. Another popular strategy to regularize problem~\eqref{eq:MLE} is by reweighting the samples instead of using a constant weight $1/N$ when calculating the loss. This approach is most popular in the name of weighted least-squares, which is a special instance of MLE problem under the Gaussian assumption with heteroscedastic noises. Distributionally robust optimization (DRO) is an emerging scheme aiming to improve the out-of-sample performance of the statistical estimator, whereby the objective function of problem~\eqref{eq:MLE2} is minimized with respect to the most adverse distribution $\mbb Q$ in some ambiguity set. The DRO framework has produced many interesting regularization effects. If the ambiguity set is defined using the Kullback-Leibler (KL) divergence, then we can recover an adversarial reweighting scheme~\cite{li2019comparing,ref:bertsimas2018datadriven}, a variance regularization~\cite{ref:namkoong2016stochastic, ref:duchi2016statistics}, and adaptive gradient boosting~\cite{ref:blanchet2019a}. DRO models using KL divergence is also gaining recent attraction in many machine learning learning tasks~\cite{ref:faury2020distributionally, ref:si2020distributionally}. Another popular choice is the Wasserstein distance function which has been shown to have strong connections to regularization~\cite{ref:shafieezadeh2019regularization, ref:kuhn2019wasserstein}, and has been used in training robust logistic regression classifiers~\cite{ref:shafieezadeh2015distributionally, ref:blanchet2018optimal}. Alternatively, the robust statistics literature also consider the robustification of the MLE problem, for example, to estimate a robust location parameter~\cite{ref:huber1964robust} Existing efforts using DRO typically ignore, or have serious difficulties in exploiting, the available information regarding the generative model~\eqref{eq:model}. While existing approaches using the Kullback-Leibler ball around the empirical distribution completely ignore the possibility of perturbing the conditional distribution, the Wasserstein approach faces the challenge of elicitating a sensible ground metric on the response variables. For a concrete example, if we consider the Poisson regression application, then $Y$ admits values in the space of natural numbers $\mathbb N$, and deriving a global metric on $\mathbb N$ that carries meaningful local information is nearly impossible because one unit of perturbation of an observation with $\widehat y_i = 1$ does not carry the same amount of information as perturbing $\widehat y_i = 1000$. The drawbacks of the existing methods behoove us to investigate a novel DRO approach that can incorporate the available information on the generative model in a systematic way. \textbf{Contributions.} We propose the following \textit{distributionally robust MLE problem} \begin{equation} \label{eq:dro} \min\limits_{w \in \mathcal W} \max\limits_{\mbb Q \in \mathbb B(\wh \PP)} \mathds{E}_{\mbb Q} \big[ \ell_\lambda(X, Y, w )\big], \end{equation} which is a robustification of the MLE problem~\eqref{eq:MLE2} for generative models governed by an exponential family of distributions. The novelty in our approach can be summarized as follows. \begin{itemize}[leftmargin = 5mm] \item We advocate a new nominal distribution which is calibrated to reflect the available parametric information, and introduce a Kullback-Leibler ambiguity set that allows perturbations on both the marginal distribution of the covariate and the conditional distributions of the response. \item We show that the min-max estimation problem~\eqref{eq:dro} can be reformulated as a single finite-dimensional minimization problem. Moreover, this reformulation is a convex optimization problem in broadly applicable settings, including the training of many generalized linear models. \item We demonstrate that our approach can recover the adversarial reweighting scheme as a special case, and it is connected to the variance regularization surrogate. Further, we prove that our estimator is consistent and provide insights on the practical tuning of the parameters of the ambiguity set. We also shed light on the most adverse distribution in the ambiguity set that incurs the extremal loss for any estimate of the statistician. \end{itemize} \textbf{Technical notations.} The variables $(X, Y)$ admit values in $\mathcal X \times \mathcal Y \subseteq \mathbb{R}^n \times \mathbb{R}^m$, and $\mathcal W$ is a finite-dimensional set. The mapping $\lambda: \mathcal W \times \mathcal X \to \Theta \subseteq \mathbb{R}^p$ is jointly continuous, and $\inner{\cdot}{\cdot}$ denotes the inner product in $\mathbb{R}^p$. For any set $\mathcal S$, $\mathcal M(\mathcal S)$ is the space of all probability measures with support on $\mathcal S$. We use $\xrightarrow{p.}$ to denote convergence in probability, and $\xrightarrow{d.}$ to denote convergence in distribution. All proofs are relegated to the appendix. \section{Distributionally Robust Estimation with a Parametric Ambiguity Set} \label{sect:ambiguity-set} We delineate in this section the ingredients of our distributionally robust MLE using parametric ambiguity set. Since the log-loss function is pre-determined, we focus solely on eliciting a nominal probability measure and the neighborhood surrounding it, which will serve as the ambiguity set. While the typical empirical measure $\wh \PP^{\text{emp}}$ may appear at first as an attractive option for the nominal measure, $\wh \PP^{\text{emp}}$ does not reflect the parametric nature of the conditional measure of $Y$ given $X$. Consequently, to robustify the MLE model, we need a novel construction of the nominal distribution~ $\wh \PP$. Before proceeding, we assume w.l.o.g. that the dataset $\{ (\widehat x_i, \widehat y_i)\}_{i=1, \ldots, N}$ consists of $C \le N$ distinct observations of $X$, each value is denoted by $\widehat x_c$ for $c = 1, \ldots, C$, and the number of observations with the same covariate value $\widehat x_c$ is denoted by $N_c$. This regrouping of the data by $\widehat x_c$ typically enhances the statistical power of estimating the distribution conditional on the event $X = \widehat x_c$. We posit the following \emph{parametric nominal distribution} $\wh \PP \in \mathcal M(\mathcal X \times \mathcal Y)$. This distribution is fully characterized by $(p+1)C$ parameters: a probability vector $\widehat p\in\mathbb{R}_+^C$ whose elements sum up to 1 and a vector of nominal natural parameters $\widehat \theta \in \Theta^C \subseteq (\mathbb{R}^p)^C$. Mathematically, $\wh \PP$ satisfies \begin{equation} \label{eq:nominal} \left\{ \begin{array}{l} \wh \PP (\{\widehat x_c\} \times A) = \wh \PP_X(\{\widehat x_c\}) \wh \PP_{Y|\widehat x_c}(A) \qquad \forall \widehat x_c, \forall A \subseteq \mathcal Y \text{ measurable} \\ \wh \PP_X = \sum_{c=1}^C \widehat p_c \delta_{\widehat x_c}, \quad \wh \PP_{Y|\widehat x_c} \sim f(\cdot | \widehat \theta_c) \; \forall c. \end{array} \right. \end{equation} The first equation indicates that the nominal measure $\wh \PP$ can be decomposed into a marginal distribution of the covariates $X$ and a collection of conditional measures of $Y$ given $X$ using the definition of the conditional probability measure ~\cite[Theorem~9.2.2]{ref:stroock2011probability}. The second line stipulates that the nominal marginal distribution $\wh \PP_X$ of the covariates is a discrete distribution supported on $\widehat x_c$, $c = 1, \ldots, C$. Moreover, for each $c$, the nominal conditional distribution of $Y$ given $X = \widehat x_c$ is a distribution in the exponential family with parameter $\widehat \theta_c$. Notice that the form of~$\wh \PP$ in~\eqref{eq:nominal} is chosen to facilitate the injection of parametric information $\widehat \theta_c$ into the nominal distribution, and it is also necessary to tie $\wh \PP$ to the MLE problem using the following notion of MLE-compatibility. \begin{comment} We posit the following parametric nominal distribution $\wh \PP \in \mathcal M(\mathcal X \times \mathcal Y)$ which can be written as \begin{equation} \label{eq:nominal} \left\{ \begin{array}{l} \wh \PP (\{\widehat x_c\} \times A) = \wh \PP_X(\{\widehat x_c\}) \wh \PP_{Y|\widehat x_c}(A) \qquad \forall \widehat x_c, \forall A \subseteq \mathcal Y \text{ measurable} \\ \wh \PP_X = \sum_{c=1}^C \widehat p_c \delta_{\widehat x_c}, \quad \wh \PP_{Y|\widehat x_c} \sim f(\cdot | \widehat \theta_c) \; \forall c, \end{array} \right. \end{equation} where $\widehat p$ is a $C$-dimensional probability vector containing non-zero elements summing up to 1, and $\widehat \theta_c \in \Theta$ for all $c$. The first equation indicates that the nominal measure $\wh \PP$ can be decomposed into a marginal distribution of the covariates $X$ and a collection of conditional measures of $Y$ given $X$ using the definition of the conditional probability measure ~\cite[Theorem~9.2.2]{ref:stroock2011probability}. The second line stipulates that the nominal marginal distribution $\wh \PP_X$ of the covariates is a discrete distribution supported on $\widehat x_c$, $c = 1, \ldots, C$. Moreover, for each $c$, the nominal conditional distribution of $Y$ given $X = \widehat x_c$ is a distribution in the exponential family with parameter $\widehat \theta_c$. Notice that the form of~$\wh \PP$ in~\eqref{eq:nominal} is chosen to facilitate the injection of parametric information $\widehat \theta_c$ into the nominal distribution, and it is also necessary to tie $\wh \PP$ to the MLE problem using the following notion of MLE-compatibility. \end{comment} \begin{definition}[MLE-compatible nominal distribution] \label{def:mle-compatible} A nominal distribution $\wh \PP$ of the form~\eqref{eq:nominal} is MLE-compatible with respect to the log-loss function $\ell_\lambda$ if the optimal solution $\widehat w = \arg \min_{w \in \mathcal W}~\mathds{E}_{\wh \PP}[ \ell_{\lambda}(X, Y, w)]$ coincides with the estimator $w_{MLE}$ that solves~\eqref{eq:MLE}. \end{definition} Definition~\ref{def:mle-compatible} indicates that $\wh \PP$ is compatible for the MLE problem if the MLE solution $w_{MLE}$ is recovered by solving problem~\eqref{eq:MLE2} where the expectation is now taken under $\wh \PP$. Therefore, MLE-compatibility implies that $\wh \PP$ and $\wh \PP^{\text{emp}}$ are equivalent in the MLE problem The next examples suggest two possible ways of calibrating an MLE-compatible $\wh \PP$ of the form~\eqref{eq:nominal}. \begin{example}[Compatible nominal distribution I] \label{ex:nominal-1} If $\wh \PP$ is chosen of the form~\eqref{eq:nominal} with $\widehat p_c = N_c/N$ and $\widehat \theta_c = (\nabla \Psi)^{-1}\big((N_c)^{-1} \sum_{\widehat x_i = \widehat x_c} T(\widehat y_i) \big)\in \Theta$ for all $c$, then $\wh \PP$ is MLE-compatible. \end{example} \begin{example}[Compatible nominal distribution II] \label{ex:nominal-2} If $\wh \PP$ is chosen of the form~\eqref{eq:nominal} with $\widehat p_c = N_c/N$ and $\widehat \theta_c = \lambda(w_{MLE}, \widehat x_c)$ for all $c$, where $w_{MLE}$ solves~\eqref{eq:MLE}, then $\wh \PP$ is MLE-compatible. \end{example} We now detail the choice of the dissimilarity measure which is used to construct the neighborhood surrounding the nominal measure $\wh \PP$. For this, we will use the Kullback-Leiber divergence. \begin{definition}[Kullback-Leibler divergence] \label{def:KL} Suppose that $\mbb P _1$ is absolutely continuous with respect to $\mbb P _2$, the Kullback-Leibler (KL) divergence from $\mbb P _1$ to $\mbb P _2$ is defined as $\mathrm{KL}(\mbb P _1 \parallel \mbb P _2) \triangleq \mathds{E}_{\mbb P _1} \left[ \log (\mathrm{d} \mbb P _1/\mathrm{d} \mbb P _2) \right]$, where $\mathrm{d} \mbb P _1/\mathrm{d} \mbb P _2$ is the Radon-Nikodym derivative of $\mbb P _1$ with respect to $\mbb P _2$. \end{definition} The KL divergence is an ideal choice in our setting for numerous reasons. Previously, DRO problems with a KL ambiguity set often result in tractable finite-dimensional reformulations~\cite{ref:bental2013robust, ref:hu2013kullback, ref:bertsimas2018datadriven}. More importantly, the manifold of exponential family of distributions equipped with the KL divergence inherits a natural geometry endowed by a dually flat and invariant Riemannian structure~\cite[Chapter~2]{ref:amari2016information}. Furthermore, the KL divergence between two distributions in the same exponential family admits a closed form expression~\cite{ref:banerjee2005clustering, ref:amari2016information}. \begin{lemma}[{KL divergence between distributions from exponential family}] \label{lemma:KL-exp-main} The KL divergence from $\mbb Q_1\!\sim\!f(\cdot | \theta_1)$ to $\mbb Q_2\!\sim\!f(\cdot|\theta_2)$ amounts to $\mathrm{KL} (\mbb Q_1 \parallel \mbb Q_2)\!=\!\inner{\theta_1 - \theta_2}{\nabla \Psi(\theta_1)} - \Psi(\theta_1) + \Psi(\theta_2). $ \end{lemma} Using the above components, we are now ready to introduce our ambiguity set $\mathbb B(\wh \PP)$ as \begin{equation} \label{eq:B-def} \mathbb B(\wh \PP)\!\triangleq\!\left\{ \mbb Q\!\in\!\mathcal M(\mathcal X\!\times\!\mathcal Y): \!\!\! \begin{array}{l} \exists \mbb Q_X \in \mathcal M(\mathcal X),~\exists\theta_c \in \Theta \text{ such that } \mbb Q_{Y| \widehat x_c} \sim f(\cdot | \theta_c) \quad \forall c \\ \mbb Q (\{\widehat x_c\} \times A)\!=\!\mbb Q_X(\{\widehat x_c\}) \mbb Q_{Y|\widehat x_c}(A) ~~ \forall c, \forall A \subseteq \mathcal Y~\text{measurable} \\ \mathrm{KL}(\mbb Q_{Y|\widehat x_c} \parallel \wh \PP_{Y|\widehat x_c}) \leq \rho_c \quad \forall c\\ \mathrm{KL}(\mbb Q_X \parallel \wh \PP_X) + \mathds{E}_{\mbb Q_X}[\sum_{c=1}^C \rho_c \mathbbm{1}_{\widehat x_c}(X)] \le \varepsilon \end{array} \right\} \end{equation} parametrized by a marginal radius $\varepsilon$ and a collection of the conditional radii $\rho_c$. Any distribution $\mbb Q \in \mathbb B(\wh \PP)$ can be decomposed into a marginal distribution $\mbb Q_X$ of the covariate and an ensemble of parametric conditional distributions $\mbb Q_{Y|\widehat x_c} \sim f(\cdot | \theta_c)$ at every event $X = \widehat x_c$. The first inequality in~\eqref{eq:B-def} restricts the parametric conditional distribution $\mbb Q_{Y|\widehat x_c}$ to be in the $\rho_c$-neighborhood from the nominal $\wh \PP_{Y|\widehat x_c}$ prescribed using the KL divergence, while the second inequality imposes a similar restriction for the marginal distribution $\mbb Q_X$. One can show that for any conditional radii $\rho \in \mathbb{R}_+^C$ satisfying $\sum_{c=1}^C \widehat p_c \rho_c \leq \varepsilon$, $\mathbb B(\wh \PP)$ is non-empty with $\wh \PP\!\in\!\mathbb B(\wh \PP)$. Moreover, if all $\rho$ and $\varepsilon$ are zero, then $\mathbb B(\wh \PP)$ becomes the singleton set $\{\wh \PP\}$ that contains only the nominal distribution. The set $\mathbb B(\wh \PP)$ is a \textit{parametric ambiguity set}: all conditional distributions $\mbb Q_{Y|\widehat x_c}$ belong to the same parametric exponential family, and at the same time, the marginal distribution $\mbb Q_X$ is absolutely continuous with respect to a discrete distribution $\wh \PP_X$ and hence $\mbb Q_X$ can be parametrized using a $C$-dimensional probability vector. At first glance, the ambiguity set $\mathbb B(\wh \PP)$ looks intricate and one may wonder whether the complexity of $\mathbb B(\wh \PP)$ is necessary. In fact, it is appealing to consider the ambiguity set \begin{equation} \label{eq:B} \mathcal B(\wh \PP)\!\triangleq\!\left\{ \mbb Q\!\in\!\mathcal M(\mathcal X\!\times\!\mathcal Y): \!\!\! \begin{array}{l} \exists \mbb Q_X \in \mathcal M(\mathcal X),~\exists\theta_c \in \Theta \text{ such that } \mbb Q_{Y| \widehat x_c} \sim f(\cdot | \theta_c) \quad \forall c \\ \mbb Q (\{\widehat x_c\} \times A) = \mbb Q_X(\{\widehat x_c\}) \mbb Q_{Y|\widehat x_c}(A)~\forall c, \forall A \subseteq \mathcal Y~\text{measurable}\\ \mathrm{KL}(\mbb Q\parallel \wh \PP) \le \varepsilon \end{array} \right\} \end{equation} which still preserves the parametric conditional structure and entails only one KL divergence constraint on the \textit{joint} distribution space. Unfortunately, the ambiguity set $\mathcal B(\wh \PP)$ may be overly conservative as pointed out in the following result. \begin{proposition} \label{prop:conservative} Denote momentarily the ambiguity sets~\eqref{eq:B-def} and~\eqref{eq:B} by $\mathbb B_{\varepsilon, \rho}(\wh \PP)$ and $\mathcal B_{\varepsilon}(\wh \PP)$ to make the dependence on the radii explicit. For any nominal distribution $\wh \PP$ of the form~\eqref{eq:nominal} and any radius $\varepsilon \in \mathbb{R}_{+}$, we have \[ \textstyle \mathcal B_\varepsilon(\wh \PP) = \bigcup_{\rho \in \mathbb{R}_+^C} \mathbb B_{\varepsilon, \rho}(\wh \PP). \] \end{proposition} Proposition~\ref{prop:conservative} suggests that the ambiguity set $\mathcal B(\wh \PP)$ can be significantly bigger than $\mathbb B(\wh \PP)$, and that the solution of the distributionally robust MLE problem~\eqref{eq:dro} with $\mathbb B(\wh \PP)$ being replaced by $\mathcal B(\wh \PP)$ is potentially too conservative and may lead to undesirable or uninformative results. The ambiguity set $\mathbb B(\wh \PP)$ requires $1+C$ parameters, including one marginal radius $\varepsilon$ and $C$ conditional radii $\rho_c$, $c= 1,\ldots, C$, which may be cumbersome to tune in the implementation. Fortunately, by the asymptotic result in Lemma~\ref{lemma:asymptotic-joint}, the set of radii $\rho_c$ can be tuned simultaneously using the same scaling rate, which will significantly reduce the computational efforts for parameter tuning. \section{Tractable Reformulation} \label{sect:refor} We devote this section to study the solution method for the min-max problem~\eqref{eq:dro} by transforming it into a finite dimensional minimization problem. To facilitate the exposition, we denote the ambiguity set for the conditional distribution of $Y$ given $X = \widehat x_c$ as \begin{equation} \label{eq:cond-ambi} \mathbb B_{Y|\widehat x_c} \triangleq \left\{ \mbb Q_{Y|\widehat x_c} \in \mathcal M(\mathcal Y): \exists \theta \in \Theta,~\mbb Q_{Y|\widehat x_c}(\cdot) \sim f(\cdot | \theta),~\mathrm{KL}(\mbb Q_{Y|\widehat x_c} \parallel \wh \PP_{Y|\widehat x_c}) \leq \rho_c \right\}. \end{equation} As a starting point, we first show the following decomposition of the worst-case expected loss under the ambiguity set $\mathbb B(\wh \PP)$ for any measurable loss function. \begin{proposition}[Worst-case expected loss] \label{prop:refor} Suppose that~$\mathbb B(\wh \PP)$ is defined as in~\eqref{eq:B-def} for some $\varepsilon \in \mathbb{R}_+$ and $\rho \in \mathbb{R}_+^C$ such that $\sum_{c=1}^C \widehat p_c \rho_c \le \varepsilon$. For any function $L: \mathcal X \times \mathcal Y \to \mathbb{R}$ measurable, we have \[ \sup\limits_{\mbb Q \in \mathbb B(\wh \PP)} \mathds{E}_{\mbb Q}\left[ L(X, Y) \right] = \left\{ \begin{array}{cl} \inf & \alpha + \beta \varepsilon + \beta \displaystyle \textstyle\sum_{c=1}^C \widehat p_c \exp\left( \beta^{-1}(t_c - \alpha) - \rho_c - 1\right) \\ \st & t \in \mathbb{R}^C,\; \alpha \in \mathbb{R},\;\beta \in \mathbb{R}_{++} \\ & \sup\limits_{\mbb Q_{Y|\widehat x_c} \in \mathbb B_{Y|\widehat x_c}} \mathds{E}_{\mbb Q_{Y|\widehat x_c}} \left[ L(\widehat x_c, Y)\right] \leq t_c \quad \forall c =1, \ldots, C. \end{array} \right. \] \end{proposition} Proposition~\ref{prop:refor} leverages the decomposition structure of the ambiguity set $ \mathbb B(\wh \PP)$ to reformulate the worst-case expected loss into an infimum problem that involves $C$ constraints, where each constraint is a hypergraph reformulation of a worst-case conditional expected loss under the ambiguity set $\mathbb B_{Y|\widehat x_c}$. Proposition~\ref{prop:refor} suggests that to reformulate the min-max estimation problem~\eqref{eq:dro}, it suffices now to reformulate the worst-case conditional expected log-loss \begin{equation} \label{eq:inner} \sup\limits_{\mbb Q_{Y|\widehat x_c} \in \mathbb B_{Y|\widehat x_c}} \mathds{E}_{\mbb Q_{Y|\widehat x_c}} \left[\ell_\lambda(\widehat x_c, Y, w ) \right] \end{equation} for each value of $\widehat x_c$ into a dual infimum problem. Using Lemma~\ref{lemma:KL-exp-main}, one can rewrite $\mathbb B_{Y|\widehat x_c}$ in \eqref{eq:cond-ambi} using the natural parameter representation as \[ \mathbb B_{Y|\widehat x_c}\!=\!\left\{ \mbb Q_{Y|\widehat x_c} \!\in\!\mathcal M(\mathcal Y)\!:\!\exists \theta \in \Theta,\mbb Q_{Y|\widehat x_c}(\cdot)\!\sim\!f(\cdot | \theta),\inner{\theta - \widehat \theta_c}{\nabla \Psi(\theta)} - \Psi(\theta) + \Psi(\widehat \theta_c) \leq \rho_c \right\}. \] Since $\Psi$ is convex~\cite[Lemma~1]{ref:banerjee2005clustering}, it is possible that $\mathbb B_{Y|\widehat x_c}$ is represented by a non-convex set of natural parameters and hence reformulating~\eqref{eq:inner} is non-trivial. Surprisingly, the next proposition asserts that problem~\eqref{eq:inner} always admits a convex reformulation. \begin{proposition}[Worst-case conditional expected log-loss] \label{prop:conditional-refor} For any $\widehat x_c \in \mathcal X$ and $w \in \mathcal W$, the worst-case conditional expected log-loss~\eqref{eq:inner} is equivalent to the univariate convex optimization problem \begin{equation} \label{eq:inner-refor} \inf\limits_{\gamma_c \in \mathbb{R}_{++}}~\gamma_c \big(\rho_c - \Psi(\widehat \theta_c) \big) + \gamma_c \Psi\big(\widehat \theta_c - \gamma_c^{-1}\lambda(w, \widehat x_c) \big) + \Psi\big(\lambda(w, \widehat x_c)\big). \end{equation} \end{proposition} A reformulation for the worst-case conditional expected log-loss was proposed in~\cite{ref:hu2013kullback}. Nevertheless, the results in~\cite[Section~5.3]{ref:hu2013kullback} requires that the sufficient statistics $T(y)$ is a linear function of $y$. The reformulation~\eqref{eq:inner-refor}, on the other hand, is applicable when $T$ is a \textit{non}linear function of $y$. Examples of exponential family of distributions with nonlinear $T$ are (multivariate) Gaussian, Gamma and Beta distributions. The results from Propositions~\ref{prop:refor} and \ref{prop:conditional-refor} lead to the reformulation of the distributionally robust estimation problem~\eqref{eq:dro}, which is the main result of this section. \begin{theorem}[Distributionally robust MLE reformulation] \label{thm:main} The distributionally robust MLE problem~\eqref{eq:dro} is tantamount to the following finite dimensional optimization problem \begin{equation} \label{eq:refor} \begin{array}{cll} \inf & \alpha + \beta \varepsilon + \beta \displaystyle \textstyle \sum_{c=1}^C \widehat p_c \exp( \beta^{-1}(t_c - \alpha) - \rho_c - 1 ) \\ \st & w \in \mathcal W,\; \alpha \in \mathbb{R},\;\beta \in \mathbb{R}_{++},\;\gamma\in \mathbb{R}_{++}^C,\; t \in \mathbb{R}^C \\[1ex] & \gamma_c \big(\rho_c - \Psi(\widehat \theta_c) \big) + \gamma_c \Psi\big( \widehat \theta_c - \gamma_c^{-1}\lambda(w, \widehat x_c) \big) + \Psi \big(\lambda(w, \widehat x_c) \big) \leq t_c & \forall c =1, \ldots, C. \end{array} \end{equation} In generalized linear models with $\lambda: (w, x) \mapsto w^\top x$ and $\mathcal W$ being convex, problem~\eqref{eq:refor} is convex. \end{theorem} Below we show how the Poisson and logistic regression models fit within this framework. \begin{example}[Poisson counting model] \label{ex:poisson} The Poisson counting model with the ground measure $\nu$ being a counting measure on $\mathcal Y = \mathbb N$, the sufficient statistic $T(y)=y$, the natural parameter space $\Theta = \mathbb{R}$ and the log-partition function $\Psi(\theta) = \exp(\theta)$. If $\lambda (w, x) = w^\top x$, we have \[ Y | X = x \sim \mathrm{Poisson} \big(w_0^\top x \big), \qquad \mbb P (Y = k | X = x) = (k!)^{-1}\exp(kw_0^\top x-e^{w_0^\top x}). \] The distributionally robust MLE is equivalent to the following convex optimization problem \begin{equation} \label{eq:Poisson:refo:exp} \begin{array}{cll} \inf & \alpha + \beta \varepsilon + \beta \displaystyle \textstyle\sum_{c =1}^C \widehat p_c \exp\left( \beta^{-1}(t_c - \alpha) - \rho_c - 1 \right)\\ \st & w \in \mathcal W,\; \alpha \in \mathbb{R},\; \beta \in \mathbb{R}_{++},\;\gamma \in \mathbb{R}_{++}^C, \; t \in \mathbb{R}^C \\[1ex] & \gamma_c \big( \rho_c - \exp( \widehat \theta_c) \big) + \gamma_c \exp\big(\widehat \theta_c -w^\top \widehat x_c/\gamma_c \big) + \exp\big(w^\top \widehat x_c\big) \le t_c & \forall c = 1, \ldots, C. \end{array} \end{equation} \end{example} \begin{example}[Logistic regression] The logistic regression model is specified with $\nu$ being a counting measure on $\mathcal Y = \{0, 1\}$, the sufficient statistic $T(y)=y$, the natural parameter space $\Theta = \mathbb{R}$ and the log-partition function $\Psi(\theta) = \log\big(1+ \exp(\theta)\big)$. If $\lambda(w, x) = w^\top x$, we have \[ Y | X = x \sim \mathrm{Bernoulli} \big((1+\exp(-w_0^\top x))^{-1} \big), \qquad \mbb P (Y = 1 | X = x) = (1+\exp(-w_0^\top x))^{-1}. \] The distributionally robust MLE is equivalent to the following convex optimization problem \begin{equation}\label{eq:Logistic:refo:exp} \begin{array}{cl} \inf & \alpha + \beta \varepsilon + \beta \displaystyle \textstyle\sum_{c =1}^C \widehat p_c \exp\left(\beta^{-1} (t_c - \alpha) - \rho_c - 1 \right)\\ \st & w \in \mathcal W,\; \alpha \in \mathbb{R},\; \beta \in \mathbb{R}_{++},\;\gamma \in \mathbb{R}_{++}^C, \; t \in \mathbb{R}^C \\[1ex] & \gamma_c \big( \rho_c \!-\! \log(1\!+\!\exp(\widehat \theta_c)) \big) \!+\!\gamma_c \log\big(1\!+\!\exp(\widehat \theta_c \!-\! w^\top \widehat x_c/\gamma_c) \big)\!+ \!\log\big(1\!+\!\exp(w^\top \widehat x_c)\big)\!\le\!t_c ~ \forall c. \end{array} \end{equation} \end{example} Problems~\eqref{eq:Logistic:refo:exp} and~\eqref{eq:Poisson:refo:exp} can be solved by exponential conic solvers such as ECOS~\cite{domahidi2013ecos} and MOSEK~\cite{mosek}. \section{Theoretical Analysis} \label{sect:analysis} In this section, we provide an in-depth theoretical analysis of our estimator. We first show that our proposed estimator is tightly connected to several existing regularization schemes. \begin{proposition}[Connection to the adversarial reweighting scheme] \label{prop:reweighting} Suppose that $\widehat x_i$ are distinct and $\rho_c = 0$ for any $c = 1, \ldots, N$. If $\wh \PP$ is of the form~\eqref{eq:nominal} and chosen according to Example~\ref{ex:nominal-1}, then the distributionally robust estimation problem~\eqref{eq:dro} is equivalent to \begin{equation} \notag \min\limits_{w \in \mathcal W}~\sup\limits_{\mbb Q: \mathrm{KL}(\mbb Q \parallel \wh \PP^{\mathrm{emp}}) \le \varepsilon} \mathds{E}_{\mbb Q}[ \ell_\lambda(X, Y, w)]. \end{equation} \end{proposition} Proposition~\ref{prop:reweighting} asserts that by setting the conditional radii to zero, we can recover the robust estimation problem where the ambiguity set is a KL ball around the empirical distribution $\wh \PP^{\text{emp}}$, which has been shown to produce the adversarial reweighting effects~\cite{li2019comparing,ref:bertsimas2018datadriven}. Recently, it has been shown that distributionally robust optimization using $f$-divergences is statistically related to the variance regularization of the empirical risk minimization problem~\cite{ref:namkoong2017variance}. Our proposed estimator also admits a variance regularization surrogate, as asserted by the following proposition. \begin{proposition}[Variance regularization surrogate] \label{prop:surrogate} Suppose that $\Psi$ has locally Lipschitz continuous gradients. For any fixed $\widehat \theta_c \in \Theta$, $c=1,\ldots,C$, there exists a constant $m>0$ that depends only on $\Psi$ and $\widehat \theta_c$, $c=1, \ldots, C$, such that for any $w \in \mathcal W$ and $\varepsilon \ge \sum_{c = 1}^C \widehat p_c \rho_c$, we have \[ \sup_{\mbb Q \in \mathbb B(\wh \PP)} \mathds{E}_{\mbb Q}[\ell_\lambda(X, Y, w)] \le \mathds{E}_{\wh \PP}[\ell_\lambda(X, Y, w)] + \kappa_1\sqrt{\mathrm{Var}_{\wh \PP}\left(\ell_\lambda(X, Y, w ) \right)} + \kappa_2 \| \lambda(w, \widehat x_c) \|_2, \] where $\kappa_1 = \sqrt{2\varepsilon}/(\min_{c}\sqrt{\widehat p_c})$ and $\kappa_2= \sqrt{2\max_{c}\rho_c/m}$. \end{proposition} One can further show that for sufficiently small $\rho_c$, the value of $m$ is proportional to the inverse of the local Lipschitz constant of $\nabla \Psi$ at $\widehat \theta_c$, in which case $\kappa_2$ admits an explicit expression (see Appendix~\ref{sec:app-aux}). Next, we show that our robust estimator is also consistent, which is a highly desirable statistical property. \begin{theorem}[Consistency] \label{thm:consistency} Assume that $w_0$ is the unique solution of the problem $\min_{w\in\mathcal W}\mathds{E}_{\mbb P }\left[\ell_{\lambda}(X,Y,w)\right]$, where $\mbb P $ denotes the true distribution. Assume that $\mathcal{X}$ has finite cardinality, $\Theta=\mathbb{R}^p$, $\Psi$ has locally Lipschitz continuous gradients, and $\ell_\lambda(x,y,w)$ is convex in $w$ for each $x$ and $y$. If $\widehat \theta_c \xrightarrow{p.} \lambda(w_0, \widehat x_c)$ for each $c$, $\varepsilon\to0,\rho_c\to0$ and $\varepsilon\geq \sum_{c=1}^C\widehat p_c\rho_c$ with probability going to $1$, then the distributionally robust estimator $w^\star$ that solves~\eqref{eq:dro} exists with probability going to $1$, and $w^\star\xrightarrow{p.} w_0$. \end{theorem} One can verify that choosing $\widehat \theta_c$ using Examples~\ref{ex:nominal-1} and~\ref{ex:nominal-2} will satisfy the condition $\widehat \theta_c \xrightarrow{p.} \lambda(w_0, \widehat x_c)$, and as a direct consequence, choosing $\wh \PP$ following these two examples will result in a consistent estimator under the conditions of Theorem~\ref{thm:consistency}. We now consider the asymptotic scaling rate of $\rho_c$ as the number $N_c$ of samples with the same covariate $\widehat x_c$ tends to infinity. Lemma~\ref{lemma:asymptotic-joint} below asserts that $\rho_c$ should scale at the rate $N_c^{-1}$. Based on this result, we can set $\rho_c = a N_c^{-1}$ for all $c$, where $a > 0$ is a tuning parameter. This reduces significantly the burden of tuning $\rho_c$ down to tuning a single parameter $a$. \begin{lemma}[Joint asymptotic convergence] \label{lemma:asymptotic-joint} Suppose that $| \mathcal X | = C$ with $\mathbb P(X = \widehat x_c) > 0$. Let $\theta_c = \lambda(w_0, \widehat x_c)$ and $\widehat{\mathbb P}$ be defined as in Example~2.2. Let $V_c=D_c \mathrm{Cov}_{f(\cdot|\theta_c)}(T(Y))D_c^\top$, where $ D_c= J (\nabla \Psi)^{-1}( \mathds E_{f(\cdot|\theta_c)}[T(Y)]) $ and $J$ denotes the Jacobian operator. Then the following joint convergence holds \vspace{-1.3mm} \begin{equation}\label{eq:jointcon} \big(N_1\times\mathrm{KL}(f(\cdot |\theta_1)\parallel f(\cdot |\widehat\theta_1)), \ldots, N_C\times \mathrm{KL}(f(\cdot|\theta_C)\parallel f(\cdot|\widehat\theta_C))\big)^\top \xrightarrow{d.} Z \qquad \text{as}\qquad N\to\infty, \end{equation} where $Z = (Z_1,\ldots, Z_C)^\top$ with $Z_c = \frac{1}{2}R_c^\top\nabla^2\Psi(\theta_c)R_c$, $R_c$ are independent and $R_c\sim\mathcal N(0,V_c)$. \end{lemma} Assuming $w_{MLE}$ that solves~\eqref{eq:MLE} is asymptotically normal with square-root convergence rate, we remark that the asymptotic joint convergence~\eqref{eq:jointcon} also holds for $\wh \PP$ in Example~\ref{ex:nominal-2}, though in this case the limiting distribution $Z$ takes a more complex form that can be obtained by the delta method. Finally, we study the structure of the worst-case distribution $\mbb Q^\star = \arg\max_{\mbb Q \in \mathbb B(\wh \PP)} \mathds{E}_{\mbb Q} \big[ \ell_\lambda(X, Y, w )\big] $ for any value of input $w$. This result explicitly quantifies how the adversary will generate the adversarial distribution adapted to any estimate $w$ provided by the statistician. \begin{theorem}[Worst-case joint distribution] \label{thm:extreme} Given $\rho \in \mathbb{R}_+^C$ and $\varepsilon \in \mathbb{R}_+$ such that $\sum_{c=1}^C \widehat p_c \rho_c \le \varepsilon$. For any $w$ and $c=1,\ldots,C$, let $\mbb Q_{Y|\widehat x_c}^\star \sim f(\cdot | \theta_c^\star)$ with $\theta_c^\star = \widehat \theta_c - \lambda(w, \widehat x_c)/\gamma_c^\star$, where $\gamma_c^\star > 0$ is the solution of the nonlinear equation \begin{equation} \nota \Psi\big( \widehat \theta_c - \gamma^{-1}\lambda(w, \widehat x_c) \big) + \gamma^{-1} \inner{\nabla \Psi\big(\widehat \theta_c - \gamma^{-1} \lambda(w, \widehat x_c) \big)}{\lambda(w, \widehat x_c)} = \Psi(\widehat \theta_c) - \rho_c, \end{equation} and let $t_c^\star = \Psi(\lambda(w, \widehat x_c)) - \inner{\nabla \Psi(\theta_c^\star)}{\lambda(w, \widehat x_c)}$. Let $\alpha^\star \in \mathbb{R}$ and $\beta^\star \in \mathbb{R}_{++}$ be the solution of the following system of nonlinear equations \begin{subequations} \begin{align*} \textstyle\sum_{c=1}^C \widehat p_c \exp \big( \beta^{-1}(t_c^\star - \alpha) - \rho_c - 1 \big) - 1 &= 0 \\ \textstyle\sum_{c=1}^C \widehat p_c (t_c^\star - \alpha) \exp \big( \beta^{-1}(t_c^\star - \alpha) - \rho_c - 1 \big) - (\varepsilon + 1) \beta &= 0, \end{align*} then the worst-case distribution is $\mbb Q^\star = \sum_{c=1}^C \widehat p_c \exp\big( (\beta^\star)^{-1}(t_c^\star - \alpha^\star) - \rho_c -1 \big) \delta_{\widehat x_c} \otimes \mbb Q_{Y|\widehat x_c}^\star$. \end{subequations} \end{theorem} Notice that $\mbb Q^\star$ is decomposed into a worst-case marginal distribution of $X$ supported on $\widehat x_c$ and a collection of worst-case conditional distributions $\mbb Q^\star_{Y|\widehat x_c}$. \section{Numerical Experiments} \begin{figure}[t] \centering \scalebox{0.44}{ \includegraphics{Poisson_OutOfSampleLogLoss_SyntheticData_final.eps}} \caption{Median (solid blue line) and the 10th-90th percentile region (shaded) of out-of-sample divergence loss collected from 100 independent runs.} \label{fig:1} \end{figure} \begin{table}[t] \centering \def1{1} \begin{tabular}{|c|c|c|c|c|} \hline && $N= 50$ & $N = 100$ & $N= 500$\\ \hline &100(\text{DRO}-\text{MLE})/\text{MLE} & $-69.84\pm3.33\%$& $-52.66\pm3.98\%$ & $-22.25\pm4.11\%$\\ $\text{CI}_{95\%}$ &$100(\text{DRO}-L_1)/L_1$ & $-22.59\pm4.02\%$ & $-19.90\pm4.16\%$& $-13.20\pm3.38\%$ \\ &$100(\text{DRO}-L_2)/L_2$ & $-14.98\pm4.08\%$ & $-9.98\pm4.14\%$& $-5.62\pm 2.83\%$\\ \hline \multirow{4}{3.5em}{$\text{CVaR}_{5\%}$} & MLE & 0.4906 & 0.1651&0.0246\\ & {$L_1$} & 0.0967 &0.0742&0.0195\\ & {$L_2$} & 0.0894 &0.0692&0.0176\\ & {DRO} & 0.0547 &0.0518&0.0172\\ \hline \end{tabular} \caption{Comparison between the DRO estimator with the other methods. Lower values are better. } \label{table2} \vspace{-6mm} \end{table} We now showcase the abilities of the proposed framework in the distributionally robust Poisson and logistic regression settings using a combination of simulated and empirical experiments. All optimization problems are modeled in MATLAB using CVX~\cite{cvx} and solved by the exponential conic solver MOSEK~\cite{mosek} on an Intel i7 CPU (1.90GHz) computer. Optimization problems \eqref{eq:Poisson:refo:exp} and \eqref{eq:Logistic:refo:exp} are solved in under 3 seconds for all instances both in the simulated and empirical experiments. The MATLAB code is available at \url{https://github.com/angelosgeorghiou/DR-Parametric-MLE}. \subsection{Poisson Regression} We will use simulated experiments to demonstrate the behavior of the tuning parameters and to compare the performance of our estimator with regard to other established methods. We assume that the true distribution $\mathbb{P}$ is discrete, the $10$-dimensional covariate $X$ is supported on $K = 100$ points and their locations $\widehat x_k$ are generated i.i.d.~using a standard normal distribution. We then generate a $K$-dimensional vector whose components are i.i.d.~uniform over $M_k\in[0, 10000]$, then normalize it to get the probability vector $p_k = M_k/M$ of the true marginal distribution of $X$. The value $w_0$ that determines the true conditional distribution $\mbb P _{Y|X}$ via the generative model~\eqref{eq:model} is assigned to $w_0 = \tilde w/ \| \tilde w\|_1$, where $\tilde w$ is drawn randomly from a 10-dimensional standard normal distribution. Our experiment comprises 100 simulation runs. In each run we generate $N\in \{50,100,500\}$ training samples i.i.d.~from $\mbb P $ and use the MLE-compatible nominal distribution $\wh \PP$ of the form~\eqref{eq:nominal} as in Example~\ref{ex:nominal-2}. We calibrate the regression model \eqref{eq:Poisson:refo:exp} by tuning $\rho_c = a N_c^{-1}$ with $a\in[10^{-4},1]$ and $\varepsilon\in [\sum_{c=1}^C \widehat p_c \rho_c,1]$, both using a logarithmic scale with 20 discrete points. The quality of an estimate $w^\star$ with respect to the true distribution $\mbb P $ is evaluated by the out-of-sample divergence loss \begin{equation} \notag \notag \mathds{E}_{\mbb P _X}[\mathrm{KL}(\mbb P _{Y|X} \parallel \mbb Q_{w^\star, Y|X})] = \textstyle\sum_{k=1}^{K} p_k \big( \exp(w_0^\top \widehat x_k) \big( (w_0-w^\star)^\top \widehat x_k - 1 \big) + \exp(\widehat x_k^\top w^\star) \big). \end{equation} In the first numerical experiment, we fix the marginal radius $\varepsilon=1$ and examine how tuning the conditional radii $\rho_c$ can improve the quality of the estimator. Figure~\ref{fig:1} shows the 10th, 50th and 90th percentile of the out-of-sample divergence for different samples sizes. If the constant $a$ is chosen judiciously, incorporating the uncertainty in the conditional distribution can reduce the out-of-sample divergence loss by $17.65\%$, $10.55\%$ and $1.82\%$ for $N = 50, 100$ and $500$, respectively. Next, we compare the performance of our proposed estimator to the $w_{MLE}$ that solves~\eqref{eq:MLE} and the 1-norm ($L_1$) and 2-norm ($L_2$) MLE regularization, where the regularization weight takes values in $[10^{-4},1]$ on the logarithmic scale with 20 discrete points. In each run, we choose the optimal parameters that give the lowest of out-of-sample divergence for each method, and construct the empirical distribution of the out-of-sample divergence collected from 100 runs. Table~\ref{table2} reports the 95\% confidence intervals of $100(\text{DRO}-\text{MLE})/\text{MLE}$, $100(\text{DRO}-L_1)/L_1$ and $100(\text{DRO}-L_2)/L_2$, as well as the 5\% Conditional Value-at-Risk (CVaR). Our approach delivers lower out-of-sample divergence loss compared to the other methods, and additionally ensures a lower value of CVaR for all sample sizes. This improvement is particularly evident in small sample sizes. \begin{table}[h] \centering \resizebox{1\columnwidth}{!}{ \begin{tabular}{|l|c|c|c|c|c||c|c|c|c|c|} \hline &\multicolumn{5}{c||}{AUC}&\multicolumn{5}{|c|}{CCR}\\ \hline Dataset & DRO & KL & $L_1$ & $L_2$ & MLE & DRO & KL & $L_1$ & $L_2$ & MLE \\ \hline australian ($N=690,\,n = 14$) & \textbf{92.74} & 92.62 & 92.73 & 92.71 & 92.61 & \textbf{85.75} & 85.72 & 85.52 & 85.60 & 85.72 \\ banknote ($N=1372,\,n = 4$) & \textbf{98.46} & \textbf{98.46} & 98.43 & 98.45 & 98.45 & 94.31 & 94.32 & 94.16 & \textbf{94.35} & 94.32 \\ climate ($N=540,\,n=18$) & 94.30 & 82.77 & \textbf{94.85} & 94.13 & 82.76 & \textbf{95.04} & 93.89 & 94.85 & 94.83 & 93.89 \\ german ($N=1000,n=19$) & \textbf{75.75} & 75.68 & 75.74 & 75.74 & 75.67 & 73.86 & \textbf{74.05} & 73.82 & 73.70 & \textbf{74.05} \\ haberman ($N=306,n=3$) & 66.86 & 67.21 & \textbf{69.19} & 68.17 & 67.20 & \textbf{73.83} & 73.80 & 73.20 & 73.18 & 73.80 \\ housing ($N=506,\,n=13$) & \textbf{76.24} & 75.73 & 75.37 & 75.57 & 75.73 & 91.65 & 91.70 & \textbf{92.68} & 92.65 & 91.70 \\ ILPD ($N=583,\,n=10$) & \textbf{74.01} & 73.66 & 73.56 & 73.77 & 73.66 & 71.11 & 71.07 & 71.68 & \textbf{71.79} & 71.07 \\ mammo. ($N=830\,n = 5$) & \textbf{87.73} & 87.72 & 87.70 & 87.68 & 87.71 & 81.00 & \textbf{81.20} & 80.99 & 80.94 & \textbf{81.20} \\ \hline \end{tabular} } \caption{Average area under the curve (AUC) and correct classification rates (CCR) on UCI datasets ($m = 1$). } \label{table:datasets} \end{table} \vspace{-2mm} \subsection{Logistic Regression} We now study the performance of our proposed estimation in a classification setting using data sets from the UCI repository~\cite{Dua:2019}. We compare four different models: our proposed DRO estimator~\eqref{eq:Logistic:refo:exp}, the $w_{MLE}$ that solves~\eqref{eq:MLE}, the 1-norm ($L_1$) and 2-norm ($L_2$) MLE regularization. In each independent trial, we randomly split the data into train-validation-test set with proportion 50\%-25\%-25\%. For our estimator, we calibrate the regression model \eqref{eq:Logistic:refo:exp} by tuning $\rho_c = a N_c^{-1}$ with $a\in[10^{-4},10]$ using a logarithmic scale with 10 discrete points and setting $\varepsilon=2\sum_{c=1}^C \widehat p_c \rho_c$. Similarly, for the $L_1$ and $L_2$ regularization, we calibrate the regularization weight from $[10^{-4},1]$ on the logarithmic scale with 10 discrete points. Leveraging Proposition~\ref{prop:reweighting}, we also compare our approach versus the DRO \textit{non}parametric Kullback-Leibler (KL) MLE by setting $\rho_c = 0$ and tune only with $\varepsilon \in [10^{-4}, 10]$ with 10 logarithmic scale points. The performance of the methods was evaluated on the testing data using two popular metrics: the correct classification rate (CCR) with a threshold level of 0.5, and the area under the receiver operating characteristics curve (AUC). Table~\ref{table:datasets} reports the performance of each method averaged over 100 runs. One can observe that our estimator performs reasonably well compared to other regularization techniques in both performance metrics. \begin{remark}[Uncertainty in $\widehat x_c$] The absolute continuity condition of the KL divergence implies that our proposed model cannot hedge against the error in the covariate $\widehat x_c$. It is natural to ask which model can effectively cover this covariate error. Unfortunately, answering this question needs to overcome to technical difficulties: first, the log-partition function $\Psi$ is convex; second, the there are multiplicative terms between $X$ and $Y$ in the objective function. Maximizing over the $X$ space to find the worst-case covariate is thus difficult. Alternatively, one can think of perturbing each $\widehat x_c$ in a finite set but this approach will lead to trivial modifications of the constraints of problem~\eqref{eq:refor}. \end{remark} \begin{comment} \begin{table}[ht] \centering \def1{1} \begin{tabular}{|c|c|c|c|c|} \hline &MLE & $L_1$ & $L_2$ & DRO\\ \hline CI min logloss & $0.0879\pm0.0122$ & $0.0552\pm0.0045$& $0.0434\pm0.0036$ & $0.0409 \pm 0.0033$\\ CVaR 95\% min logloss & $0.2966$ & $0.1163$ & $0.0896$ & $0.0826$\\ \hline \end{tabular} \end{table} \begin{table}[ht] \centering \def1{1} \begin{tabular}{|c|c|c|c|} \hline & CI min logloss & CI CCR & CI AUC\\ \hline (DRO - MLE)/MLE & $-0.4433\pm 0.0469$ & $0.0075\pm0.0013$ & $0.0067\pm0.0015$\\ (DRO - $L_1$)/$L_1$ & $-0.2449\pm0.0317$ & $0.0067\pm0.0013$& $0.0058\pm0.0012$ \\ (DRO - $L_2$)/$L_2$ &$-0.0392\pm0.0340$ & $0.0041\pm0.0015$& $0.0012\pm0.0017$\\ \hline \end{tabular} \end{table} \end{comment} \paragraph{\bf Acknowledgments.} Material in this paper is based upon work supported by the Air Force Office of Scientific Research under award number FA9550-20-1-0397. Additional support is gratefully acknowledged from NSF grants 1915967, 1820942, 1838676 and from the China Merchant Bank. \newpage
{'timestamp': '2020-10-13T02:24:49', 'yymm': '2010', 'arxiv_id': '2010.05321', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05321'}
arxiv